This commit is contained in:
sankalp committed 2025-02-04 19:33:35 +05:45
1 parent 0c7d17dda0
commit f943f3f43c
17 files changed
+382 -1016

No files matched your search

@@ -6,8 +6,8 @@ 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, read_config
from gi.repository import GLib, Gdk
from snippets import read_config
from fabric.widgets.image import Image
@@ -19,6 +19,10 @@ class AppLauncher(Box):
all_visible=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
self.selected_index = -1
self._arranger_handler: int = 0
self._all_apps = get_desktop_applications()
self.config = read_config()
@@ -27,10 +31,11 @@ class AppLauncher(Box):
self.search_entry = Entry(
name="search-entry",
h_expand=True,
notify_text=self.handle_search_input,
notify_text=lambda entry, *_: self.arrange_viewport(entry.get_text()),
on_activate=lambda entry, *_: self.on_search_entry_activate(
entry.get_text()
),
on_key_press_event=self.on_search_entry_key_press, # Handle key presses
)
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
@@ -57,65 +62,58 @@ class AppLauncher(Box):
)
self.resize_viewport()
self.add(self.launcher_box)
self.show_all()
def open_launcher(self):
def close_launcher(self, *_):
self.viewport.children = []
self.selected_index = -1 # Reset selection
self.launcher.close()
def open_launcher(self):
self._all_apps = get_desktop_applications()
self.arrange_viewport()
self.search_entry.grab_focus()
def close_launcher(self, *_):
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
GLib.spawn_command_line_async("fabric-cli exec modus 'launcher.close()'")
def handle_search_input(self, entry, *_):
text = entry.get_text().strip()
commands = self.config.get("commands", {})
if text in commands:
command = commands[text]
GLib.spawn_command_line_async(f"fabric-cli exec modus '{command}'")
self.search_entry.set_text("")
else:
self.arrange_viewport(text)
def resize_viewport(self):
self.scrolled_window.set_min_content_width(
self.viewport.get_allocation().width # type: ignore
)
return False
self.show_all()
def arrange_viewport(self, query: str = ""):
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
self.selected_index = -1
if not query.strip():
return False
filtered_apps = iter(
[
app
for app in self._all_apps
if query.casefold()
in (
(app.display_name or "")
+ (" " + app.name + " ")
+ (app.generic_name or "")
).casefold()
][:6]
sorted(
[
app
for app in self._all_apps
if query.casefold()
in (
(app.display_name or "")
+ (" " + app.name + " ")
+ (app.generic_name or "")
).casefold()
][:6],
key=lambda app: (app.display_name or "").casefold(),
)
)
should_resize = operator.length_hint(filtered_apps) == len(self._all_apps)
self._arranger_handler = idle_add(
lambda *args: self.add_next_application(*args)
or (self.resize_viewport() if should_resize else False),
lambda apps_iter: self.add_next_application(apps_iter)
or self.handle_arrange_complete(should_resize, query),
filtered_apps,
pin=True,
)
def handle_arrange_complete(self, should_resize, query):
if should_resize:
self.resize_viewport()
# Only auto-select first item if query exists
if query.strip() != "" and self.viewport.get_children():
self.update_selection(0)
return False
def add_next_application(self, apps_iter: Iterator[DesktopApp]):
@@ -125,8 +123,14 @@ class AppLauncher(Box):
self.viewport.add(self.bake_application_slot(app))
return True
def resize_viewport(self):
self.scrolled_window.set_min_content_width(
self.viewport.get_allocation().width # type: ignore
)
return False
def bake_application_slot(self, app: DesktopApp, **kwargs) -> Button:
return Button(
button = Button(
name="launcher-app",
child=Box(
orientation="h",
@@ -138,13 +142,99 @@ class AppLauncher(Box):
),
Label(
label=app.display_name or "Unknown",
ellipsization="end",
v_align="center",
h_align="center",
),
Box(h_expand=True),
],
),
tooltip_text=app.description,
on_clicked=lambda *_: (app.launch(), self.close_launcher()),
**kwargs,
)
return button
def update_selection(self, new_index: int):
# Unselect current
if self.selected_index != -1 and self.selected_index < len(
self.viewport.get_children()
):
current_button = self.viewport.get_children()[self.selected_index]
current_button.get_style_context().remove_class("selected")
# Select new
if new_index != -1 and new_index < len(self.viewport.get_children()):
new_button = self.viewport.get_children()[new_index]
new_button.get_style_context().add_class("selected")
self.selected_index = new_index
self.scroll_to_selected(new_button)
else:
self.selected_index = -1
def scroll_to_selected(self, button):
def scroll():
adj = self.scrolled_window.get_vadjustment()
alloc = button.get_allocation()
if alloc.height == 0:
return False # Retry if allocation isn't ready
y = alloc.y
height = alloc.height
page_size = adj.get_page_size()
current_value = adj.get_value()
# Calculate visible boundaries
visible_top = current_value
visible_bottom = current_value + page_size
if y < visible_top:
# Item above viewport - align to top
adj.set_value(y)
elif y + height > visible_bottom:
# Item below viewport - align to bottom
new_value = y + height - page_size
adj.set_value(new_value)
# No action if already fully visible
return False
GLib.idle_add(scroll)
def on_search_entry_activate(self, text):
commands = self.config.get("commands", {})
if text in commands:
command = commands[text]
eval(command, {"launcher": self.launcher}) # Dynamically execute command
else:
children = self.viewport.get_children()
if children:
# Only activate if we have selection or non-empty query
if text.strip() == "" and self.selected_index == -1:
return # Prevent accidental activation when empty
selected_index = self.selected_index if self.selected_index != -1 else 0
if 0 <= selected_index < len(children):
children[selected_index].clicked()
def on_search_entry_key_press(self, widget, event):
keyval = event.keyval
if keyval == Gdk.KEY_Down:
self.move_selection(1)
return True
elif keyval == Gdk.KEY_Up:
self.move_selection(-1)
return True
elif keyval == Gdk.KEY_Escape:
self.close_launcher()
return True
return False
def move_selection(self, delta: int):
children = self.viewport.get_children()
if not children:
return
# Allow starting selection from nothing when empty
if self.selected_index == -1 and delta == 1:
new_index = 0
else:
new_index = self.selected_index + delta
new_index = max(0, min(new_index, len(children) - 1))
self.update_selection(new_index)
@@ -1,295 +0,0 @@
from fabric.bluetooth import BluetoothClient, BluetoothDevice
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
DEVICE_TYPE_ICONS = {
"headset": "headphones", # Icon for headset devices
"headphones": "headphones", # Icon for audio devices
"computer": "computer", # Icon for computer devices
"phone": "smartphone", # Icon for phone devices
"tablet": "tablet", # Icon for tablet devices
"keyboard": "keyboard", # Icon for keyboard devices
"mouse": "mouse", # Icon for mouse devices
"other": "devices", # Default icon
}
DEVICE_BATTERY_ICONS = {
"full": "battery_full", # Full battery
"medium": "battery_half", # Medium battery
"low": "battery_alert", # Low battery
}
class BluetoothManager(Box):
def __init__(self, **kwargs):
super().__init__(
name="bluetooth-launcher",
all_visible=False,
visible=False,
**kwargs,
)
self._arranger_handler = None
self.device_manager = DeviceManager(self)
self.viewport = None
self.search_entry = Entry(
name="search-entry",
h_expand=True,
notify_text=self.handle_search_input,
on_activate=self.handle_search_input,
)
self.toggle_button = Button(
on_clicked=lambda *_: self.device_manager.bluetooth_client.toggle_power()
)
self.device_manager.bluetooth_client.connect(
"notify::enabled", self.update_toggle_button
)
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
self.toggle_button,
Button(
child=MaterialIcon("sync"),
on_clicked=lambda *_: self.device_manager.bluetooth_client.toggle_scan(),
),
],
)
self.launcher_box = Box(
name="bluetooth-launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
)
self.add(self.launcher_box)
self.is_active = False
self.polling_handler = None
def update_toggle_button(self, *_):
icon_name = (
"bluetooth"
if self.device_manager.bluetooth_client.enabled
else "bluetooth_disabled"
)
self.toggle_button.children = []
self.toggle_button.add(MaterialIcon(icon_name))
self.toggle_button.show_all()
def open_launcher(self):
if not self.is_active:
self.is_active = True
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.device_manager.arrange_viewport()
self.viewport.show()
self.search_entry.grab_focus()
self.start_device_polling()
else:
self.device_manager.arrange_viewport()
def handle_search_input(self, entry, text: str):
if isinstance(text, str):
self.device_manager.arrange_viewport(text)
def start_device_polling(self):
if not self.polling_handler and self.is_active:
self.polling_handler = GLib.timeout_add(
5000, self.device_manager.refresh_devices
)
def stop_device_polling(self):
if self.polling_handler:
GLib.source_remove(self.polling_handler)
self.polling_handler = None
class DeviceManager:
def __init__(self, launcher):
self.launcher = launcher
self.bluetooth_client = BluetoothClient(
on_device_added=self.on_device_added,
on_device_removed=self.on_device_removed,
)
self._cached_devices = []
def refresh_devices(self, *_):
if self.launcher.is_active: # Only refresh devices if Bluetooth section is open
self.arrange_viewport()
return True
def toggle_bluetooth(self, *_):
self.bluetooth_client.toggle_power()
self.arrange_viewport()
def on_device_added(self, client: BluetoothClient, address: str):
if device := client.get_device(address):
self._cached_devices.append(device)
self.refresh_viewport()
def on_device_removed(self, client: BluetoothClient, address: str):
self._cached_devices = [
device for device in self._cached_devices if device.address != address
]
self.refresh_viewport()
def refresh_viewport(self):
GLib.idle_add(self.arrange_viewport)
def query_devices(self, query: str = "") -> list:
devices = []
query = query.lower()
for device in self._cached_devices:
name = device.name or "Unknown Device"
if query in name.lower():
devices.append(device)
# Sort connected devices first, then unconnected ones based on signal strength
return sorted(
devices,
key=lambda d: (
not d.connected,
not d.paired,
d.rssi if hasattr(d, "rssi") else 0,
),
)[:48]
def get_battery_status(self, device: BluetoothDevice) -> str:
if not device.connected:
return "not-connected"
battery_level = device.battery_level if device.battery_level > 0 else None
battery_percentage = (
device.battery_percentage if device.battery_percentage > 0 else None
)
if battery_level is None and battery_percentage is None:
return "low" # Show low if no battery info is available
if battery_percentage is not None:
if battery_percentage >= 75:
return "full"
elif battery_percentage >= 30:
return "medium"
else:
return "low"
# Fallback to battery level if percentage is unavailable
if battery_level is not None:
if battery_level >= 75:
return "full"
elif battery_level >= 30:
return "medium"
else:
return "low"
return "low"
def connect_device(self, device: BluetoothDevice):
device.set_connecting(not device.connected)
def bake_device_slot(self, device: BluetoothDevice, **kwargs) -> Box:
device_type = device.type.lower() # Ensure device type is in lowercase
icon_name = DEVICE_TYPE_ICONS.get(
device_type, "devices"
) # Default to 'bluetooth'
status_icon = MaterialIcon("link" if device.connected else "link_off")
# Only show battery icon for connected devices
if device.connected:
battery_status = self.get_battery_status(device)
battery_icon = MaterialIcon(
DEVICE_BATTERY_ICONS.get(battery_status, "battery_alert")
)
else:
battery_icon = None # No battery icon for non-connected devices
device_slot_children = [
MaterialIcon(icon_name),
Label(
label=device.name or "Unknown Device",
h_align="start",
h_expand=True,
),
battery_icon,
status_icon,
Button(
name="connect-button",
child=MaterialIcon(
"bluetooth_connected" if device.connected else "bluetooth_searching"
),
tooltip_text="Disconnect" if device.connected else "Connect",
on_clicked=lambda *_: self.connect_device(device),
),
]
device_slot_children = [
child for child in device_slot_children if child is not None
]
return Box(
name="device-slot",
spacing=10,
orientation="h",
children=device_slot_children,
)
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_devices = self.query_devices(query)
# Show available (unpaired) devices first, followed by paired devices
if available_devices := [d for d in filtered_devices if not d.paired]:
for device in available_devices:
self.launcher.viewport.add(self.bake_device_slot(device))
if paired_devices := [d for d in filtered_devices if d.paired]:
for device in paired_devices:
self.launcher.viewport.add(self.bake_device_slot(device))
if not filtered_devices:
self.launcher.viewport.add(
Label(
label="No devices found" if not query else "No matching devices",
name="empty-label",
h_align="center",
)
)
@@ -1,290 +1,124 @@
from fabric.bluetooth import BluetoothClient, BluetoothDevice
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.image import Image
from fabric.widgets.button import Button
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GLib
from fabric.bluetooth import BluetoothClient, BluetoothDevice
from snippets import MaterialIcon
DEVICE_TYPE_ICONS = {
"headset": "headphones", # Icon for headset devices
"headphones": "headphones", # Icon for audio devices
"computer": "computer", # Icon for computer devices
"phone": "smartphone", # Icon for phone devices
"tablet": "tablet", # Icon for tablet devices
"keyboard": "keyboard", # Icon for keyboard devices
"mouse": "mouse", # Icon for mouse devices
"other": "devices", # Default icon
}
DEVICE_BATTERY_ICONS = {
"full": "battery_full", # Full battery
"medium": "battery_half", # Medium battery
"low": "battery_alert", # Low battery
}
class BluetoothDeviceSlot(CenterBox):
def __init__(self, device: BluetoothDevice, **kwargs):
super().__init__(name="bluetooth-device", **kwargs)
self.device = device
self.device.connect("changed", self.on_changed)
self.device.connect(
"notify::closed", lambda *_: self.device.closed and self.destroy()
)
self.connection_icon = MaterialIcon("bluetooth_disabled", 12)
self.connect_button = Button(
name="bluetooth-connect",
label="Connect",
on_clicked=lambda *_: self.device.set_connecting(not self.device.connected),
)
self.start_children = [
Box(
spacing=8,
children=[
Image(icon_name=device.icon_name + "-symbolic", size=32),
Label(label=device.name),
self.connection_icon,
],
)
]
self.end_children = self.connect_button
self.device.emit("changed") # to update display status
def on_changed(self, *_):
self.connection_icon.set_label(
"bluetooth" if self.device.connected else "bluetooth_disabled"
)
if self.device.connecting:
self.connect_button.set_label(
"Connecting..." if not self.device.connecting else "Disconnecting..."
)
else:
self.connect_button.set_label(
"Connect" if not self.device.connected else "Disconnect"
)
return
class BluetoothManager(Box):
class BluetoothConnections(Box):
def __init__(self, **kwargs):
super().__init__(
name="bluetooth-launcher",
all_visible=False,
visible=False,
name="bluetooth",
spacing=8,
orientation="vertical",
**kwargs,
)
self._arranger_handler = None
self.device_manager = DeviceManager(self)
self.viewport = None
self.client = BluetoothClient(on_device_added=self.on_device_added)
self.toggle_icon = MaterialIcon("bluetooth_disabled")
self.scan_icon = MaterialIcon("bluetooth_searching")
self.search_entry = Entry(
name="search-entry",
h_expand=True,
notify_text=self.handle_search_input,
on_activate=self.handle_search_input,
self.scan_button = Button(
name="bluetooth-scan",
child=self.scan_icon,
tooltip_text="scan",
on_clicked=lambda *_: self.client.toggle_scan(),
)
self.toggle_button = Button(
on_clicked=lambda *_: self.device_manager.bluetooth_client.toggle_power()
name="bluetooth-toggle",
tooltip_text="bluetooth-toggle",
child=self.toggle_icon,
on_clicked=lambda *_: self.client.toggle_power(),
)
self.device_manager.bluetooth_client.connect(
"notify::enabled", self.update_toggle_button
self.client.connect(
"notify::enabled",
lambda *_: self.toggle_icon.set_label(
"bluetooth" if self.client.enabled else "bluetooth_disabled"
),
)
self.client.connect(
"notify::scanning",
lambda *_: self.scan_icon.set_label(
"Stop" if self.client.scanning else "bluetooth_searching"
),
)
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
self.toggle_button,
Button(
child=MaterialIcon("sync"),
on_clicked=lambda *_: self.device_manager.bluetooth_client.toggle_scan(),
),
],
)
self.paired_box = Box(spacing=2, orientation="vertical")
self.available_box = Box(spacing=2, orientation="vertical")
self.launcher_box = Box(
name="bluetooth-launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
)
self.children = [
CenterBox(
start_children=self.scan_button,
center_children=Label(name="bluetooth-text", label="Bluetooth Devices"),
end_children=self.toggle_button,
),
Label(name="bluetooth-text", label="Paired"),
ScrolledWindow(min_content_size=(-1, -1), child=self.paired_box),
Label(name="bluetooth-text", label="Available"),
ScrolledWindow(min_content_size=(-1, -1), child=self.available_box),
]
self.add(self.launcher_box)
# self.is_active = False
# self.polling_handler = None
def update_toggle_button(self, *_):
icon_name = (
"bluetooth"
if self.device_manager.bluetooth_client.enabled
else "bluetooth_disabled"
)
self.toggle_button.children = []
self.toggle_button.add(MaterialIcon(icon_name))
self.toggle_button.show_all()
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",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.viewport.children = []
self.device_manager.arrange_viewport()
self.viewport.show()
self.search_entry.grab_focus()
self.start_device_polling()
def handle_search_input(self, entry, text: str):
if isinstance(text, str):
self.device_manager.arrange_viewport(text)
def start_device_polling(self):
GLib.timeout_add(5000, self.device_manager.refresh_devices)
class DeviceManager:
def __init__(self, launcher):
self.launcher = launcher
self.bluetooth_client = BluetoothClient(
on_device_added=self.on_device_added,
on_device_removed=self.on_device_removed,
)
self._cached_devices = []
def refresh_devices(self, *_):
if not sel.bluetooth_client.enabled:
return True
if self.launcher.viewport: # Only refresh devices if Bluetooth section is open
self.arrange_viewport()
return True
def toggle_bluetooth(self, *_):
self.bluetooth_client.toggle_power()
self.arrange_viewport()
# to run notify closures thus display the status
# without having to wait until an actual change
self.client.notify("scanning")
self.client.notify("enabled")
def on_device_added(self, client: BluetoothClient, address: str):
if device := client.get_device(address):
self._cached_devices.append(device)
self.refresh_viewport()
def on_device_removed(self, client: BluetoothClient, address: str):
self._cached_devices = [
device for device in self._cached_devices if device.address != address
]
self.refresh_viewport()
def refresh_viewport(self):
GLib.idle_add(self.arrange_viewport)
def query_devices(self, query: str = "") -> list:
if not self.bluetooth_client.enabled: # Skip querying if Bluetooth is off
return [] # No devices to show when Bluetooth is off
devices = []
query = query.lower()
for device in self._cached_devices:
name = device.name or "Unknown Device"
if query in name.lower():
devices.append(device)
# Sort connected devices first, then unconnected ones based on signal strength
return sorted(
devices,
key=lambda d: (
not d.connected,
not d.paired,
d.rssi if hasattr(d, "rssi") else 0,
),
)[:48]
def get_battery_status(self, device: BluetoothDevice) -> str:
if not device.connected:
return "not-connected"
battery_level = device.battery_level if device.battery_level > 0 else None
battery_percentage = (
device.battery_percentage if device.battery_percentage > 0 else None
)
if battery_level is None and battery_percentage is None:
return "low" # Show low if no battery info is available
if battery_percentage is not None:
if battery_percentage >= 75:
return "full"
elif battery_percentage >= 30:
return "medium"
else:
return "low"
# Fallback to battery level if percentage is unavailable
if battery_level is not None:
if battery_level >= 75:
return "full"
elif battery_level >= 30:
return "medium"
else:
return "low"
return "low"
def connect_device(self, device: BluetoothDevice):
device.set_connecting(not device.connected)
def bake_device_slot(self, device: BluetoothDevice, **kwargs) -> Box:
device_type = device.type.lower() # Ensure device type is in lowercase
icon_name = DEVICE_TYPE_ICONS.get(
device_type, "devices"
) # Default to 'bluetooth'
status_icon = MaterialIcon("link" if device.connected else "link_off")
# Only show battery icon for connected devices
if device.connected:
battery_status = self.get_battery_status(device)
battery_icon = MaterialIcon(
DEVICE_BATTERY_ICONS.get(battery_status, "battery_alert")
)
else:
battery_icon = None # No battery icon for non-connected devices
device_slot_children = [
MaterialIcon(icon_name),
Label(
label=device.name or "Unknown Device",
h_align="start",
h_expand=True,
),
battery_icon,
status_icon,
Button(
name="connect-button",
child=MaterialIcon(
"bluetooth_connected" if device.connected else "bluetooth_searching"
),
tooltip_text="Disconnect" if device.connected else "Connect",
on_clicked=lambda *_: self.connect_device(device),
),
]
device_slot_children = [
child for child in device_slot_children if child is not None
]
return Box(
name="device-slot",
spacing=10,
orientation="h",
children=device_slot_children,
)
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
if not (device := client.get_device(address)):
return
slot = BluetoothDeviceSlot(device)
# If Bluetooth is off, show a message that Bluetooth is off
if not self.bluetooth_client.enabled:
self.launcher.viewport.children = [] # Clear any existing content
self.launcher.viewport.add(
Label(
label="Bluetooth is off", # Display "Bluetooth is off"
h_align="center",
)
)
return
self.launcher.viewport.children = []
if device.paired:
return self.paired_box.add(slot)
return self.available_box.add(slot)
filtered_devices = self.query_devices(query)
# Show available (unpaired) devices first, followed by paired devices
if available_devices := [d for d in filtered_devices if not d.paired]:
for device in available_devices:
self.launcher.viewport.add(self.bake_device_slot(device))
if paired_devices := [d for d in filtered_devices if d.paired]:
for device in paired_devices:
self.launcher.viewport.add(self.bake_device_slot(device))
if not filtered_devices:
self.launcher.viewport.add(
Label(
label="No devices found" if not query else "No matching devices",
name="empty-label",
h_align="center",
)
)
@@ -25,6 +25,7 @@ class Cliphist(Box):
self._arranger_handler = 0
self.cliphist_manager = CliphistManager(self)
self.viewport = None
self.launcher = kwargs["launcher"]
self.search_entry = Entry(
name="search-entry",
@@ -80,8 +81,7 @@ class Cliphist(Box):
def close_launcher(self):
"""Closes the clipboard history launcher and clears viewport."""
self.viewport.children = []
GLib.spawn_command_line_async("fabric-cli exec modus 'launcher.close()'")
self.launcher.close()
def handle_search_input(self, text: str):
"""Handles search input to filter clipboard history."""
@@ -22,6 +22,7 @@ class Emoji(Box):
**kwargs,
)
self.launcher = kwargs["launcher"]
self._arranger_handler: int = 0
self.emoji_manager = EmojiManager(self)
self.viewport = None
@@ -70,7 +71,7 @@ class Emoji(Box):
self.search_entry.grab_focus()
def close_launcher(self):
GLib.spawn_command_line_async("fabric-cli exec modus'launcher.close()'")
self.launcher.close()
def handle_search_input(self, text: str):
self.emoji_manager.arrange_viewport(text)
@@ -19,6 +19,8 @@ class PowerMenu(Box):
**kwargs,
)
self.launcher = kwargs["launcher"]
self.btn_lock = Button(
name="powermenu-button",
child=MaterialIcon("lock", 45),
@@ -63,7 +65,7 @@ class PowerMenu(Box):
self.show_all()
def close_menu(self):
GLib.spawn_command_line_async("fabric-cli exec modus 'launcher.close()'")
self.launcher.close()
def lock(self, *_):
GLib.spawn_command_line_async("hyprlock --immediate")
@@ -23,6 +23,7 @@ class Sh(Box):
**kwargs,
)
self.launcher = kwargs["launcher"]
self._arranger_handler: int = 0
self.shell_command_manager = ShellCommandManager(self)
self.viewport = None
@@ -127,7 +128,7 @@ class ShellCommandManager:
viewport.add(button)
def close_menu(self):
GLib.spawn_command_line_async("fabric-cli exec modus 'launcher.close()'")
self.launcher.close()
def execute_command(self, cmd: str):
try:
@@ -1,14 +1,16 @@
import hashlib
import json
import os
from PIL import Image
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 gi.repository import GdkPixbuf, GLib, Gtk, Gio
from snippets import MaterialIcon
from fabric.utils import exec_shell_command, get_relative_path
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
class WallpaperSelector(Box):
@@ -29,22 +31,16 @@ class WallpaperSelector(Box):
def __init__(self, **kwargs):
super().__init__(name="wallpapers", spacing=4, orientation="v", **kwargs)
self.launcher = kwargs["launcher"]
self.wallpapers_dir = os.path.expanduser("~/Pictures/wallpapers")
os.makedirs(self.CACHE_DIR, exist_ok=True)
self.files = [f for f in os.listdir(self.wallpapers_dir) if self._is_image(f)]
self.thumbnails = []
self.thumbnail_queue = []
self.executor = ThreadPoolExecutor(max_workers=4) # Shared executor
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)
@@ -60,14 +56,12 @@ class WallpaperSelector(Box):
child=self.viewport,
)
def _init_search_entry(self):
self.search_entry = Entry(
name="search-entry",
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")
@@ -94,7 +88,6 @@ class WallpaperSelector(Box):
],
)
def _init_layout(self):
self.header_box = Box(
name="header-box",
spacing=10,
@@ -104,6 +97,45 @@ class WallpaperSelector(Box):
self.add(self.header_box)
self.add(self.scrolled_window)
self._start_thumbnail_thread()
self.setup_file_monitor()
self.show_all()
def setup_file_monitor(self):
gfile = Gio.File.new_for_path(self.wallpapers_dir)
self.file_monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None)
self.file_monitor.connect("changed", self.on_directory_changed)
def on_directory_changed(self, monitor, file, other_file, event_type):
file_name = file.get_basename()
if event_type == Gio.FileMonitorEvent.DELETED:
if file_name in self.files:
self.files.remove(file_name)
cache_path = self._get_cache_path(file_name)
if os.path.exists(cache_path):
try:
os.remove(cache_path)
except Exception as e:
print(f"Error deleting cache {cache_path}: {e}")
self.thumbnails = [(p, n) for p, n in self.thumbnails if n != file_name]
GLib.idle_add(self.arrange_viewport, self.search_entry.get_text())
elif event_type == Gio.FileMonitorEvent.CREATED:
if self._is_image(file_name) and file_name not in self.files:
self.files.append(file_name)
self.files.sort()
self.executor.submit(self._process_file, file_name)
elif event_type == Gio.FileMonitorEvent.CHANGED:
if self._is_image(file_name) and file_name in self.files:
cache_path = self._get_cache_path(file_name)
if os.path.exists(cache_path):
try:
os.remove(cache_path)
except Exception as e:
print(f"Error deleting cache for changed file {file_name}: {e}")
self.executor.submit(self._process_file, file_name)
def close_selector(self):
self.launcher.close()
def arrange_viewport(self, query: str = ""):
self.viewport.get_model().clear()
@@ -179,42 +211,41 @@ class WallpaperSelector(Box):
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)
futures = [
self.executor.submit(self._process_file, file_name)
for file_name in self.files
]
concurrent.futures.wait(futures)
GLib.idle_add(self._process_batch)
if not os.path.exists(cache_path):
pixbuf = self._create_thumbnail(full_path)
if pixbuf:
pixbuf.savev(cache_path, "png", [], [])
else:
def _process_file(self, file_name):
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):
try:
with Image.open(full_path) as img:
img.thumbnail((96, 96), Image.Resampling.BILINEAR)
img.save(cache_path, "PNG")
except Exception as e:
print(f"Error processing {file_name}: {e}")
return
self.thumbnail_queue.append((cache_path, file_name))
GLib.idle_add(self._process_batch)
def _process_batch(self):
batch = self.thumbnail_queue[:10]
del self.thumbnail_queue[:10]
for cache_path, file_name in batch:
try:
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])
self.thumbnails.append((pixbuf, file_name))
self.viewport.get_model().append([pixbuf, file_name])
except Exception as e:
print(f"Error loading thumbnail {cache_path}: {e}")
if self.thumbnail_queue:
GLib.idle_add(self._process_batch)
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")
Whitespace-only changes.
@@ -1,132 +0,0 @@
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.wayland import WaylandWindow as Window
from modules.launcher.components import (
AppLauncher,
BluetoothManager,
Cliphist,
Emoji,
PowerMenu,
Sh,
TodoManager,
WallpaperSelector,
)
class Launcher(Window):
def __init__(self, **kwargs):
super().__init__(
layer="top",
anchor="center",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = AppLauncher()
self.wallpapers = WallpaperSelector()
self.power = PowerMenu()
self.emoji = Emoji()
self.cliphist = Cliphist()
self.todo = TodoManager()
self.bluetooth = BluetoothManager()
self.sh = Sh()
self.widgets = {
"launcher": self.launcher,
"wallpapers": self.wallpapers,
"power": self.power,
"emoji": self.emoji,
"cliphist": self.cliphist,
"todo": self.todo,
"bluetooth": self.bluetooth,
"sh": self.sh,
}
self.launcher_box = CenterBox(
name="launcher",
orientation="v",
start_children=[
self.launcher,
self.wallpapers,
self.power,
self.emoji,
self.cliphist,
self.todo,
self.bluetooth,
self.sh,
],
)
self.add(self.launcher_box)
self.show_all()
self.hide()
self.add_keybinding("Escape", lambda *_: self.close())
def close(self):
self.set_keyboard_mode("none")
self.hide()
if self.bluetooth.is_active:
self.bluetooth.stop_device_polling()
for widget in self.widgets.values():
widget.hide()
# if hasattr(widget, "viewport") and widget.viewport:
# widget.viewport.hide()
return True
def open(self, widget):
if widget not in self.widgets:
return
self.set_keyboard_mode("exclusive")
self.show()
for w in self.widgets.values():
w.hide()
w.remove_style_class("open")
self.widgets[widget].show()
if widget == "launcher":
self.launcher.open_launcher()
self.launcher.search_entry.set_text("")
self.launcher.search_entry.grab_focus()
elif widget == "wallpapers":
self.wallpapers.search_entry.set_text("")
self.wallpapers.search_entry.grab_focus()
self.wallpapers.viewport.show()
self.wallpapers.viewport.set_property("name", "wallpaper-icons")
elif widget == "emoji":
self.emoji.open_launcher()
self.emoji.search_entry.set_text("")
self.emoji.search_entry.grab_focus()
elif widget == "cliphist":
self.cliphist.open_launcher()
self.cliphist.search_entry.set_text("")
self.cliphist.search_entry.grab_focus()
elif widget == "todo":
self.todo.open_launcher()
self.todo.todo_entry.set_text("")
self.todo.todo_entry.grab_focus()
elif widget == "bluetooth":
self.bluetooth.open_launcher()
self.bluetooth.search_entry.set_text("")
self.bluetooth.search_entry.grab_focus()
self.bluetooth.device_manager.arrange_viewport()
elif widget == "sh":
self.sh.open_launcher()
self.sh.search_entry.set_text("")
self.sh.search_entry.grab_focus()
else:
if hasattr(self.wallpapers, "viewport"):
self.wallpapers.viewport.hide()
self.wallpapers.viewport.set_property("name", None)
@@ -1,194 +0,0 @@
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.stack import Stack
from fabric.widgets.wayland import WaylandWindow as Window
from modules.launcher.components import (
AppLauncher,
BluetoothManager,
Cliphist,
Emoji,
PowerMenu,
Sh,
TodoManager,
WallpaperSelector,
)
class Launcher(Window):
def __init__(self, **kwargs):
super().__init__(
layer="top",
anchor="center",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = AppLauncher()
self.wallpapers = WallpaperSelector()
self.power = PowerMenu()
self.emoji = Emoji()
self.cliphist = Cliphist()
self.todo = TodoManager()
self.bluetooth = BluetoothManager()
self.sh = Sh()
self._emoji_viewport = None
self._cliphist_viewport = None
self._todo_viewport = None
self._bluetooth_viewport = None
self._sh_viewport = None
self.stack = Stack(
name="launcher-content",
v_expand=True,
h_expand=True,
transition_type="crossfade",
transition_duration=250,
children=[
self.launcher,
self.wallpapers,
self.power,
self.emoji,
self.cliphist,
self.todo,
self.bluetooth,
self.sh,
],
)
self.launcher_box = CenterBox(
name="launcher",
orientation="v",
start_children=self.stack,
)
self.add(self.launcher_box)
self.show_all()
self.hide()
self.wallpapers.viewport.hide()
self.add_keybinding("Escape", lambda *_: self.close())
def close(self):
self.set_keyboard_mode("none")
self.hide()
if self.bluetooth.is_active:
self.bluetooth.stop_device_polling()
for widget in [
self.launcher,
self.wallpapers,
self.power,
self.emoji,
self.cliphist,
self.todo,
self.bluetooth,
self.sh,
]:
widget.remove_style_class("open")
if widget == self.wallpapers:
self.wallpapers.viewport.hide()
self.wallpapers.viewport.set_property("name", None)
if widget == self.emoji and hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
if (
widget == self.cliphist
and hasattr(widget, "viewport")
and widget.viewport
):
widget.viewport.hide()
if widget == self.todo and hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
if widget == self.bluetooth and widget.viewport:
widget.viewport.hide()
widget.viewport.children = []
widget.is_active = False
if widget == self.sh and widget.viewport:
widget.viewport.hide()
for style in [
"launcher",
"wallpapers",
"power",
"emoji",
"cliphist",
"todo",
"bluetooth",
"sh",
]:
self.stack.remove_style_class(style)
self.stack.set_visible_child(self.launcher)
return True
def open(self, widget):
self.set_keyboard_mode("exclusive")
self.show()
widgets = {
"launcher": self.launcher,
"wallpapers": self.wallpapers,
"power": self.power,
"emoji": self.emoji,
"cliphist": self.cliphist,
"todo": self.todo,
"bluetooth": self.bluetooth,
"sh": self.sh,
}
for style in widgets.keys():
self.stack.remove_style_class(style)
for w in widgets.values():
w.remove_style_class("open")
if widget in widgets:
self.stack.get_style_context().add_class(widget)
self.stack.set_visible_child(widgets[widget])
widgets[widget].add_style_class("open")
if widget == "launcher":
self.launcher.open_launcher()
self.launcher.search_entry.set_text("")
self.launcher.search_entry.grab_focus()
elif widget == "wallpapers":
self.wallpapers.search_entry.set_text("")
self.wallpapers.search_entry.grab_focus()
self.wallpapers.viewport.show()
self.wallpapers.viewport.set_property("name", "wallpaper-icons")
elif widget == "emoji":
self.emoji.open_launcher()
self.emoji.search_entry.set_text("")
self.emoji.search_entry.grab_focus()
elif widget == "cliphist":
self.cliphist.open_launcher()
self.cliphist.search_entry.set_text("")
self.cliphist.search_entry.grab_focus()
elif widget == "todo":
self.todo.open_launcher()
self.todo.todo_entry.set_text("")
self.todo.todo_entry.grab_focus()
elif widget == "bluetooth":
self.bluetooth.open_launcher()
self.bluetooth.search_entry.set_text("")
self.bluetooth.search_entry.grab_focus()
self.bluetooth.device_manager.arrange_viewport()
elif widget == "sh":
self.sh.open_launcher()
self.sh.search_entry.set_text("")
self.sh.search_entry.grab_focus()
else:
if hasattr(self.wallpapers, "viewport"):
self.wallpapers.viewport.hide()
self.wallpapers.viewport.set_property("name", None)
+16 -35
View File
@@ -3,7 +3,7 @@ from fabric.widgets.stack import Stack
from fabric.widgets.wayland import WaylandWindow as Window
from modules.launcher.components import (
AppLauncher,
BluetoothManager,
BluetoothConnections,
Cliphist,
Emoji,
PowerMenu,
@@ -23,14 +23,14 @@ class Launcher(Window):
**kwargs,
)
self.launcher = AppLauncher()
self.wallpapers = WallpaperSelector()
self.power = PowerMenu()
self.emoji = Emoji()
self.cliphist = Cliphist()
self.launcher = AppLauncher(launcher=self)
self.wallpapers = WallpaperSelector(launcher=self)
self.power = PowerMenu(launcher=self)
self.emoji = Emoji(launcher=self)
self.cliphist = Cliphist(launcher=self)
self.todo = TodoManager()
self.bluetooth = BluetoothManager()
self.sh = Sh()
self.bluetooth = BluetoothConnections()
self.sh = Sh(launcher=self)
self.stack = Stack(
name="launcher-content",
@@ -53,9 +53,8 @@ class Launcher(Window):
self.launcher_box = CenterBox(
name="launcher",
orientation="v",
# start_children=self.stack,
start_children=self.stack,
)
self.launcher_box.add(self.stack) # Dynamically add only the stack
self.add(self.launcher_box)
self.show_all()
@@ -81,23 +80,7 @@ class Launcher(Window):
self.wallpapers.viewport.hide()
self.wallpapers.viewport.set_property("name", None)
if widget == self.emoji and hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
if (
widget == self.cliphist
and hasattr(widget, "viewport")
and widget.viewport
):
widget.viewport.hide()
if widget == self.todo and hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
if widget == self.bluetooth and widget.viewport:
widget.viewport.hide()
if widget == self.sh and widget.viewport:
if hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
for style in [
@@ -139,8 +122,12 @@ class Launcher(Window):
self.stack.set_visible_child(widgets[widget])
widgets[widget].show()
if widget != "launcher":
self.launcher.hide()
# if widget != "launcher":
# self.launcher.hide()
if widget != "wallpapers":
self.wallpapers.viewport.hide()
self.wallpapers.viewport.set_property("name", None)
if widget == "launcher":
self.launcher.open_launcher()
@@ -168,12 +155,6 @@ class Launcher(Window):
self.todo.todo_entry.set_text("")
self.todo.todo_entry.grab_focus()
elif widget == "bluetooth":
self.bluetooth.open_launcher()
self.bluetooth.search_entry.set_text("")
self.bluetooth.search_entry.grab_focus()
self.bluetooth.device_manager.arrange_viewport()
elif widget == "sh":
self.sh.open_launcher()
self.sh.search_entry.set_text("")
+1
View File
@@ -27,6 +27,7 @@
opacity: 0;
padding: 3px;
margin-bottom: -52px;
transition: all 0.5s cubic-bezier(0.5, 0.25, 0, 1);
}
/*
View File
Whitespace-only changes.
+50 -4
View File
@@ -72,11 +72,17 @@
}
#launcher-app:hover image,
#launcher-app:active image,
#launcher-app:selected image,
#launcher-app.selected image,
#launcher-app:focus image {
-gtk-icon-shadow: 2px 2px @primary;
}
#launcher-app:hover,
#launcher-app:active,
#launcher-app.selected,
#launcher-app:selected,
#launcher-app:focus {
text-shadow: 2pt 2pt 2pt @primary;
}
@@ -243,8 +249,48 @@
* ── bluetooth ─────────────────────────────────────────────────────────
*/
#device-slot {
background-color: @suraceVariant;
border-radius: 5px;
padding: 8px;
#bluetooth-device {
background-color: @secondaryContainer;
border-radius: 16px;
padding: 4px;
margin-bottom: 4px;
}
#bluetooth-scan,
#bluetooth-toggle {
background-color: @secondaryContainer;
color: @onSecondaryContainer;
margin: 11px;
margin-left: 0px;
min-width: 44px;
min-height: 44px;
border-radius: 100%;
}
#bluetooth-scan:hover,
#bluetooth-toggle:hover {
background-color: @surfaceBright;
}
#bluetooth-scan label,
#bluetooth-toggle label {
font-weight: bold;
}
#bluetooth-text {
font-weight: bold;
}
#bluetooth-connection {
font-size: 20px;
}
#bluetooth-connect {
background-color: @shadow;
border-radius: 16px;
padding: 8px 16px;
}
#bluetooth-connect:hover {
background-color: @surfaceBright;
}
+1 -1
View File
@@ -1,4 +1,4 @@
@import url(../../.cache/material/colors.css);
@import url(../../../.cache/material/colors.css);
@import "./bar.css";
@import "./notification.css";
@import "./osd.css";
View File
Whitespace-only changes.