# The primary config for Qtile on TileOS

from libqtile import bar, hook, layout, widget
from libqtile.config import Group, Key, Match, Screen
from libqtile.lazy import lazy
# Make sure 'qtile-extras' is installed or this config will not work.
from qtile_extras import widget
from qtile_extras.widget.decorations import BorderDecoration
from libqtile.backend.wayland import InputConfig
from keybindings import mod, keys, terminal
from mouse import mouse
import colors
import os
import subprocess

groups = []
group_names = ["1", "2", "3", "4", "5", "6", "7", "8", "9",]
group_labels = ["1", "2", "3", "4", "5", "6", "7", "8", "9",]

group_layouts = ["monadtall", "monadtall", "monadtall", "monadtall", "monadtall", "monadtall", "monadtall", "monadtall", "monadtall"]

@hook.subscribe.startup
def autostart():
   home = os.path.expanduser('~/.config/qtile/autostart.sh')
   subprocess.Popen([home])

for n in range(len(group_names)):
    groups.append(
        Group(
            name=group_names[n],
            layout=group_layouts[n].lower(),
            label=group_labels[n],
        ))

for i in groups:
    keys.extend(
        [
            # mod1 + letter of group = switch to group
            Key(
                [mod],
                i.name,
                lazy.group[i.name].toscreen(),
                desc="Switch to group {}".format(i.name),
            ),
            # mod1 + shift + letter of group = move focused window to group
            Key(
                [mod, "shift"],
                i.name,
                lazy.window.togroup(i.name, switch_group=False),
                desc="Move focused window to group {}".format(i.name),
            ),
        ]
    )

qtile_colors = colors.Macchiato

# Common settings for all layouts
layout_theme = {"border_width": 2,
                "margin": 8,
                "border_focus": qtile_colors[11],
                "border_normal": qtile_colors[15]
                }

layouts = [
    layout.Columns(**layout_theme),
    layout.Max(border_width = 0, margin = 0),
    layout.Stack(**layout_theme, num_stacks=2),
    # layout.Bsp(),
    # layout.Matrix(),
    layout.MonadTall(**layout_theme),
    # layout.MonadWide(),
    # layout.RatioTile(),
    layout.RatioTile(**layout_theme),
    # layout.TreeTab(),
    # layout.VerticalTile(),
    layout.Floating(**layout_theme),
    layout.Zoomy(**layout_theme),
    layout.TreeTab(
         font = "Noto Sans",
         fontsize = 12,
         sections = ["FIRST", "SECOND", "THIRD", "FOURTH"],
         section_fontsize = 12,
         border_width = 2,
         padding_left = 0,
         padding_x = 0,
         padding_y = 5,
         section_top = 10,
         section_bottom = 20,
         level_shift = 8,
         vspace = 3,
         panel_width = 200,
         bg_color = "181926",
         active_bg = "8aadf4",
         active_fg = "000000",
         inactive_bg = "a5adcb",
         inactive_fg = "181926"
    ),
]

# Common settings for all widgets
widget_defaults = dict(
    font="Noto Sans",
    fontsize=14,
    padding=2,
    background=qtile_colors[22]
)

extension_defaults = widget_defaults.copy()

screens = [
    Screen(
        top=bar.Bar(
            [
                widget.Image(
                    filename="~/.config/qtile/icons/logo.png",
                    margin = 3,
                    mouse_callbacks={'Button1': lazy.spawn('nwg-drawer')}
                ),
                widget.GroupBox(
                    fontsize = 14,
                    margin_y = 3,
                    margin_x = 4,
                    padding_y = 2,
                    padding_x = 3,
                    borderwidth = 3,
                    active = qtile_colors[13],
                    inactive = qtile_colors[13],
                    rounded = False,
                    highlight_color = qtile_colors[21],
                    highlight_method = "line",
                    urgent_border = qtile_colors[4],
                    urgent_text = qtile_colors[4],
                    this_current_screen_border = qtile_colors[10],
                ),
                widget.Sep(
                 linewidth=1,
                 padding=10,
                 foreground=qtile_colors[13],
                 background=qtile_colors[22]
                ),
                widget.CurrentLayout(
                    foreground = qtile_colors[13],
                    background=qtile_colors[22],
                    padding = 5,
                    scale=0.7
                ),
                widget.Sep(
                 linewidth=1,
                 padding=10,
                 foreground=qtile_colors[13],
                 background=qtile_colors[22]
                ),
                widget.Spacer(length = 8),
                widget.Prompt(),
                widget.WindowName(
                    foreground = qtile_colors[13],
                    max_chars = 40,
                ),
                widget.Spacer(length = 8),
                widget.StatusNotifier(
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[1],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                ),
                widget.Spacer(length = 8),
                widget.Mpris2(
                    playing_text = "",
                    paused_text = "",
                    foreground = qtile_colors[2],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[2],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                ),
                widget.Spacer(length = 8),
                widget.KeyboardLayout(
                    configured_keyboards = [
                        "us"
                    ],
                    font = "Noto Sans",
                    fontsize = "14",
                    fmt = '⌨  {}',
                    foreground = qtile_colors[3],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[3],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                ),
                widget.Spacer(length = 8),
                # Custom clipboard manager widget, based on Cliphist
                widget.TextBox(
                    text="",
                    foreground = qtile_colors[4],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[4],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={"Button1": lazy.spawn("nwg-clipman")
                    },
                ),
                widget.Spacer(length = 8),
                # Idle inhibitor
                widget.GenPollText(
                    update_interval=1,
                    func=lambda: subprocess.check_output(os.path.expanduser("/usr/share/tileos/scripts/idle-inhibit")).decode(),
                    foreground = qtile_colors[5],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[5],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn(os.path.expanduser("/usr/share/tileos/scripts/idle-inhibit toggle"), shell=True)}
                ),
                widget.Spacer(length = 8),
                widget.CPU(
                    format = ' {load_percent:.1f}%',
                    foreground = qtile_colors[5],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[5],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn(terminal + ' --class floating_shell -e btop')}
                ),
                widget.Spacer(length = 8),
                widget.Memory(
                    format = " {MemUsed:.1f}/{MemTotal:.1f} GiB",
                    measure_mem='G',
                    foreground = qtile_colors[6],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[6],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn(terminal + ' --class floating_shell -e btop')}
                ),
                widget.Spacer(length = 8),
                widget.Net(
                    prefix="M",
                    format=' {down:.0f}{down_suffix} ↓↑ {up:.0f}{up_suffix}',
                    foreground = qtile_colors[7],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[7],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn(terminal + ' --class floating_shell -e nmtui')}
                ),
                widget.Spacer(length = 8),
                widget.Volume(
                    foreground = qtile_colors[8],
                    fmt = 'Vol: {}',
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[8],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button3': lazy.spawn('pavucontrol')}
                ),
                widget.Spacer(length = 8),
                widget.Clock(
                    format="%d %b  %H:%M",
                    foreground = qtile_colors[9],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[9],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn(terminal + ' --class floating_shell -e calcurse')}
                ),
                widget.Spacer(length = 8),
                widget.TextBox(
                    text="",
                    fontsize = 14,
                    foreground = qtile_colors[10],
                    decorations=[
                        BorderDecoration(
                            colour = qtile_colors[10],
                            border_width = [0, 0, 2, 0],
                        )
                    ],
                    mouse_callbacks={'Button1': lazy.spawn('nwg-bar')}
                ),
                widget.Spacer(length = 8),
            ],
            30,
        ),
    ),
]

dgroups_key_binder = None
dgroups_app_rules = []  # type: list
follow_mouse_focus = True
bring_front_click = False
floats_kept_above = True
cursor_warp = False
floating_layout = layout.Floating(
    border_width=2,
    border_focus=qtile_colors[11],
    border_normal=qtile_colors[15],
    float_rules=[
        # Run the utility of `xprop` to see the wm class and name of an X client.
        *layout.Floating.default_float_rules,
        Match(wm_class="confirmreset"),  # gitk
        Match(wm_class="makebranch"),  # gitk
        Match(wm_class="maketag"),  # gitk
        Match(wm_class="ssh-askpass"),  # ssh-askpass
        Match(title="branchdialog"),  # gitk
        Match(title="pinentry"),  # GPG key password entry
        Match(wm_class="qt5ct"), # Qt5 Config
        Match(wm_class="qt6ct"), # Qt6 config
        Match(wm_class="calamares"), # Calamares installer
        Match(wm_class="engrampa"), # Archive manager
        Match(wm_class="nwg-look"), # GTK settings
        Match(wm_class="pavucontrol"), # PulseAudio Volume Control
        Match(wm_class="wdisplays"), # Display configurator
        Match(wm_class="floating_shell"), # Start all windows with app_id "floating_shell" in float
        Match(title="Picture-in-Picture"),
        Match(title="Firefox — Sharing Indicator"),
    ]
)
auto_fullscreen = True
focus_on_window_activation = "smart"
reconfigure_screens = True

# If things like steam games want to auto-minimize themselves when losing
# focus, should we respect this or not?
auto_minimize = True

# When using the Wayland backend, this can be used to configure input devices.
wl_input_rules = None


# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this
# string besides java UI toolkits; you can see several discussions on the
# mailing lists, GitHub issues, and other WM documentation that suggest setting
# this string if your java app doesn't work correctly. We may as well just lie
# and say that we're a working one by default.
#
# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in
# java that happens to be on java's whitelist.
wmname = "LG3D"
