new widget for launcher

This commit is contained in:
sankalp committed 2025-01-11 07:58:05 +05:45
1 parent a1027cdf89
commit 4b9876819a
16 files changed
+1212 -805

No files matched your search

@@ -1,9 +1,7 @@
from .app import *
from .bluetooth import *
from .calendar import *
from .clipboard import *
from .applauncher import *
from .cliphist import *
from .dashboard import *
from .emoji import *
from .power_menu import *
from .shell import *
from .wallpaper import *
from .wifi import *
from .power import *
from .todo import *
from .wallpapers import *
@@ -1,68 +0,0 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
def handle_application_search(launcher, query: str):
if not query.strip():
launcher.additional_box.set_visible(True)
return
launcher.additional_box.set_visible(False)
filtered_apps = [
app
for app in launcher.all_apps
if query.casefold()
in (
(app.display_name or "")
+ " "
+ (app.name or "")
+ " "
+ (app.generic_name or "")
).casefold()
]
if filtered_apps:
launcher.viewport.children = [
bake_application_slot(launcher, app) for app in filtered_apps[:6]
]
launcher.scrolled_revealer.reveal()
else:
launcher.scrolled_revealer.unreveal()
def bake_application_slot(launcher, app, **kwargs) -> Button:
return Button(
child=Box(
orientation="h",
spacing=10,
children=[
Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=62),
Box(
orientation="v",
spacing=10,
children=[
Label(
label=app.display_name or "Unknown",
h_expand=True,
name="title",
v_align="center",
h_align="start",
),
Label(
label=app.description or "",
name="description",
h_expand=True,
v_align="center",
justification="left",
line_wrap="char",
),
],
),
],
),
name="app-item",
on_clicked=lambda *_: (app.launch(), launcher.set_visible(False)),
**kwargs,
)
@@ -0,0 +1,166 @@
import operator
from collections.abc import Iterator
from fabric.utils import DesktopApp, get_desktop_applications, idle_add, remove_handler
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import Gdk, GLib
from snippets import MaterialIcon
class AppLauncher(Box):
def __init__(self, **kwargs):
super().__init__(
name="app-launcher",
visible=False,
all_visible=False,
**kwargs,
)
self._arranger_handler: int = 0
self._all_apps = get_desktop_applications()
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder="Search Applications...",
h_expand=True,
notify_text=lambda entry, *_: self.handle_search_input(entry.get_text()),
on_activate=lambda entry, *_: self.on_search_entry_activate(
entry.get_text()
),
on_button_press_event=print,
)
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
h_scrollbar_policy="never",
v_scrollbar_policy="never",
child=self.viewport,
)
self.header_box = Box(
name="header_box",
spacing=10,
orientation="h",
children=[
self.search_entry,
Button(
name="close-button",
child=MaterialIcon("close"),
tooltip_text="Exit",
on_clicked=lambda *_: self.close_launcher(),
),
],
)
self.launcher_box = Box(
name="launcher-box",
spacing=10,
h_expand=True,
orientation="v",
children=[
self.header_box,
self.scrolled_window,
],
)
self.add(self.launcher_box)
self.connect("key-press-event", self.on_key_press_event)
self.show_all()
def close_launcher(self):
self.viewport.children = []
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def open_launcher(self):
self._all_apps = get_desktop_applications()
self.arrange_viewport()
def on_key_press_event(self, widget, event):
if event.keyval == Gdk.KEY_Escape:
self.close_launcher()
def arrange_viewport(self, query: str = ""):
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
if not query.strip():
return False
filtered_apps = sorted(
[
app
for app in self._all_apps
if query.casefold()
in (
(app.display_name or "")
+ (" " + app.name + " ")
+ (app.generic_name or "")
).casefold()
],
key=lambda app: (app.display_name or "").casefold(),
)
filtered_apps = filtered_apps[:6]
self._arranger_handler = idle_add(
lambda *args: self.add_next_application(*args),
iter(filtered_apps),
pin=True,
)
return False
def add_next_application(self, apps_iter: Iterator[DesktopApp]):
if not (app := next(apps_iter, None)):
return False
self.viewport.add(self.bake_application_slot(app))
return True
def bake_application_slot(self, app: DesktopApp, **kwargs) -> Button:
return Button(
name="app-slot-button",
child=Box(
name="app-slot-box",
orientation="h",
spacing=10,
children=[
Label(
name="app-label",
label=app.display_name or "Unknown",
ellipsization="end",
v_align="center",
h_align="center",
),
],
),
tooltip_text=app.description,
on_clicked=lambda *_: (app.launch(), self.close_launcher()),
**kwargs,
)
def handle_search_input(self, text: str):
if text.strip() == ":wp":
GLib.spawn_command_line_async(
"fabric-cli exec quickbar 'launcher.open(\"wallpapers\")'"
)
self.search_entry.set_text("")
elif text.strip() == ":em":
GLib.spawn_command_line_async(
"fabric-cli exec quickbar 'launcher.open(\"emoji\")'"
)
elif text.strip() == ":ch":
GLib.spawn_command_line_async(
"fabric-cli exec quickbar 'launcher.open(\"cliphist\")'"
)
elif text.strip() == ":td":
GLib.spawn_command_line_async(
"fabric-cli exec quickbar 'launcher.open(\"todo\")'"
)
else:
self.arrange_viewport(text)
@@ -1,91 +0,0 @@
from fabric.bluetooth import BluetoothClient
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from snippets import MaterialIcon
class BluetoothMenu:
def __init__(self, launcher):
self.launcher = launcher
self.client = BluetoothClient(on_device_added=self.on_device_added)
self.paired_devices = {}
self.available_devices = {}
self.bt_button = self.create_bluetooth_button()
self.scan_button = self.create_scan_button()
self.update_bt_button_style()
def create_bluetooth_button(self):
button = Button(
child=MaterialIcon("bluetooth"),
h_align="center",
v_align="center",
on_clicked=self.bt_toggle,
)
return button
def create_scan_button(self):
return Button(
child=MaterialIcon("refresh"),
h_align="center",
v_align="center",
on_clicked=lambda *_: self.client.toggle_scan(),
)
def bt_toggle(self, *_):
self.client.toggle_power()
self.update_bt_button_style()
def update_bt_button_style(self):
style = (
"background-color: transparent;"
if self.client.enabled
else "background-color: @surfaceVariant; border-radius:100px; min-height: 50px; min-width: 50px;"
)
self.bt_button.set_style(style)
def show_bluetooth_menu(self, viewport):
viewport.children = []
devices_box = Box(orientation="v", spacing=5)
# Combine paired and available devices
all_devices = {**self.paired_devices, **self.available_devices}
for address, device in all_devices.items():
device_button = self.create_device_button(device)
devices_box.add(device_button)
viewport.add(devices_box)
def create_device_button(self, device):
connection_status = "Connected" if device.connected else ""
return Button(
child=Box(
orientation="h",
spacing=10,
children=[
Image(icon_name=device.icon_name, size=32),
Label(label=device.name),
Label(label=connection_status, h_align="end"),
],
),
on_clicked=lambda _, device=device: self.connect_to_device(device),
name="launcher-item",
)
def connect_to_device(self, device):
device.set_connecting(True)
self.show_bluetooth_menu(self.launcher.viewport)
def on_device_added(self, client, address):
if device := client.get_device(address):
if device.paired:
self.paired_devices[address] = device
else:
self.available_devices[address] = device
self.show_bluetooth_menu(self.launcher.viewport)
def get_bluetooth_buttons(self):
return [self.bt_button, self.scan_button]
@@ -1,26 +0,0 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from gi.repository import Gtk
from snippets import MaterialIcon
class Calendar:
def __init__(self, launcher):
self.launcher = launcher
self.today_button = Button(
child=MaterialIcon("event_available"),
v_align="center",
)
def show_calendar_menu(self, viewport):
viewport.children = []
calendar_container = Box(
name="calendar",
children=Gtk.Calendar(visible=True, hexpand=True),
)
viewport.add(calendar_container)
def get_calendar_buttons(self):
return self.today_button
@@ -1,140 +0,0 @@
import os
import subprocess
from fabric import Fabricator
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from snippets import MaterialIcon
class ClipboardManager:
def __init__(self, launcher, viewport):
self.launcher = launcher
self.viewport = viewport
self.clipboard_history = []
self._initialize_clipboard_watcher()
def _initialize_clipboard_watcher(self):
self.wl_paste_watcher = Fabricator(
poll_from="wl-paste --watch echo", stream=True, interval=-1
)
self.wl_paste_watcher.connect(
"changed", lambda *_: self.update_clipboard_history()
)
def get_clip_history(self):
try:
result = subprocess.run(
["cliphist", "list"], capture_output=True, text=True, check=True
)
return self._parse_clip_history(result.stdout)
except subprocess.CalledProcessError:
return []
def _parse_clip_history(self, output):
return [
{"content": line.strip(), "id": line.split()[0]}
for line in output.splitlines()
if line.strip()
][:10]
def update_clipboard_history(self):
new_history = self.get_clip_history()
if isinstance(new_history, list) and new_history != self.clipboard_history:
self.clipboard_history = new_history
self.refresh_ui()
def refresh_ui(self):
self._clear_viewport()
self.show_clipboard_history(self.viewport)
def _clear_viewport(self):
for child in self.viewport.children:
self.viewport.remove(child)
def run_command(self, command, input_data=None):
try:
input_data = self._ensure_bytes(input_data)
return subprocess.run(
command, input=input_data, capture_output=True, check=True
)
except subprocess.CalledProcessError:
return None
def _ensure_bytes(self, input_data):
if input_data and not isinstance(input_data, bytes):
return input_data.encode() # Ensure input data is in bytes
return input_data
def copy_by_id(self, clip_id: str):
command = f"cliphist decode {clip_id} | wl-copy"
try:
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError:
pass
def save_cache_file(self, clip_id: str):
output_file = f"/tmp/cliphist/{clip_id}.png"
os.makedirs("/tmp/cliphist/", exist_ok=True)
result = self.run_command(["cliphist", "decode", clip_id])
if result:
self._write_to_cache(output_file, result.stdout)
return output_file
return None
def _write_to_cache(self, output_file, data):
with open(output_file, "wb") as f:
f.write(data)
def show_clipboard_history(self, viewport, query=""):
filtered_history = self._filter_clip_history(query)
for item in filtered_history:
self.add_clipboard_item(viewport, item)
def _filter_clip_history(self, query):
if not self.clipboard_history: # Safeguard against None or empty
return []
return [item for item in self.clipboard_history if query in item["content"]]
# return [item for item in self.clipboard_history if query in item["content"]]
def add_clipboard_item(self, viewport, item):
if "png" in item["content"]:
self._add_image_button(viewport, item)
else:
self._add_text_button(viewport, item)
def _add_image_button(self, viewport, item):
output_file = self.save_cache_file(item["id"])
if output_file and os.path.exists(output_file):
image_button = Button(
h_align="start",
child=Image(file=output_file),
on_clicked=lambda _, clip_id=item["id"]: self.handle_clip_click(
clip_id
),
name="cliphist-img-item",
)
image_button.set_style(f"background-image: url('{output_file}');")
viewport.add(image_button)
def _add_text_button(self, viewport, item):
label_button = Button(
child=Label(
label=item["content"][:35], # Truncate text for display
h_expand=True,
v_align="center",
h_align="start",
),
on_clicked=lambda _, clip_id=item["id"]: self.handle_clip_click(clip_id),
name="launcher-item",
)
viewport.add(label_button)
def handle_clip_click(self, clip_id):
self.copy_by_id(clip_id)
self.launcher.set_visible(False)
def get_clipboard_buttons(self):
return MaterialIcon("content_paste")
@@ -0,0 +1,206 @@
import os
import subprocess
from typing import List
from fabric import Fabricator
from fabric.utils import remove_handler
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GLib
from snippets import MaterialIcon
class Cliphist(Box):
def __init__(self, **kwargs):
super().__init__(
name="cliphist-launcher",
all_visible=False,
visible=False,
**kwargs,
)
self._arranger_handler = 0
self.cliphist_manager = CliphistManager(self)
self.viewport = None
self.search_entry = Entry(
name="search-entry",
placeholder="Search cliphist...",
h_expand=True,
notify_text=lambda entry, *_: self.handle_search_input(entry.get_text()),
on_activate=lambda entry, *_: self.handle_search_input(entry.get_text()),
)
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
Button(
name="close-button",
child=MaterialIcon("close"),
tooltip_text="Exit",
on_clicked=lambda *_: self.close_launcher(),
),
],
)
self.launcher_box = Box(
name="cliphist-launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
)
self.add(self.launcher_box)
def open_launcher(self):
if not self.viewport:
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
h_scrollbar_policy="never",
v_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.viewport.children = []
self.cliphist_manager.arrange_viewport()
self.viewport.show()
self.search_entry.grab_focus()
def close_launcher(self):
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def handle_search_input(self, text: str):
self.cliphist_manager.arrange_viewport(text)
class CliphistManager:
def __init__(self, launcher):
self.launcher = launcher
self.cliphist_history = []
self.wl_paste_watcher = Fabricator(
poll_from="wl-paste --watch echo", stream=True, interval=-1
)
self.wl_paste_watcher.connect(
"changed", lambda *_: self.update_cliphist_history()
)
def get_clip_history(self) -> List[dict]:
try:
result = subprocess.run(
["cliphist", "list"], capture_output=True, text=True, check=True
)
return self._parse_clip_history(result.stdout)
except subprocess.CalledProcessError as e:
print(f"Error fetching cliphist history: {e}")
return []
def _parse_clip_history(self, output: str) -> List[dict]:
items = []
for line in output.splitlines():
if line.strip():
parts = line.strip().split(maxsplit=1)
if len(parts) == 2:
items.append({"id": parts[0], "content": parts[1]})
return items[:16]
def copy_clip(self, clip_id: str):
try:
decode_result = subprocess.run(
["cliphist", "decode", clip_id], capture_output=True, check=True
)
subprocess.run(["wl-copy"], input=decode_result.stdout, check=True)
self.launcher.close_launcher()
except subprocess.CalledProcessError as e:
print(f"Error copying clip {clip_id}: {e}")
def save_cache_file(self, clip_id: str) -> str:
output_file = f"/tmp/cliphist/{clip_id}.png"
os.makedirs("/tmp/cliphist/", exist_ok=True)
try:
decode_result = subprocess.run(
["cliphist", "decode", clip_id], capture_output=True, check=True
)
with open(output_file, "wb") as f:
f.write(decode_result.stdout)
return output_file
except (subprocess.CalledProcessError, IOError) as e:
print(f"Error saving cache file for clip {clip_id}: {e}")
return None
def query_clips(self, query: str = "") -> List[dict]:
if not query.strip():
return self.get_clip_history()
filtered_clips = [
item
for item in self.get_clip_history()
if query.lower() in item["content"].lower()
]
return filtered_clips
def bake_clip_slot(self, item: dict) -> Button:
if "png" in item["content"].lower():
return self._create_image_button(item)
return self._create_text_button(item)
def _create_image_button(self, item: dict) -> Button:
output_file = self.save_cache_file(item["id"])
if output_file and os.path.exists(output_file):
button = Button(
h_align="start",
child=Image(file=output_file),
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
name="clip-img-item",
)
button.set_style(f"background-image: url('{output_file}');")
return button
return None
def _create_text_button(self, item: dict) -> Button:
return Button(
child=Label(
label=item["content"][:55]
+ ("..." if len(item["content"]) > 55 else ""),
h_expand=True,
v_align="center",
h_align="start",
),
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
name="clip-item",
)
def update_cliphist_history(self):
self.cliphist_history = self.get_clip_history()
if self.launcher.viewport:
self.arrange_viewport()
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
return
if self.launcher._arranger_handler:
remove_handler(self.launcher._arranger_handler)
self.launcher.viewport.children = []
filtered_clips = self.query_clips(query)
for clip in filtered_clips:
button = self.bake_clip_slot(clip)
if button:
self.launcher.viewport.add(button)
@@ -0,0 +1,242 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from snippets import MaterialIcon
class Buttons(Box):
def __init__(self, **kwargs):
super().__init__(
name="buttons",
spacing=4,
h_align="center",
v_align="start",
h_expand=True,
v_expand=True,
visible=True,
all_visible=True,
)
self.network_status_button = Button(
name="network-status-button",
h_expand=True,
child=Box(
h_align="start",
v_align="center",
spacing=10,
children=[
MaterialIcon("wifi"),
Box(
name="network-text",
orientation="v",
h_align="start",
v_align="center",
children=[
Box(
children=[
Label(
name="network-label",
label="Wi-Fi",
justification="left",
),
Box(h_expand=True),
]
),
Box(
children=[
Label(
name="network-ssid",
label="ARGOS_5GHz",
justification="left",
),
Box(h_expand=True),
]
),
],
),
],
),
)
self.network_menu_button = Button(
name="network-menu-button",
child=MaterialIcon("chevron_right"),
)
self.network_button = Box(
name="network-button",
orientation="h",
h_align="fill",
v_align="center",
h_expand=True,
v_expand=True,
children=[
self.network_status_button,
self.network_menu_button,
],
)
self.bluetooth_status_button = Button(
name="bluetooth-status-button",
h_expand=True,
child=Box(
h_align="start",
v_align="center",
spacing=10,
children=[
MaterialIcon("bluetooth"),
Box(
name="bluetooth-text",
orientation="v",
h_align="start",
v_align="center",
children=[
Box(
children=[
Label(
name="bluetooth-label",
label="Bluetooth",
justification="left",
),
Box(h_expand=True),
]
),
Box(
children=[
Label(
name="bluetooth-status",
label="Connected",
justification="left",
),
Box(h_expand=True),
]
),
],
),
],
),
)
self.bluetooth_menu_button = Button(
name="bluetooth-menu-button",
child=MaterialIcon("chevron_right"),
)
self.bluetooth_button = Box(
name="bluetooth-button",
orientation="h",
h_align="fill",
v_align="center",
h_expand=True,
v_expand=True,
children=[
self.bluetooth_status_button,
self.bluetooth_menu_button,
],
)
self.night_mode_button = Button(
name="night-mode-button",
child=Box(
h_align="start",
v_align="center",
spacing=10,
children=[
MaterialIcon("nightlight"),
Box(
name="night-mode-text",
orientation="v",
h_align="start",
v_align="center",
children=[
Box(
children=[
Label(
name="night-mode-label",
label="Night Mode",
justification="left",
),
Box(h_expand=True),
]
),
Box(
children=[
Label(
name="night-mode-status",
label="Enabled",
justification="left",
),
Box(h_expand=True),
]
),
],
),
],
),
)
self.caffeine_button = Button(
name="caffeine-button",
child=Box(
h_align="start",
v_align="center",
spacing=10,
children=[
MaterialIcon("coffee"),
Box(
name="caffeine-text",
orientation="v",
h_align="start",
v_align="center",
children=[
Box(
children=[
Label(
name="caffeine-label",
label="Caffeine",
justification="left",
),
Box(h_expand=True),
]
),
Box(
children=[
Label(
name="caffeine-status",
label="Enabled",
justification="left",
),
Box(h_expand=True),
]
),
],
),
],
),
)
self.add(self.network_button)
self.add(self.bluetooth_button)
self.add(self.night_mode_button)
self.add(self.caffeine_button)
self.show_all()
class Dashboard(Box):
def __init__(self, **kwargs):
super().__init__(
name="dashboard",
h_align="center",
v_align="start",
h_expand=True,
v_expand=True,
visible=True,
all_visible=True,
)
self.buttons = Buttons()
self.add(self.buttons)
self.show_all()
+107 -26
View File
@@ -3,25 +3,102 @@ import subprocess
from typing import Generator, List
import ijson
from fabric.utils import remove_handler
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GLib
from snippets import MaterialIcon
class Emoji(Box):
def __init__(self, **kwargs):
super().__init__(
name="emoji-launcher",
all_visible=False,
visible=False,
**kwargs,
)
self._arranger_handler: int = 0
self.emoji_manager = EmojiManager(self)
self.viewport = None
self.search_entry = Entry(
name="search-entry",
placeholder="Search Emojis...",
h_expand=True,
notify_text=lambda entry, *_: self.handle_search_input(entry.get_text()),
on_activate=lambda entry, *_: self.handle_search_input(entry.get_text()),
)
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
Button(
name="close-button",
child=MaterialIcon("close"),
tooltip_text="Exit",
on_clicked=lambda *_: self.close_launcher(),
),
],
)
self.launcher_box = Box(
name="emoji-launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
)
self.add(self.launcher_box)
def open_launcher(self):
if not self.viewport:
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
h_scrollbar_policy="never",
v_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.viewport.children = []
self.emoji_manager.arrange_viewport()
self.viewport.show()
self.search_entry.grab_focus()
def close_launcher(self):
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def handle_search_input(self, text: str):
self.emoji_manager.arrange_viewport(text)
class EmojiManager:
def __init__(self, launcher):
self.launcher = launcher
self.emoji_file_path = os.path.expanduser("~/fabric/assets/emoji.json")
self.emoji_file_path = os.path.expanduser("~/quickbar/assets/emoji.json")
def load_emojis(self) -> Generator[tuple, None, None]:
if not os.path.exists(self.emoji_file_path):
print(f"Emoji file not found: {self.emoji_file_path}")
return
try:
with open(self.emoji_file_path, "r") as file:
for emoji_str, item in ijson.kvitems(file, ""):
yield emoji_str, item["name"], item["slug"], item["group"]
except (ijson.JSONError, KeyError, OSError):
except (ijson.JSONError, KeyError, OSError) as e:
print(f"Error loading emojis: {e}")
return
def query_emojis(self, query: str) -> List[tuple]:
@@ -34,32 +111,36 @@ class EmojiManager:
def copy_emoji(self, emoji: tuple):
subprocess.run(["wl-copy"], input=emoji[0].encode(), check=True)
self.launcher.set_visible(False)
self.launcher.close_launcher()
def show_emojis(self, viewport, query: str):
filtered_emojis = self.query_emojis(query)
self._display_emoji_grid(viewport, filtered_emojis)
def _display_emoji_grid(self, viewport, emojis: List[tuple]):
row = Box(orientation="h", spacing=10)
for emoji in emojis:
button = self._create_emoji_button(emoji)
row.add(button)
if len(row.children) >= 12:
viewport.add(row)
row = Box(orientation="h", spacing=10)
if row.children:
viewport.add(row)
def _create_emoji_button(self, emoji: tuple) -> Button:
def bake_emoji_slot(self, emoji: tuple, **kwargs) -> Button:
return Button(
child=Label(label=emoji[0], h_pack="start"),
tooltip_text=f"Copy {emoji[1]}",
on_clicked=lambda *_: self.copy_emoji(emoji),
name="emoji-item",
child=Label(label=emoji[0], h_align="center"),
tooltip_text=emoji[1],
on_clicked=lambda *_: self.copy_emoji(emoji),
**kwargs,
)
def get_emoji_buttons(self):
return MaterialIcon("mood")
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
return
(
remove_handler(self.launcher._arranger_handler)
if self.launcher._arranger_handler
else None
)
self.launcher.viewport.children = []
filtered_emojis = self.query_emojis(query)
row = Box(name="emoji-row", spacing=10, orientation="h")
for emoji in filtered_emojis:
row.add(self.bake_emoji_slot(emoji))
if len(row.children) >= 12:
self.launcher.viewport.add(row)
row = Box(name="emoji-row", spacing=10, orientation="h")
if row.children:
self.launcher.viewport.add(row)
@@ -0,0 +1,86 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from gi.repository import GLib
from snippets import MaterialIcon
class PowerMenu(Box):
def __init__(self, **kwargs):
super().__init__(
name="power-menu",
orientation="h",
spacing=10,
v_align="center",
h_align="center",
v_expand=True,
h_expand=True,
visible=True,
**kwargs,
)
self.btn_lock = Button(
name="power-menu-button",
child=MaterialIcon("lock", 50),
on_clicked=self.lock,
)
self.btn_suspend = Button(
name="power-menu-button",
child=MaterialIcon("sleep", 50),
on_clicked=self.suspend,
)
self.btn_logout = Button(
name="power-menu-button",
child=MaterialIcon("logout", 50),
on_clicked=self.logout,
)
self.btn_reboot = Button(
name="power-menu-button",
child=MaterialIcon("restart_alt", 50),
on_clicked=self.reboot,
)
self.btn_shutdown = Button(
name="power-menu-button",
child=MaterialIcon("power_settings_new", 50),
on_clicked=self.poweroff,
)
self.buttons = [
self.btn_lock,
self.btn_suspend,
self.btn_logout,
self.btn_reboot,
self.btn_shutdown,
]
for button in self.buttons:
self.add(button)
self.show_all()
def close_menu(self):
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def lock(self, *_):
GLib.spawn_command_line_async("hyprlock --immediate")
self.close_menu()
def suspend(self, *_):
GLib.spawn_command_line_async("systemctl suspend")
self.close_menu()
def logout(self, *_):
GLib.spawn_command_line_async("hyprctl dispatch exit")
self.close_menu()
def reboot(self, *_):
GLib.spawn_command_line_async("systemctl reboot")
self.close_menu()
def poweroff(self, *_):
GLib.spawn_command_line_async("systemctl poweroff")
self.close_menu()
@@ -1,102 +0,0 @@
import os
from fabric.utils import exec_shell_command, exec_shell_command_async
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from loguru import logger
from snippets import MaterialIcon
IDLE_BUTTON_ACTIVE_STYLE = "background-color: @surfaceVariant; min-width:50px; min-height:50px; border-radius:100px;"
IDLE_BUTTON_INACTIVE_STYLE = "background-color: transparent;"
class PowerMenu:
def __init__(self, launcher):
self.launcher = launcher
self.idle_inhibitor = False
self.idle_button = Button(
child=MaterialIcon("schedule"),
v_align="center",
on_clicked=self.toggle_idle_inhibitor,
)
self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE)
def toggle_idle_inhibitor(self, *_):
self.idle_inhibitor = not self.idle_inhibitor
script_path = os.path.expanduser(
"~/fabric/assets/scripts/wayland-idle-inhibitor.py"
)
if self.idle_inhibitor and not self.check_idle_state():
exec_shell_command_async(
["python3", script_path],
lambda output: logger.info(f"Idle inhibitor output: {output}"),
)
self.idle_button.set_style(IDLE_BUTTON_ACTIVE_STYLE)
else:
exec_shell_command("pkill -f wayland-idle-inhibitor.py")
self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE)
def check_idle_state(self):
pid_check = exec_shell_command("pidof wayland-idle-inhibitor.py")
return "wayland-idle-inhibitor.py" in pid_check
def show_power_menu(self, viewport, query: str = ""):
viewport.children = []
power_options = [
{
"label": "Shutdown",
"icon": "power_settings_new",
"action": self.shutdown,
},
{"label": "Logout", "icon": "logout", "action": self.logout},
{"label": "Reboot", "icon": "restart_alt", "action": self.reboot},
{"label": "Suspend", "icon": "sleep", "action": self.suspend},
{"label": "Lock", "icon": "lock", "action": self.lock},
]
# Filter power options based on the query using a generator
filtered_options = (
(
option
for option in power_options
if query.lower() in option["label"].lower()
)
if query
else power_options
)
for option in filtered_options:
button = Button(
child=Box(
orientation="h",
spacing=10,
children=[
MaterialIcon(option["icon"], size=28),
Label(label=option["label"], h_align="start"),
],
),
on_clicked=lambda _, action=option["action"]: action(),
name="launcher-item",
)
viewport.add(button)
def shutdown(self):
exec_shell_command("systemctl poweroff")
def reboot(self):
exec_shell_command("systemctl reboot")
def suspend(self):
exec_shell_command("systemctl suspend")
def logout(self):
exec_shell_command("hyprctl dispatch logout")
def lock(self):
exec_shell_command("hyprlock --immediate")
def get_power_buttons(self):
return self.idle_button
@@ -1,78 +0,0 @@
import os
import subprocess
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from snippets import MaterialIcon
CACHE_DIR = os.getenv(
"XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache", "fabric")
)
BINS = os.path.join(CACHE_DIR, "binaries")
class ShellCommandManager:
def __init__(self, launcher):
self.launcher = launcher
self.binaries = set() # Use a set to store unique binaries
self.reload_binaries()
def reload_binaries(self):
paths = os.getenv("PATH", "").split(":")
self.binaries = set()
for path in paths:
self.binaries.update(self.list_binaries_in_path(path))
# Write unique binaries to the cache file
with open(BINS, "w") as f:
f.write("\n".join(self.binaries))
def list_binaries_in_path(self, path):
if not os.path.exists(path):
return []
try:
return [
entry
for entry in os.listdir(path)
if os.access(os.path.join(path, entry), os.X_OK)
]
except OSError:
return []
def show_shell_commands(self, viewport, search_query: str):
if not search_query:
return
results = self.query_binaries(search_query)
self.display_results(viewport, results)
def query_binaries(self, filter_str: str):
# Use a generator to filter binaries on demand
filtered_bins = (cmd for cmd in self.binaries if filter_str in cmd)
return list(dict.fromkeys(filtered_bins))[:16] # Deduplicate and limit to 16
def display_results(self, viewport, results):
for command in results:
button = Button(
child=Label(
label=command,
v_align="center",
h_align="start",
),
on_clicked=lambda _, cmd=command: self.execute_command(cmd),
name="launcher-item",
)
viewport.add(button)
def execute_command(self, cmd: str):
try:
output = subprocess.check_output(cmd, shell=True, text=True)
print(output)
except subprocess.CalledProcessError as e:
print(e.output)
finally:
self.launcher.set_visible(False)
def get_shell_buttons(self):
return MaterialIcon("terminal")
@@ -0,0 +1,182 @@
import json
import os
from typing import List
from fabric import Fabricator
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GLib
from snippets import MaterialIcon
class TodoManager(Box):
def __init__(self, **kwargs):
super().__init__(
name="todo-launcher",
all_visible=False,
visible=False,
**kwargs,
)
self._arranger_handler = 0
self.todo_manager = TodoListManager(self)
self.viewport = None
self.todo_entry = Entry(
name="todo-entry",
placeholder="Add new todo...",
h_expand=True,
on_activate=lambda entry, *_: self.handle_add_todo(entry.get_text()),
)
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.todo_entry,
Button(
name="add-button",
child=MaterialIcon("add"),
tooltip_text="Add Todo",
on_clicked=lambda *_: self.handle_add_todo(
self.todo_entry.get_text()
),
),
Button(
name="close-button",
child=MaterialIcon("close"),
tooltip_text="Exit",
on_clicked=lambda *_: self.close_launcher(),
),
],
)
self.launcher_box = Box(
name="todo-launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
)
self.add(self.launcher_box)
def open_launcher(self):
if not self.viewport:
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
h_scrollbar_policy="never",
v_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.viewport.children = []
self.todo_manager.arrange_viewport()
self.viewport.show()
self.todo_entry.grab_focus()
def close_launcher(self):
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def handle_add_todo(self, text: str):
if text.strip():
self.todo_manager.add_todo(text)
self.todo_entry.set_text("")
class TodoListManager:
def __init__(self, launcher):
self.launcher = launcher
self.todos = []
self.todo_file = os.path.expanduser("~/.local/share/fabric/todos.json")
self.load_todos()
def load_todos(self):
os.makedirs(os.path.dirname(self.todo_file), exist_ok=True)
try:
if os.path.exists(self.todo_file):
with open(self.todo_file, "r") as f:
self.todos = json.load(f)
except Exception as e:
print(f"Error loading todos: {e}")
self.todos = []
def save_todos(self):
try:
with open(self.todo_file, "w") as f:
json.dump(self.todos, f)
except Exception as e:
print(f"Error saving todos: {e}")
def add_todo(self, content: str):
todo = {"content": content, "completed": False, "id": len(self.todos)}
self.todos.append(todo)
self.save_todos()
self.arrange_viewport()
def toggle_todo(self, todo_id: int):
for todo in self.todos:
if todo["id"] == todo_id:
todo["completed"] = not todo["completed"]
break
self.save_todos()
self.arrange_viewport()
def delete_todo(self, todo_id: int):
self.todos = [todo for todo in self.todos if todo["id"] != todo_id]
self.save_todos()
self.arrange_viewport()
def bake_todo_slot(self, todo: dict) -> Box:
todo_box = Box(
name="todo-item",
spacing=10,
orientation="h",
h_expand=True,
)
checkbox = Button(
name="todo-checkbox",
child=MaterialIcon(
"check_box" if todo["completed"] else "check_box_outline_blank"
),
on_clicked=lambda _, todo_id=todo["id"]: self.toggle_todo(todo_id),
)
label = Label(
label=todo["content"],
h_expand=True,
v_align="center",
h_align="start",
name="todo-label-completed" if todo["completed"] else "todo-label",
)
delete_button = Button(
name="delete-button",
child=MaterialIcon("delete"),
on_clicked=lambda _, todo_id=todo["id"]: self.delete_todo(todo_id),
)
todo_box.add(checkbox)
todo_box.add(label)
todo_box.add(delete_button)
return todo_box
def arrange_viewport(self):
if not self.launcher.viewport:
return
self.launcher.viewport.children = []
for todo in self.todos:
todo_slot = self.bake_todo_slot(todo)
self.launcher.viewport.add(todo_slot)
@@ -1,167 +0,0 @@
import hashlib
import os
from fabric.utils import exec_shell_command, exec_shell_command_async
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from gi.repository import GdkPixbuf
from loguru import logger
from snippets import MaterialIcon
class WallpaperManager:
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"}
CACHE_DIR = os.path.expanduser("~/.cache/fabric/thumbnails/wallpapers")
WALLPAPER_SCRIPT_PATH = os.path.expanduser("~/dotfiles/hypr/scripts/wallpaper.py")
def __init__(self):
self.wallpaper_dir = os.path.expanduser("~/Pictures/wallpapers")
os.makedirs(self.CACHE_DIR, exist_ok=True)
self.thumbnails = []
self.theme_toggle_button = self._create_theme_toggle_button()
self._update_button_style()
def _create_theme_toggle_button(self):
return Button(
child=MaterialIcon("contrast"),
v_align="center",
on_clicked=self.toggle_dark_mode,
)
def toggle_dark_mode(self, *_):
exec_shell_command(
os.path.expanduser("~/fabric/assets/scripts/dark-theme.sh --toggle")
)
self._update_button_style()
def check_dark_mode_state(self):
result = exec_shell_command(
"gsettings get org.gnome.desktop.interface color-scheme"
)
return result.strip().replace("'", "") == "prefer-dark"
def _update_button_style(self):
dark_mode = self.check_dark_mode_state()
style = (
"background-color: @surfaceVariant; border-radius:100px; min-height:50px; min-width:50px;"
if dark_mode
else "background-color: transparent; border-radius:100px;"
)
self.theme_toggle_button.set_style(style)
def get_cache_path(self, file_name: str) -> str:
file_hash = hashlib.md5(file_name.encode("utf-8")).hexdigest()
return os.path.join(self.CACHE_DIR, f"{file_hash}.png")
def create_thumbnail(self, image_path: str, thumbnail_size=100):
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(image_path)
width, height = pixbuf.get_width(), pixbuf.get_height()
if width > height:
new_width = thumbnail_size
new_height = int(height * (thumbnail_size / width))
else:
new_height = thumbnail_size
new_width = int(width * (thumbnail_size / height))
return pixbuf.scale_simple(
new_width, new_height, GdkPixbuf.InterpType.BILINEAR
)
except Exception as e:
logger.error(f"Error creating thumbnail for {image_path}: {e}")
return None
def generate_or_load_thumbnail(self, wallpaper_path):
cache_path = self.get_cache_path(os.path.basename(wallpaper_path))
if not os.path.exists(cache_path):
pixbuf = self.create_thumbnail(wallpaper_path)
if pixbuf:
pixbuf.savev(cache_path, "png", [], [])
return cache_path
def show_wallpaper_thumbnails(self, viewport, search_term: str = ""):
wallpapers = list(self._get_wallpapers(search_term))[:24]
if not wallpapers:
self._show_no_wallpapers_message(viewport)
return
self._display_thumbnails(viewport, wallpapers)
def _show_no_wallpapers_message(self, viewport):
viewport.add(
Box(
orientation="h",
style="padding:20px;",
children=[Button(child="No wallpapers found!", v_align="center")],
)
)
def _display_thumbnails(self, viewport, wallpapers):
row = Box(orientation="h", spacing=10, style="margin:5px;")
for index, wallpaper in enumerate(wallpapers, 1):
thumbnail_path = self.generate_or_load_thumbnail(wallpaper)
row.add(self._create_wallpaper_thumbnail(thumbnail_path, wallpaper))
if index % 6 == 0:
viewport.add(row)
row = Box(orientation="h", spacing=10, style="margin:5px;")
if row.children:
viewport.add(row)
def _get_wallpapers(self, search_term: str):
return (
os.path.join(self.wallpaper_dir, file_name)
for file_name in os.listdir(self.wallpaper_dir)
if os.path.isfile(os.path.join(self.wallpaper_dir, file_name))
and os.path.splitext(file_name)[1].lower() in self.IMAGE_EXTENSIONS
and self._matches_search(file_name, search_term)
)
def _matches_search(self, file_name, search_term: str):
return not search_term or search_term.lower() in file_name.lower()
def _thumbnail_style(self, thumbnail_path):
return (
f"background-image: url('{thumbnail_path}'); "
"min-width: 64px; min-height: 64px; "
"background-repeat: no-repeat; "
"background-size: cover; background-position: center;"
)
def _create_wallpaper_thumbnail(self, thumbnail_path, wallpaper_path):
return Button(
child=Box(
orientation="h",
h_align="center",
v_align="center",
style=self._thumbnail_style(thumbnail_path),
),
h_align="start",
v_align="center",
name="wall-item",
on_clicked=lambda _: self._select_wallpaper(wallpaper_path),
)
def _select_wallpaper(self, wallpaper_path):
self._apply_wallpaper(wallpaper_path)
def _apply_wallpaper(self, wallpaper_path):
self._execute_wallpaper_script("--image", wallpaper_path)
def apply_wallpaper_random(self):
self._execute_wallpaper_script("-R")
def _execute_wallpaper_script(self, *args):
try:
exec_shell_command_async(
["python3", self.WALLPAPER_SCRIPT_PATH, *args],
lambda output: logger.info(f"Wallpaper script output: {output}"),
)
except Exception as e:
logger.error(f"Error executing wallpaper script: {e}")
def get_wallpaper_buttons(self):
return self.theme_toggle_button
@@ -0,0 +1,217 @@
import hashlib
import json
import os
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GdkPixbuf, GLib, Gtk
from snippets import MaterialIcon
class WallpaperSelector(Box):
CACHE_DIR = os.path.expanduser("~/.cache/fabric/wallpapers")
SETTINGS_FILE = os.path.expanduser("~/dotfiles/.settings/settings.json")
SCHEMES = {
"TonalSpot": "tonalSpot",
"Expressive": "expressive",
"FruitSalad": "fruitSalad",
"Monochrome": "monochrome",
"Rainbow": "rainbow",
"Vibrant": "vibrant",
"Neutral": "neutral",
"Fidelity": "fidelity",
"Content": "content",
}
def __init__(self, wallpapers_dir: str, **kwargs):
super().__init__(name="wallpapers", spacing=4, orientation="v", **kwargs)
self.wallpapers_dir = wallpapers_dir
os.makedirs(self.CACHE_DIR, exist_ok=True)
self.files = [f for f in os.listdir(wallpapers_dir) if self._is_image(f)]
self.thumbnails = []
self._init_viewport()
self._init_search_entry()
self._init_scheme_dropdown()
self._init_layout()
self._start_thumbnail_thread()
self.show_all()
def _init_viewport(self):
self.viewport = Gtk.IconView()
self.viewport.set_model(Gtk.ListStore(GdkPixbuf.Pixbuf, str))
self.viewport.set_pixbuf_column(0)
self.viewport.set_text_column(1)
self.viewport.set_item_width(0)
self.viewport.connect("item-activated", self.on_wallpaper_selected)
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
h_expand=True,
v_expand=True,
child=self.viewport,
)
def _init_search_entry(self):
self.search_entry = Entry(
name="search-entry",
placeholder="Search Wallpapers...",
h_expand=True,
notify_text=lambda entry, *_: self.arrange_viewport(entry.get_text()),
)
def _init_scheme_dropdown(self):
self.scheme_dropdown = Gtk.ComboBoxText()
self.scheme_dropdown.set_name("scheme-dropdown")
self.scheme_dropdown.set_tooltip_text("Select color scheme")
for display_name, scheme_id in sorted(self.SCHEMES.items()):
self.scheme_dropdown.append(scheme_id, display_name)
self.scheme_dropdown.set_active_id("tonalSpot")
self.scheme_dropdown.connect("changed", self.on_scheme_changed)
self.dropdown_box = Box(
name="dropdown-box",
spacing=10,
orientation="h",
children=[
self.scheme_dropdown,
MaterialIcon("keyboard_arrow_down"),
],
)
def _init_layout(self):
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
self.dropdown_box,
Button(
name="close-button",
child=MaterialIcon("close"),
tooltip_text="Close Selector",
on_clicked=lambda *_: self.close_selector(),
),
],
)
self.add(self.header_box)
self.add(self.scrolled_window)
def close_selector(self):
GLib.spawn_command_line_async("fabric-cli exec quickbar 'launcher.close()'")
def arrange_viewport(self, query: str = ""):
self.viewport.get_model().clear()
filtered_thumbnails = [
(thumb, name)
for thumb, name in self.thumbnails
if query.casefold() in name.casefold()
]
filtered_thumbnails.sort(key=lambda x: x[1].lower())
for pixbuf, file_name in filtered_thumbnails:
self.viewport.get_model().append([pixbuf, file_name])
def on_wallpaper_selected(self, iconview, path):
model = iconview.get_model()
file_name = model[path][1]
full_path = os.path.join(self.wallpapers_dir, file_name)
selected_scheme = self.scheme_dropdown.get_active_id()
home_dir = GLib.get_home_dir()
command = (
f"python -O {home_dir}/dotfiles/hypr/scripts/wallpaper.py -I {full_path}"
)
GLib.spawn_command_line_async(command)
self.update_scheme(selected_scheme)
def on_scheme_changed(self, combo):
scheme_id = combo.get_active_id()
display_name = next(
name for name, id in self.SCHEMES.items() if id == scheme_id
)
print(f"Color scheme selected: {display_name} ({scheme_id})")
self.update_scheme(scheme_id) # Update the settings file
# Apply the selected scheme immediately
home_dir = GLib.get_home_dir()
color_generator = os.path.join(home_dir, "dotfiles/material-colors/generate.py")
try:
command = f'python -O {color_generator} -R --scheme "{scheme_id}"'
GLib.spawn_command_line_async(command)
print(f"Applied color scheme: {display_name}")
except Exception as e:
print(f"Failed to apply color scheme: {e}")
def update_scheme(self, scheme: str):
try:
with open(self.SETTINGS_FILE, "r") as f:
settings = json.loads(f.read())
settings["generation-scheme"] = scheme
with open(self.SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=2)
except Exception as error:
print(f"Failed to update generation-scheme in settings.json: {error}")
def _start_thumbnail_thread(self):
thread = GLib.Thread.new("thumbnail-loader", self._preload_thumbnails, None)
def _preload_thumbnails(self, _data):
for file_name in sorted(self.files):
full_path = os.path.join(self.wallpapers_dir, file_name)
cache_path = self._get_cache_path(file_name)
if not os.path.exists(cache_path):
pixbuf = self._create_thumbnail(full_path)
if pixbuf:
pixbuf.savev(cache_path, "png", [], [])
else:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(cache_path)
if pixbuf:
GLib.idle_add(self._add_thumbnail_to_view, pixbuf, file_name)
def _add_thumbnail_to_view(self, pixbuf, file_name):
self.thumbnails.append((pixbuf, file_name))
self.viewport.get_model().append([pixbuf, file_name])
return False
def _create_thumbnail(self, image_path: str, thumbnail_size=96):
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(image_path)
width, height = pixbuf.get_width(), pixbuf.get_height()
if width > height:
new_width = thumbnail_size
new_height = int(height * (thumbnail_size / width))
else:
new_height = thumbnail_size
new_width = int(width * (thumbnail_size / height))
return pixbuf.scale_simple(
new_width, new_height, GdkPixbuf.InterpType.BILINEAR
)
except Exception as e:
print(f"Error creating thumbnail for {image_path}: {e}")
return None
def _get_cache_path(self, file_name: str) -> str:
file_hash = hashlib.md5(file_name.encode("utf-8")).hexdigest()
return os.path.join(self.CACHE_DIR, f"{file_hash}.png")
@staticmethod
def _is_image(file_name: str) -> bool:
return file_name.lower().endswith(
(".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp")
)
@@ -1,99 +0,0 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from services import NetworkClient
from snippets import MaterialIcon
class WifiMenu:
def __init__(self, launcher):
self.launcher = launcher
self.client = NetworkClient()
self.paired_devices = {}
self.available_devices = {}
self.wifi_toggle_button = Button(
child=MaterialIcon("signal_wifi_4_bar"),
h_align="center",
v_align="center",
on_clicked=self.toggle_wifi,
)
self.update_wifi_button_style()
self.rescan_button = Button(
child=MaterialIcon("refresh"),
h_align="center",
v_align="center",
on_clicked=self.scan_for_networks,
)
self.client.device_ready.connect(self.on_device_added)
def update_wifi_button_style(self):
if self.check_wifi_state():
self.wifi_toggle_button.set_style("background-color: transparent;")
else:
self.wifi_toggle_button.set_style(
"background-color: @surfaceVariant; border-radius:100px; min-height:50px; min-width:50px;"
)
def check_wifi_state(self):
return self.client.wifi_device.enabled if self.client.wifi_device else False
def show_wifi_menu(self, viewport):
viewport.children = []
devices_box = Box(orientation="v", spacing=5)
# Iterate over the list of available access points
for ap in self.client.wifi_device.access_points:
is_connected = ap["ssid"] == self.client.wifi_device.ssid # Compare SSID
device_button = Button(
child=Box(
orientation="h",
spacing=10,
children=[
Image(icon_name=ap["icon-name"], size=32),
Label(label=ap["ssid"]), # Show SSID
Box(
orientation="h",
children=[
Label(
label="Connected" if is_connected else "",
h_align="end",
),
],
),
],
),
on_clicked=lambda _, ap=ap: (
self.connect_to_ap(ap, is_connected),
self.launcher.set_visible(False),
),
name="launcher-item",
)
devices_box.add(device_button)
viewport.add(devices_box)
def connect_to_ap(self, ap, is_connected):
if not is_connected:
self.client.connect_wifi_bssid(ap["bssid"])
def on_device_added(self, client):
self.show_wifi_menu(self.launcher.viewport)
def scan_for_networks(self, button):
self.client.wifi_device.scan()
self.show_wifi_menu(self.launcher.viewport)
def toggle_wifi(self, button):
self.update_wifi_button_style()
if self.client.wifi_device:
self.client.wifi_device.toggle_wifi()
self.show_wifi_menu(self.launcher.viewport)
def get_wifi_buttons(self):
return [self.wifi_toggle_button, self.rescan_button]