huge update on launcher

This commit is contained in:
sankalp committed 2024-11-22 20:55:11 +05:45
1 parent abfc2ff888
commit b93f1164cc
50 files changed
+685 -261

No files matched your search

+1 -1
View File
@@ -6,9 +6,9 @@ from fabric.widgets.button import Button
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.datetime import DateTime
from fabric.widgets.wayland import WaylandWindow as Window
from modules.bar.widgets import Bluetooth # Weather,
from modules.bar.widgets import (
BatteryLabel,
Bluetooth,
HardwareUsage,
IdleIndicator,
MicrophoneIndicator,
+139 -58
View File
@@ -1,36 +1,36 @@
import os
import time
import psutil
from fabric.utils import (
exec_shell_command,
exec_shell_command_async,
get_desktop_applications,
idle_add,
invoke_repeater,
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.revealer import Revealer
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.widgets.wayland import WaylandWindow as Window
from loguru import logger
from modules.launcher.widgets import (
BluetoothMenu,
ClipboardManager,
EmojiManager,
PowerMenu,
ShellCommandManager,
WallpaperManager,
WifiMenu,
bake_favorite_slot,
handle_application_search,
)
from snippets import get_profile_picture_path, read_config, username
class Launcher(Window):
COMMAND_ICONS = {
"/e": "face-smile-symbolic",
"/c": "edit-copy-symbolic",
"/s": "utilities-terminal-symbolic",
"/w": "image-symbolic",
}
def __init__(self, **kwargs):
self.FAVORITE_APPS = self.load_favorite_apps()
super().__init__(
layer="top",
anchor="center",
@@ -42,43 +42,94 @@ class Launcher(Window):
)
self.all_apps = get_desktop_applications()
self.initialize_managers()
self.uptime_label = Label(
label=self.get_current_uptime(), style="margin-left: 60px;"
)
self.setup_ui()
self.connect("key-press-event", self.on_key_press)
self.update_uptime_label()
def load_favorite_apps(self):
config = read_config()
return config.get("favorite_apps", [])
def initialize_managers(self):
self.clipboard_manager = ClipboardManager(self, self.get_viewport())
self.emoji_manager = EmojiManager(self)
self.shell_command_manager = ShellCommandManager(self)
self.wallpaper_manager = WallpaperManager()
self.idle_inhibitor = False
self.power_menu = PowerMenu(self)
self.bluetooth_menu = BluetoothMenu(self)
self.network_menu = WifiMenu(self)
def setup_ui(self):
self.scrolled_window = self.create_scrolled_window()
self.scrolled_revealer = self.create_revealer()
self.search_entry = self.create_search_entry()
self.additional_box = self.create_additional_box()
self.search_box = Box(spacing=10, orientation="h", children=[self.search_entry])
launcher_box = Box(
orientation="v",
size=(550, 0),
size=(580, 0),
name="launcher",
children=[
Box(spacing=10, orientation="h", children=[self.search_entry]),
self.search_box,
self.get_favorites_box(),
self.additional_box,
self.scrolled_revealer,
],
)
self.add(launcher_box)
self.show_favorites()
self.show_all()
def create_additional_box(self):
return Box(
orientation="h",
spacing=10,
children=[
Box(
name="profile-pic",
style=f"background-image: url(\"file://{get_profile_picture_path() or ''}\")",
),
Label(label=username()),
self.uptime_label,
],
)
def get_current_uptime(self):
uptime = time.time() - psutil.boot_time()
uptime_hours, remainder = divmod(uptime, 3600)
uptime_minutes, _ = divmod(remainder, 60)
return (
f"Up: {int(uptime_hours)} {'hours' if uptime_hours != 1 else 'hour'}, "
f"{int(uptime_minutes)} {'minutes' if uptime_minutes != 1 else 'minute'}"
)
def update_uptime_label(self):
self.uptime_label.set_label(self.get_current_uptime())
invoke_repeater(
60 * 1000, lambda: self.uptime_label.set_label(self.get_current_uptime())
)
def create_search_entry(self):
self.entry = Entry(
entry = Entry(
placeholder="Search.....",
h_expand=True,
notify_text=lambda entry, *_: self.debounce_search(entry.get_text()),
)
return self.entry
entry.set_icon_from_icon_name(0, "preferences-system-search-symbolic")
return entry
def get_favorites_box(self):
if not hasattr(self, "fav_apps_box"):
self.fav_apps_box = Box(spacing=10, orientation="h")
return self.fav_apps_box
def create_scrolled_window(self):
return ScrolledWindow(
name="launcher-scroll",
child=self.get_viewport(),
h_scrollbar_policy="never",
v_scrollbar_policy="never",
@@ -109,83 +160,113 @@ class Launcher(Window):
remove_handler(self._arranger_handler)
self._arranger_handler = idle_add(self.arrange_viewport, query, pin=True)
def show_favorites(self):
for app_name in self.FAVORITE_APPS:
app = next((a for a in self.all_apps if a.name == app_name), None)
if app:
self.get_favorites_box().add(bake_favorite_slot(self, app))
def arrange_viewport(self, query: str = ""):
self.clear_viewport()
self.get_viewport().children = []
command_handlers = {
"/e": self.show_emojis,
"/c": self.show_clipboard_history,
"/s": self.show_shell_commands,
"/w": self.show_wallpapers,
"/idle": self.toggle_idle_inhibitor,
":em": self.show_emojis,
":ch": self.show_clipboard_history,
":sh": self.show_shell_commands,
":wl": self.show_wallpapers,
":p": self.show_powermenu,
":bt": self.show_bluetooth_settings,
":nw": self.show_network,
}
for command, handler in command_handlers.items():
if query.startswith(command):
self.handle_command(command, query, handler)
handler(query[len(command) :].strip())
return
self.reset_search_icon()
if query.startswith(":"):
self.get_favorites_box().set_visible(False)
self.additional_box.set_visible(False)
self.show_help(query[1:])
self.scrolled_revealer.reveal()
return
handle_application_search(self, query)
def clear_viewport(self):
# Clear the children of the viewport
self.get_viewport().children = []
def handle_command(self, command: str, query: str, handler):
icon_name = self.get_command_icon(command)
self.entry.set_icon_from_icon_name(0, icon_name)
handler(query[len(command) :].strip())
def show_network(self, *_):
self.network_menu.show_wifi_menu(self.viewport)
self.scrolled_revealer.reveal()
def get_command_icon(self, command: str) -> str:
return self.COMMAND_ICONS.get(command, "")
def reset_search_icon(self):
self.entry.set_icon_from_icon_name(0, "preferences-system-search-symbolic")
# def show_desktop_buttons(self, query: str):
# self.desktop_button_manager.show_desktop_buttons(query)
def show_emojis(self, query: str):
self.emoji_manager.show_emojis(self.get_viewport(), query)
self.scrolled_revealer.reveal()
def show_clipboard_history(self, query: str):
self.clipboard_manager.show_clipboard_history(self.get_viewport(), query)
self.scrolled_revealer.reveal()
def show_powermenu(self, query: str = ""):
self.power_menu.show_power_menu(self.get_viewport(), query)
self.scrolled_revealer.reveal()
def show_shell_commands(self, query: str):
if not query:
self.scrolled_revealer.unreveal()
return
self.shell_command_manager.show_shell_commands(self.get_viewport(), query)
self.scrolled_revealer.reveal()
def show_wallpapers(self, query: str):
if query == "random":
self.wallpaper_manager.apply_wallpaper_random()
else:
self.wallpaper_manager.show_wallpaper_thumbnails(self.get_viewport(), query)
self.scrolled_revealer.reveal()
def toggle_idle_inhibitor(self, query: str):
def show_bluetooth_settings(self, *_):
self.bluetooth_menu.show_bluetooth_menu(self.viewport)
self.scrolled_revealer.reveal()
self.idle_inhibitor = not self.idle_inhibitor
script_path = os.path.expanduser(
"~/fabric/assets/scripts/wayland-idle-inhibitor.py"
)
def show_help(self, query: str):
help_commands = [
(":bt", "Bluetooth"),
(":ch", "Copy a clipboard history entry"),
(":em", "Copy an emoji"),
(":p", "Shutdown and go sleepy time"),
(":sh", "Run executables from PATH"),
(":wl", "Set the wallpaper"),
(":nw", "List of available wifi networks"),
]
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}"),
filtered_help = [
(command, description)
for command, description in help_commands
if query.lower() in command[1:].lower()
]
for command, description in filtered_help:
button = Button(
child=self.create_help_button_content(command, description),
name="help-item",
)
else:
exec_shell_command("pkill -f wayland-idle-inhibitor.py")
self.get_viewport().add(button)
def check_idle_state(self):
return "wayland-idle-inhibitor.py" in exec_shell_command(
"pidof wayland-idle-inhibitor.py"
def create_help_button_content(self, command, description):
return Box(
orientation="h",
spacing=10,
children=[
Label(
label=command, h_expand=True, name="command-label", h_align="start"
),
Label(
label=description,
h_expand=True,
name="description-label",
h_align="end",
),
],
)
def toggle(self):
self.set_visible(not self.is_visible())
if self.is_visible():
self.search_entry.set_text("")
self.search_entry.grab_focus()
@@ -1,13 +1,20 @@
from .app import handle_application_search
from .app import bake_favorite_slot, handle_application_search
from .bluetooth import BluetoothMenu
from .clipboard import ClipboardManager
from .emoji import EmojiManager
from .powermenu import PowerMenu
from .shell import ShellCommandManager
from .wallpaper import WallpaperManager
from .wifi import WifiMenu
__all__ = [
"bake_favorite_slot",
"handle_application_search",
"ClipboardManager",
"EmojiManager",
"ShellCommandManager",
"WallpaperManager",
"WifiMenu",
"PowerMenu",
"BluetoothMenu",
]
+57 -44
View File
@@ -1,4 +1,3 @@
from fabric.utils import DesktopApp
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
@@ -6,25 +5,18 @@ from fabric.widgets.label import Label
def handle_application_search(launcher, query: str):
if not query.strip():
query = query.strip()
if not query:
launcher.fav_apps_box.set_visible(True)
launcher.additional_box.set_visible(True)
launcher.scrolled_revealer.unreveal()
return
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()
]
launcher.fav_apps_box.set_visible(False)
launcher.additional_box.set_visible(False)
filtered_apps = filter_apps_by_query(launcher.all_apps, query)
if filtered_apps:
# Limit to the first 6 applications
limited_apps = filtered_apps[:6]
launcher.viewport.children = [
bake_application_slot(launcher, app) for app in limited_apps
@@ -34,38 +26,59 @@ def handle_application_search(launcher, query: str):
launcher.scrolled_revealer.unreveal()
def bake_application_slot(launcher, app: DesktopApp, **kwargs) -> Button:
app_slot = Box(
orientation="h",
spacing=10,
children=[
Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=62),
Box(
orientation="v",
spacing=5,
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",
),
],
),
],
def filter_apps_by_query(all_apps, query: str):
query_casefold = query.casefold()
return [
app
for app in all_apps
if query_casefold in build_app_search_string(app).casefold()
]
def build_app_search_string(app):
return " ".join(filter(None, [app.display_name, app.name, app.generic_name]))
def bake_favorite_slot(launcher, app, **kwargs) -> Button:
return Button(
child=Image(pixbuf=app.get_icon_pixbuf(), size=68),
name="fav-item",
tooltip_text=app.description,
on_clicked=lambda *_: (app.launch(), launcher.set_visible(False)),
**kwargs,
)
def bake_application_slot(launcher, app, **kwargs) -> Button:
return Button(
child=app_slot,
child=Box(
orientation="h",
spacing=10,
children=[
Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=68),
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,91 @@
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 = {}
def show_bluetooth_menu(self, viewport):
viewport.children = []
devices_box = Box(orientation="v", spacing=5)
# Add paired devices to the paired devices box
for address, device in self.paired_devices.items():
device_button = Button(
child=Box(
orientation="h",
spacing=10,
children=[
Image(icon_name=device.icon_name, size=32),
Label(label=device.name), # Show the device name
Box(
orientation="h",
children=[
Label(
label=" "
+ ("Connected" if device.connected else ""),
h_align="end",
),
],
),
],
),
on_clicked=lambda _, device=device: self.connect_to_device(device),
name="sh-item",
)
devices_box.add(device_button)
# Add available devices to the available devices box
for address, device in self.available_devices.items():
device_button = Button(
child=Box(
orientation="h",
spacing=10,
children=[
Image(icon_name=device.icon_name, size=32),
Label(label=device.name), # Show the device name
Box(
orientation="h",
children=[
Label(
label="",
),
],
),
],
),
on_clicked=lambda _, device=device: self.connect_to_device(device),
name="sh-item",
)
devices_box.add(device_button)
viewport.add(devices_box)
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 not (device := client.get_device(address)):
return
if device.paired:
self.paired_devices[address] = device
else:
self.available_devices[address] = device
self.show_bluetooth_menu(self.launcher.viewport)
def icon_button(self):
return Button(
child=MaterialIcon("bluetooth"),
)
@@ -1,11 +1,11 @@
import os
import subprocess
from gi.repository import GLib
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:
@@ -13,52 +13,66 @@ class ClipboardManager:
self.launcher = launcher
self.viewport = viewport
self.clipboard_history = []
self.update_clipboard_history()
self.refresh_ui()
GLib.timeout_add(10000, self.update_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 [
{"text": line.strip(), "id": line.split()[0]}
for line in result.stdout.splitlines()
if line.strip()
][:10]
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 new_history != self.clipboard_history:
self.clipboard_history = new_history
self.refresh_ui()
return True
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)
self.show_clipboard_history(self.viewport, "")
def run_command(self, command, input_data=None):
try:
if input_data is not None:
input_data = input_data.encode()
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 copy_by_id(self, clip_id: str):
result = self.run_command(["cliphist", "decode", clip_id])
if result:
self.run_command(["wl-copy"], input=result.stdout)
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 clear_clipboard(self):
self.run_command(["cliphist", "wipe"])
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"
@@ -66,28 +80,29 @@ class ClipboardManager:
result = self.run_command(["cliphist", "decode", clip_id])
if result:
with open(output_file, "wb") as f:
f.write(result.stdout)
self._write_to_cache(output_file, result.stdout)
return output_file
return None
def clear_tmp(self):
self.run_command(["rm", "-rf", "/tmp/cliphist/*"])
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: str):
filtered_history = [
item for item in self.clipboard_history if query in item["text"]
]
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 add_clipboard_item(self, viewport, item):
if "png" in item["text"]:
self.add_image_button(viewport, item)
else:
self.add_label_button(viewport, item)
def _filter_clip_history(self, query):
return [item for item in self.clipboard_history if query in item["content"]]
def add_image_button(self, viewport, item):
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(
@@ -100,12 +115,11 @@ class ClipboardManager:
)
image_button.set_style(f"background-image: url('{output_file}');")
viewport.add(image_button)
# GLib.timeout_add(3000, lambda: self.cleanup_file(output_file))
def add_label_button(self, viewport, item):
def _add_text_button(self, viewport, item):
label_button = Button(
child=Label(
label=item["text"][:55],
label=item["content"][:55], # Truncate text for display
h_expand=True,
v_align="center",
h_align="start",
@@ -119,8 +133,7 @@ class ClipboardManager:
self.copy_by_id(clip_id)
self.launcher.set_visible(False)
def cleanup_file(self, file_path):
try:
os.remove(file_path)
except FileNotFoundError:
pass
def icon_button(self):
return Button(
child=MaterialIcon("content_paste"),
)
+44 -31
View File
@@ -1,15 +1,17 @@
import json
import os
import subprocess
from typing import List
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from snippets import MaterialIcon
class EmojiItem:
def __init__(self, str: str, name: str, slug: str, group: str):
self.str = str
def __init__(self, emoji_str: str, name: str, slug: str, group: str):
self.str = emoji_str
self.name = name
self.slug = slug
self.group = group
@@ -18,37 +20,42 @@ class EmojiItem:
class EmojiManager:
def __init__(self, launcher):
self.launcher = launcher
self.emojis = None # Delay loading until first use
self.query_cache = {}
self.emojis: List[EmojiItem] = []
self.query_cache: dict = {}
def load_emojis(self):
if self.emojis is None:
emoji_path = os.path.expanduser("~/fabric/assets/emoji.json")
try:
with open(emoji_path, "r") as f:
data = json.load(f)
self.emojis = [
EmojiItem(str, item["name"], item["slug"], item["group"])
for str, item in data.items()
]
except Exception as e:
print(f"Error loading emojis: {e}")
self.emojis = []
emoji_path = os.path.expanduser("~/fabric/assets/emoji.json")
if not os.path.exists(emoji_path):
return []
def query_emojis(self, query: str):
# Return cached results if available
try:
with open(emoji_path, "r") as file:
data = json.load(file)
return [
EmojiItem(emoji_str, item["name"], item["slug"], item["group"])
for emoji_str, item in data.items()
]
except (json.JSONDecodeError, OSError):
return []
def get_emojis(self):
if not self.emojis:
self.emojis = self.load_emojis()
return self.emojis
def query_emojis(self, query: str) -> List[EmojiItem]:
if query in self.query_cache:
return self.query_cache[query]
self.load_emojis() # Ensure emojis are loaded
emojis = self.get_emojis()
filtered_emojis = [
e
for e in self.emojis
if query in e.name or query in e.slug or query in e.group
][:44]
emoji
for emoji in emojis
if query.lower() in emoji.name.lower()
or query.lower() in emoji.slug.lower()
or query.lower() in emoji.group.lower()
][:48]
# Cache the results
self.query_cache[query] = filtered_emojis
return filtered_emojis
@@ -58,24 +65,30 @@ class EmojiManager:
def show_emojis(self, viewport, query: str):
filtered_emojis = self.query_emojis(query)
row = Box(orientation="h", spacing=10)
self._display_emoji_grid(viewport, filtered_emojis)
for emoji_item in filtered_emojis:
button = self.bake_emoji_slot(emoji_item)
def _display_emoji_grid(self, viewport, emojis: List[EmojiItem]):
row = Box(orientation="h", spacing=10)
for emoji in emojis:
button = self._create_emoji_button(emoji)
row.add(button)
if len(row.children) >= 11:
if len(row.children) >= 12:
viewport.add(row)
row = Box(orientation="h", spacing=10)
if row.children:
viewport.add(row)
def bake_emoji_slot(self, emoji: EmojiItem, **kwargs) -> Button:
def _create_emoji_button(self, emoji: EmojiItem) -> Button:
return Button(
child=Label(label=emoji.str, h_pack="start"),
tooltip_text=f"Copy {emoji.name}",
on_clicked=lambda *_: self.copy_emoji(emoji),
name="emoji-item",
**kwargs,
)
def icon_button(self):
return Button(
child=MaterialIcon("mood"),
)
@@ -0,0 +1,82 @@
from fabric.utils import exec_shell_command
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from snippets import MaterialIcon
class PowerMenu:
def __init__(self, launcher):
self.launcher = launcher
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,
},
]
if query:
power_options = [
option
for option in power_options
if query.lower() in option["label"].lower()
]
for option in power_options:
button = Button(
child=Box(
orientation="h",
spacing=10,
children=[
MaterialIcon(option["icon"], size="28px"),
Label(label=option["label"], h_align="start"),
],
),
on_clicked=lambda _, action=option["action"]: action(),
name="sh-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 icon_button(self):
return Button(
child=MaterialIcon("power_settings_new"),
)
+17 -12
View File
@@ -3,11 +3,12 @@ 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_PATH = os.path.join(CACHE_DIR, "binaries")
BINS = os.path.join(CACHE_DIR, "binaries")
class ShellCommandManager:
@@ -16,14 +17,15 @@ class ShellCommandManager:
self.reload_binaries()
def reload_binaries(self):
"""Reload the binaries from the PATH environment variable."""
paths = os.getenv("PATH", "").split(":")
unique_bins = set()
bins = []
for path in paths:
unique_bins.update(self.list_binaries_in_path(path))
bins.extend(self.list_binaries_in_path(path))
self.save_binaries_to_cache(unique_bins)
unique_bins = set(bins)
with open(BINS, "w") as f:
f.write("\n".join(unique_bins))
def list_binaries_in_path(self, path):
if not os.path.exists(path):
@@ -37,10 +39,6 @@ class ShellCommandManager:
except subprocess.CalledProcessError:
return []
def save_binaries_to_cache(self, binaries):
with open(BINS_PATH, "w") as f:
f.write("\n".join(binaries))
def show_shell_commands(self, viewport, search_query: str):
if not search_query:
return
@@ -50,9 +48,11 @@ class ShellCommandManager:
def query_binaries(self, filter_str):
try:
with open(BINS_PATH) as f:
return [line.strip() for line in f if filter_str in line][:16]
except FileNotFoundError:
result = subprocess.check_output(
f"cat {BINS} | fzf -f {filter_str} | head -n 16", shell=True, text=True
)
return list(dict.fromkeys(result.splitlines())) # Deduplicate results
except subprocess.CalledProcessError:
return []
def display_results(self, viewport, results):
@@ -76,3 +76,8 @@ class ShellCommandManager:
print(e.output)
finally:
self.launcher.set_visible(False)
def icon_button(self):
return Button(
child=MaterialIcon("terminal"),
)
@@ -1,14 +1,19 @@
import os
from pathlib import Path
from loguru import logger
from fabric.utils import exec_shell_command_async
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from loguru import logger
from snippets import MaterialIcon
class WallpaperManager:
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"}
THUMBNAIL_SIZE = "x32"
THUMBNAIL_ASPECT_RATIO = "1:1"
WALLPAPER_SCRIPT_PATH = os.path.expanduser("~/dotfiles/hypr/scripts/wallpaper.py")
def __init__(self):
self.wallpaper_dir = Path.home() / "Pictures" / "wallpapers"
self.thumbnail_dir = (
@@ -17,7 +22,7 @@ class WallpaperManager:
self.thumbnail_dir.mkdir(parents=True, exist_ok=True)
def show_wallpaper_thumbnails(self, viewport, search_term: str = ""):
wallpapers = self._get_wallpapers(search_term)[:24]
wallpapers = self._get_wallpapers(search_term)
self._populate_viewport(viewport, wallpapers)
def _get_wallpapers(self, search_term: str):
@@ -25,22 +30,25 @@ class WallpaperManager:
f
for f in self.wallpaper_dir.iterdir()
if f.is_file()
and f.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}
and (not search_term or search_term.lower() in f.name.lower())
and f.suffix.lower() in self.IMAGE_EXTENSIONS
and self._matches_search(f, search_term)
]
def _matches_search(self, file, search_term: str):
return not search_term or search_term.lower() in file.name.lower()
def _populate_viewport(self, viewport, wallpapers):
viewport.children.clear()
row = Box(orientation="h", spacing=10)
for i, wallpaper in enumerate(wallpapers):
for i, wallpaper in enumerate(wallpapers[:27]): # Limit to 27 wallpapers
thumbnail_path = self._generate_thumbnail(wallpaper)
thumbnail_button = self._create_wallpaper_thumbnail(
thumbnail_path, wallpaper
)
row.add(thumbnail_button)
if (i + 1) % 8 == 0:
if (i + 1) % 9 == 0:
viewport.add(row)
row = Box(orientation="h", spacing=10)
@@ -54,27 +62,26 @@ class WallpaperManager:
return thumbnail_path
def _create_thumbnail(self, wallpaper_path, thumbnail_path):
logger.debug(f"Generating thumbnail for {wallpaper_path}")
exec_shell_command_async(
[
"magick",
str(wallpaper_path),
"-resize",
"x32",
self.THUMBNAIL_SIZE,
"-gravity",
"Center",
"-extent",
"1:1",
self.THUMBNAIL_ASPECT_RATIO,
str(thumbnail_path),
],
lambda *args: logger.debug(args),
)
def _create_wallpaper_thumbnail(self, thumbnail_path, wallpaper_path):
thumbnail_style = self._thumbnail_style(thumbnail_path)
thumbnail_box = Box(
orientation="h",
h_align="center",
v_align="center",
style=self._thumbnail_style(thumbnail_path),
orientation="h", h_align="center", v_align="center", style=thumbnail_style
)
return Button(
child=thumbnail_box,
@@ -93,7 +100,6 @@ class WallpaperManager:
)
def _select_wallpaper(self, wallpaper_path):
logger.info(f"Selected wallpaper: {wallpaper_path}")
self._apply_wallpaper(wallpaper_path)
def _apply_wallpaper(self, wallpaper_path):
@@ -103,12 +109,15 @@ class WallpaperManager:
self._execute_wallpaper_script("-R")
def _execute_wallpaper_script(self, *args):
script_path = os.path.expanduser("~/dotfiles/hypr/scripts/wallpaper.py")
try:
exec_shell_command_async(
["python3", script_path, *args],
lambda output: logger.info(f"{output}"),
["python3", self.WALLPAPER_SCRIPT_PATH, *args],
lambda output: logger.info(f"Wallpaper script output: {output}"),
)
logger.info(f"Wallpaper applied with args: {args}")
except Exception as e:
logger.error(f"Error applying wallpaper: {e}")
except Exception:
pass
def icon_button(self):
return Button(
child=MaterialIcon("image"),
)
@@ -0,0 +1,77 @@
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 = {}
# Connect the event when a new device is added
self.client.device_ready.connect(self.on_device_added)
def show_wifi_menu(self, viewport):
viewport.children = []
devices_box = Box(orientation="v", spacing=5)
scan_button = Button(
child=MaterialIcon("sync"),
on_clicked=self.scan_for_networks,
name="sh-item",
)
devices_box.add(scan_button)
# 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="sh-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 icon_button(self):
return Button(
child=MaterialIcon("sync"),
)
+4
View File
@@ -1,9 +1,13 @@
from .animator import Animator
from .icon import MaterialIcon
from .icon_resolver import IconResolver
from .util import get_profile_picture_path, read_config, username
__all__ = [
"Animator",
"MaterialIcon",
"IconResolver",
"read_config",
"get_profile_picture_path",
"username",
]
+20 -15
View File
@@ -1,26 +1,31 @@
import json
from typing import Literal
import os
from gi.repository import GLib
from loguru import logger
def read_config():
with open("config.json", "r") as file:
home_dir = GLib.get_home_dir()
config_path = f"{home_dir}/fabric/assets/config.json"
with open(config_path, "r") as file:
# Load JSON data into a Python dictionary
data = json.load(file)
return data
def format_time(secs):
mm, _ = divmod(secs, 60)
hh, mm = divmod(mm, 60)
return "%d h %02d min" % (hh, mm)
def get_profile_picture_path() -> str | None:
path = os.path.expanduser("~/Pictures/Other/face.jpg")
if not os.path.exists(path):
path = os.path.expanduser("~/.face")
if not os.path.exists(path):
logger.warning(
"can't fetch a user profile picture, add a profile picture image at ~/.face or at ~/Pictures/Other/profile.jpg"
)
path = None
return path
def convert_bytes(bytes: int, to: Literal["kb", "mb", "gb"]):
multiplier = 1
if to == "mb":
multiplier = 2
elif to == "gb":
multiplier = 3
return bytes / (1024**multiplier)
def username():
return os.getlogin().title()
+61 -37
View File
@@ -269,6 +269,24 @@ tooltip label {
background-color: transparent;
}
#launcher button#fav-item {
border-radius: 10px;
padding: 10px;
background-image: none;
box-shadow: none;
}
#launcher button#fav-item:hover image,
#launcher button#fav-item:focus image {
-gtk-icon-shadow: 2px 2px @primary;
}
#launcher button#fav-item:active {
background-color: transparent;
border-radius: 11px;
box-shadow: inset 0 0 0 1px rgba(158, 142, 130, 0.04);
}
#launcher button#app-item {
border-radius: 11px;
color: @foreground;
@@ -304,24 +322,6 @@ tooltip label {
color: @foreground;
}
#launcher button#fav-item {
border-radius: 10px;
padding: 10px;
background-image: none;
box-shadow: none;
}
#launcher button#fav-item:hover image,
#launcher button#fav-item:focus image {
-gtk-icon-shadow: 2px 2px @primary;
}
#launcher button#fav-item:active {
background-color: transparent;
border-radius: 11px;
box-shadow: inset 0 0 0 1px rgba(158, 142, 130, 0.04);
}
#launcher button#emoji-item {
border-radius: 11px;
background-color: transparent;
@@ -335,7 +335,7 @@ tooltip label {
}
#launcher button#emoji-item label {
font-size: 27px;
font-size: 26px;
}
#launcher button#emoji-item:hover,
@@ -343,23 +343,6 @@ tooltip label {
text-shadow: 2px 2px 2px @primary;
}
#launcher button#wall-item {
border-radius: 11px;
background-color: transparent;
background-image: none;
box-shadow: none;
padding: 7px;
}
#launcher button#wall-item:disabled {
color: mix(@onSurface, transparent, 0.38);
}
#launcher button#wall-item:hover,
#launcher button#wall-item:focus {
background-color: mix(@onSurfaceVariant, @surface, 0.9);
}
#launcher button#cliphist-item {
border-radius: 11px;
background-color: transparent;
@@ -367,7 +350,7 @@ tooltip label {
box-shadow: none;
}
#launcher button#cliphist-item:disabled {
window#launcher button#cliphist-item:disabled {
color: mix(@onSurface, transparent, 0.38);
}
@@ -387,9 +370,34 @@ tooltip label {
#launcher button#cliphist-img-item:hover,
#launcher button#cliphist-img-item:focus {
box-shadow: 2px 2px 2px @primary;
}
#launcher button#exit-button {
/* background-color: red; */
border-radius: 100px;
}
#launcher button#exit-button:active {
text-shadow: 2px 2px 2px @primary;
}
#launcher button#power-item {
border-radius: 11px;
background-color: transparent;
background-image: none;
box-shadow: none;
}
#launcher button#power-item:disabled {
color: mix(@onSurface, transparent, 0.38);
}
#launcher button#power-item:hover,
#launcher button#power-item:focus {
text-shadow: 2pt 2pt 2pt @primary;
}
#launcher button#sh-item {
border-radius: 11px;
background-color: transparent;
@@ -418,6 +426,22 @@ tooltip label {
text-shadow: 2px 2px 2px @primary;
}
#launcher button#wall-item {
border-radius: 11px;
background-color: transparent;
background-image: none;
box-shadow: none;
padding: 7px;
}
#launcher button#wall-item:disabled {
color: mix(@onSurface, transparent, 0.38);
}
#launcher button#wall-item:hover,
#launcher button#wall-item:focus {
box-shadow: 2pt 2pt 2pt @primary;
}
#osd-container {
background: @surfaceContainer;
padding: 12px;