feat(update): huge changes

This commit is contained in:
sankalp committed 2025-04-25 06:33:51 +05:45
1 parent 2b044338b9
commit aa9eebb9e7
98 files changed
+9636 -5575

No files matched your search

+5 -1
View File
@@ -5,8 +5,12 @@ from .dashboard import *
from .emoji import *
from .power import *
from .sh import *
from .todo import *
from .wallpapers import *
from .wifi import *
from .calendar import *
from .dashboard import *
from .tools import *
from .kanban import *
from .tmux import *
from .window_switcher import *
from .notification_center import *
+517 -161
View File
@@ -1,101 +1,143 @@
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.label import Label
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 fabric.widgets.image import Image
from gi.repository import Gdk, GLib
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.utils import (
DesktopApp,
get_desktop_applications,
idle_add,
remove_handler,
exec_shell_command_async,
)
from fabric.utils.helpers import get_relative_path
from gi.repository import GLib, Gdk
import utils.icons as icons
import config.data as data
import json
import os
import math
import re
import math
import numpy as np
import subprocess
import webbrowser
from functools import partial
from utils import read_config
from modules.dock import Dock # Import the Dock class
class AppLauncher(Box):
def __init__(self, **kwargs):
super().__init__(
name="app-launcher", visible=False, all_visible=False, **kwargs
name="app-launcher",
visible=False,
all_visible=False,
**kwargs,
)
self.scrolled_window = None
self.launcher = kwargs["launcher"]
self.selected_index = -1
self._arranger_handler = 0
self._all_apps = get_desktop_applications()
self.config = read_config()
self.selected_index = -1 # Track the selected item index
self.calc_history_path = os.path.expanduser("~/.cache/modus/calc.json")
self.calc_history = self._load_calc_history()
self._arranger_handler: int = 0
self._all_apps = get_desktop_applications()
self.config = data.read_config()
# Calculator history initialization
self.calc_history_path = f"{data.CACHE_DIR}/calc.json"
if os.path.exists(self.calc_history_path):
with open(self.calc_history_path, "r") as f:
self.calc_history = json.load(f)
else:
self.calc_history = []
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder="Search Applications...",
h_expand=True,
notify_text=self._on_notify_text,
on_activate=self._on_activate,
on_key_press_event=self.on_search_entry_key_press,
notify_text=self.notify_text, # Use the method instead of lambda
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.search_entry.props.xalign = 0.5
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
min_content_size=(450, 105),
max_content_size=(450, 105),
child=self.viewport,
)
self.header_box = Box(
name="header-box", orientation="h", children=[self.search_entry]
name="header_box",
spacing=10,
orientation="h",
children=[
Button(
name="config-button",
child=Label(name="config-label", markup=icons.config),
on_clicked=lambda *_: (
exec_shell_command_async(
f"python {get_relative_path('../../../config/config.py')}"
),
self.close_launcher(),
),
),
self.search_entry,
],
)
self.launcher_box = Box(
name="launcher-box",
spacing=10,
h_expand=True,
orientation="v",
children=[self.header_box],
children=[
self.header_box,
self.scrolled_window,
],
)
self.resize_viewport()
self.add(self.launcher_box)
self.show_all()
def _load_calc_history(self):
if os.path.exists(self.calc_history_path):
with open(self.calc_history_path, "r") as f:
return json.load(f)
return []
def _on_notify_text(self, entry, *args):
self.arrange_viewport(entry.get_text())
def _on_activate(self, entry, *args):
self.on_search_entry_activate(entry.get_text())
def close_launcher(self, *_):
def close_launcher(self):
self.viewport.children = []
self.selected_index = -1
self.selected_index = -1 # Reset selection
self.launcher.close()
self.hide_scrolled_window()
def open_launcher(self):
self._all_apps = get_desktop_applications()
self.arrange_viewport("")
self.arrange_viewport()
def ensure_initialized(self):
"""Make sure the launcher is initialized with apps list before opening"""
if not hasattr(self, "_initialized"):
# Force pre-loading apps
self._all_apps = get_desktop_applications()
self._initialized = True
return True # Was initialized for first time
return False # Was already initialized
def arrange_viewport(self, query: str = ""):
if query.startswith(":"):
self.hide_scrolled_window()
self.launcher.dashboard.hide()
return
if query.startswith("="):
# In calculator mode, update history view once (not per keystroke)
self.show_scrolled_window()
self.launcher.dashboard.hide()
self.update_calculator_viewport()
return
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
self.selected_index = -1 # Clear selection when viewport changes
if query.startswith("/"):
self.launcher.dashboard.hide()
return
if self._arranger_handler:
remove_handler(self._arranger_handler)
self._arranger_handler = 0
self.viewport.children = []
self.selected_index = -1
if query.strip():
self.launcher.dashboard.hide()
self.show_scrolled_window()
@@ -104,171 +146,485 @@ class AppLauncher(Box):
self.hide_scrolled_window()
return False
filtered_apps = [
app
for app in self._all_apps
if query.casefold()
in (
(app.display_name or "")
+ " "
+ app.name
+ " "
+ (app.generic_name or "")
).casefold()
]
filtered_apps_iter = iter(
sorted(filtered_apps, key=lambda app: (app.display_name or "").casefold())
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(),
)
)
should_resize = operator.length_hint(filtered_apps_iter) == len(self._all_apps)
self._arranger_handler = idle_add(
partial(self._arranger_callback, query=query), filtered_apps_iter, pin=True
lambda apps_iter: self.add_next_application(apps_iter)
or self.handle_arrange_complete(should_resize, query),
filtered_apps_iter,
pin=True,
)
def _arranger_callback(self, apps_iter: Iterator[DesktopApp], query: str):
if self.add_next_application(apps_iter):
return True
return self.handle_arrange_complete(query)
def show_scrolled_window(self):
if self.scrolled_window is None:
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
style_classes="applauncher-scrolled-window",
h_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.scrolled_window.show_all()
GLib.idle_add(self.update_scrolled_window_size)
def hide_scrolled_window(self):
if self.scrolled_window:
self.scrolled_window.hide()
def handle_arrange_complete(self, query):
self.update_scrolled_window_size()
if query.strip() and self.viewport.get_children():
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]):
app = next(apps_iter, None)
if app is None:
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) -> Button:
return Button(
name="launcher-app",
def show_scrolled_window(self):
if hasattr(self, "scrolled_window") and self.scrolled_window:
self.scrolled_window.show_all()
def hide_scrolled_window(self):
if hasattr(self, "scrolled_window") and self.scrolled_window:
self.scrolled_window.hide()
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:
button = Button(
name="slot-button",
child=Box(
name="slot-box",
orientation="h",
spacing=10,
children=[
Image(pixbuf=app.get_icon_pixbuf(size=32), h_align="start"),
Image(
name="app-icon",
pixbuf=app.get_icon_pixbuf(size=24),
h_align="start",
),
Label(
name="app-label",
label=app.display_name or "Unknown",
ellipsization="end",
v_align="center",
h_align="center",
),
Label(
name="app-desc",
label=app.description or "",
ellipsization="end",
v_align="center",
h_align="start",
h_expand=True,
),
],
),
tooltip_text=app.description,
on_clicked=partial(self._on_app_clicked, app),
on_clicked=lambda *_: (app.launch(), self.close_launcher()),
**kwargs,
)
def _on_app_clicked(self, app, *args):
app.launch()
self.close_launcher()
return button
def update_selection(self, new_index: int):
children = self.viewport.get_children()
if self.selected_index >= 0 < len(children):
children[self.selected_index].get_style_context().remove_class("selected")
if 0 <= new_index < len(children):
children[new_index].get_style_context().add_class("selected")
# 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 update_scrolled_window_size(self):
if self.scrolled_window is None:
return
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
children = self.viewport.get_children()
item_count = len(children)
y = alloc.y
height = alloc.height
page_size = adj.get_page_size()
current_value = adj.get_value()
if item_count == 0:
self.scrolled_window.set_size_request(-1, 0)
return
# Calculate visible boundaries
visible_top = current_value
visible_bottom = current_value + page_size
first_child = children[0]
first_child_height = first_child.get_allocation().height
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
if first_child_height == 0:
GLib.idle_add(self.update_scrolled_window_size)
return
spacing = self.viewport.props.spacing
total_height = (item_count * first_child_height) + ((item_count - 1) * spacing)
max_height = 400
self.scrolled_window.set_size_request(-1, min(total_height, max_height))
GLib.idle_add(scroll)
def on_search_entry_activate(self, text):
if text.startswith(":i "):
webbrowser.open(f"https://www.google.com/search?q={text[3:].strip()}")
self.close_launcher()
return
# This method is now only used for non-Enter key activations
commands = self.config.get("commands", {})
if text.startswith("="):
# Check if text is a mathematical expression
if text and (text[0].isdigit()):
self.evaluate_calculator_expression(text)
return
children = self.viewport.get_children()
if children:
(children[self.selected_index or 0]).clicked()
if text in commands:
command = commands[text]
eval(command, {"launcher": self.launcher})
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):
if event.keyval in (Gdk.KEY_Down, Gdk.KEY_Up):
self.move_selection(1 if event.keyval == Gdk.KEY_Down else -1)
return True
if event.keyval == Gdk.KEY_Escape:
self.close_launcher()
return True
return False
text = widget.get_text()
# Check if we're in calculator mode
if text.startswith("="):
if event.keyval == Gdk.KEY_Down:
self.move_selection(1)
return True
elif event.keyval == Gdk.KEY_Up:
self.move_selection(-1)
return True
elif event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
# In calculator mode, if a history item is highlighted:
if self.selected_index != -1 and self.selected_index < len(
self.calc_history
):
if event.state & Gdk.ModifierType.SHIFT_MASK:
# Shift+Enter deletes the selected calculator history item
self.delete_selected_calc_history()
else:
# Normal Enter copies the result
selected_text = self.calc_history[self.selected_index]
self.copy_text_to_clipboard(selected_text)
# Clear selection so new expressions are evaluated on further Return presses
self.selected_index = -1
else:
# Force reset selection index
self.selected_index = -1
# No item selected, evaluate the expression
self.evaluate_calculator_expression(text)
return True
elif event.keyval == Gdk.KEY_Escape:
self.close_launcher()
return True
return False
else:
# Normal app mode behavior
if event.keyval == Gdk.KEY_Down:
self.move_selection(1)
return True
elif event.keyval == Gdk.KEY_Up:
self.move_selection(-1)
return True
elif event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter) and (
event.state & Gdk.ModifierType.SHIFT_MASK
):
# Only add to dock when in app mode (not calculator mode)
self.add_selected_app_to_dock()
return True
elif event.keyval == Gdk.KEY_Escape:
self.close_launcher()
return True
return False
def notify_text(self, entry, *_):
"""Handle text changes in the search entry"""
text = entry.get_text()
if text.startswith("="):
# In calculator mode, show scrolled window and update viewport
self.show_scrolled_window()
self.launcher.dashboard.hide()
self.update_calculator_viewport()
# Always reset selection when typing a new expression
self.selected_index = -1
else:
self.arrange_viewport(text)
def add_selected_app_to_dock(self):
"""Adds the currently selected application to the modus.json file with comprehensive metadata."""
children = self.viewport.get_children()
if (
not children
or self.selected_index == -1
or self.selected_index >= len(children)
):
return # No app selected
selected_button = children[self.selected_index]
# Extract the app's display name from the label to find the DesktopApp object
selected_app = next(
(
app
for app in self._all_apps
if app.display_name
== selected_button.get_child().get_children()[1].props.label
),
None,
)
if not selected_app:
return
# Create comprehensive app data dictionary - Include all available properties
# Filter out None values to keep the JSON clean
app_data = {
k: v
for k, v in {
"name": selected_app.name,
"display_name": selected_app.display_name,
"window_class": selected_app.window_class,
"executable": selected_app.executable,
"command_line": selected_app.command_line,
"icon_name": selected_app.icon_name,
}.items()
if v is not None
}
config_path = get_relative_path("../../../config/assets/modus.json")
try:
with open(config_path, "r") as file:
data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
data = {"pinned_apps": []}
# Check if app is already pinned (by name)
already_pinned = False
for pinned_app in data.get("pinned_apps", []):
if (
isinstance(pinned_app, dict)
and pinned_app.get("name") == app_data["name"]
):
already_pinned = True
# Update existing entry with latest app data
pinned_app.update(app_data)
break
elif isinstance(pinned_app, str) and pinned_app == app_data["name"]:
already_pinned = True
# Replace string format with new comprehensive format
data["pinned_apps"].remove(pinned_app)
data["pinned_apps"].append(app_data)
break
# Add to pinned apps if not already there
if not already_pinned:
data.setdefault("pinned_apps", []).append(app_data)
# Write the updated config
with open(config_path, "w") as file:
json.dump(data, file, indent=4)
# Notify dock instances of the configuration change immediately
Dock.notify_config_change()
def move_selection(self, delta: int):
children = self.viewport.get_children()
if not children:
return
new_index = max(0, min(self.selected_index + delta, len(children) - 1))
# 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)
def evaluate_calculator_expression(self, text: str):
expr = text.lstrip("=").replace("^", "**").replace("×", "*")
expr = re.sub(r"(\d+)!", r"math.factorial(\1)", expr)
result = eval(expr, {"__builtins__": None, "math": math})
self.calc_history.insert(0, f"{text} => {result}")
self.save_calc_history()
self.update_calculator_viewport()
def update_calculator_viewport(self):
self.viewport.children = [
Button(
child=Label(label=item),
on_clicked=partial(self.copy_text_to_clipboard, item),
)
for item in self.calc_history
]
self.update_scrolled_window_size()
def save_calc_history(self):
with open(self.calc_history_path, "w") as f:
json.dump(self.calc_history, f)
def copy_text_to_clipboard(self, text: str, *args):
subprocess.run(
["wl-copy"], input=text.split("=>", 1)[-1].strip().encode(), check=True
)
def evaluate_calculator_expression(self, text: str):
# Add debug print
print(f"Evaluating calculator expression: {text}")
# Remove the '=' prefix and extra spaces
expr = text.lstrip("=").strip()
if not expr:
return
# Common replacements to make expressions more natural
replacements = {
"^": "**", # Power operator
"×": "*", # Multiplication
"÷": "/", # Division
"π": "np.pi", # Pi constant
"pi": "np.pi", # Pi constant (text)
"e": "np.e", # Euler's number
"sin(": "np.sin(", # Sine
"cos(": "np.cos(", # Cosine
"tan(": "np.tan(", # Tangent
"log(": "np.log10(", # Log base 10
"ln(": "np.log(", # Natural log
"sqrt(": "np.sqrt(", # Square root
"abs(": "np.abs(", # Absolute value
"exp(": "np.exp(", # Exponential
}
# Apply all replacements
for old, new in replacements.items():
expr = expr.replace(old, new)
# Replace factorial: e.g. 5! -> np.factorial(5)
expr = re.sub(r"(\d+)!", r"np.factorial(\1)", expr)
# Replace brackets: allow [] and {} as ()
for old, new in [("[", "("), ("]", ")"), ("{", "("), ("}", ")")]:
expr = expr.replace(old, new)
# Define the safe execution environment
safe_dict = {
"np": np,
"math": math,
"arange": np.arange,
"linspace": np.linspace,
"array": np.array,
}
try:
# Evaluate the expression in the safe environment
result = eval(expr, {"__builtins__": None}, safe_dict)
# Format the result based on its type
if isinstance(result, np.ndarray):
if result.size > 10: # Truncate large arrays
result_str = f"Array of shape {result.shape}"
else:
result_str = str(result)
elif isinstance(result, (int, float, np.number)):
# Format numbers nicely - integers as integers, floats with limited precision
if isinstance(result, (int, np.integer)) or result.is_integer():
result_str = str(int(result))
else:
result_str = f"{float(result):.10g}" # Remove trailing zeros
else:
result_str = str(result)
except Exception as e:
result_str = f"Error: {str(e)}"
# Prepend to history (newest first)
self.calc_history.insert(0, f"{text} => {result_str}")
self.save_calc_history()
self.update_calculator_viewport()
def update_calculator_viewport(self):
self.viewport.children = []
for item in self.calc_history:
btn = self.create_calc_history_button(item)
self.viewport.add(btn)
# Don't reset selection index here automatically
# Ensure selection state stays valid
if self.selected_index >= len(self.calc_history):
self.selected_index = -1
def create_calc_history_button(self, text: str) -> Button:
# Parse the result to create a more readable display
if "=>" in text:
parts = text.split("=>")
expression = parts[0].strip()
result = parts[1].strip()
# For very long results, truncate for display but keep full in tooltip
display_text = text
if len(result) > 50: # Truncate long results
display_text = f"{expression} => {result[:47]}..."
btn = Button(
name="slot-button", # reuse existing CSS styling
child=Box(
name="calc-slot-box",
orientation="h",
spacing=10,
children=[
Label(
name="calc-label",
label=display_text,
ellipsization="end",
v_align="center",
h_align="center",
),
],
),
tooltip_text=text,
on_clicked=lambda *_: self.copy_text_to_clipboard(text),
)
else:
# Fallback for non-calculation entries
btn = Button(
name="slot-button",
child=Box(
name="calc-slot-box",
orientation="h",
spacing=10,
children=[
Label(
name="calc-label",
label=text,
ellipsization="end",
v_align="center",
h_align="center",
),
],
),
tooltip_text=text,
on_clicked=lambda *_: self.copy_text_to_clipboard(text),
)
return btn
def copy_text_to_clipboard(self, text: str):
# Split the text on "=>" and copy only the result part if available
parts = text.split("=>", 1)
copy_text = parts[1].strip() if len(parts) > 1 else text
try:
subprocess.run(["wl-copy"], input=copy_text.encode(), check=True)
except subprocess.CalledProcessError as e:
print(f"Clipboard copy failed: {e}")
def delete_selected_calc_history(self):
if self.selected_index != -1 and self.selected_index < len(self.calc_history):
# Store the current index before deletion
current_index = self.selected_index
# Delete the item
del self.calc_history[current_index]
self.save_calc_history()
# Determine the new selection index
# If we deleted the first item, stay at index 0
# Otherwise, move to the previous item
new_index = 0 if current_index == 0 else current_index - 1
# Reset selection before updating viewport
self.selected_index = -1
# Update the viewport
self.update_calculator_viewport()
# If we still have items, select the determined index
if len(self.calc_history) > 0:
self.update_selection(min(new_index, len(self.calc_history) - 1))
+35 -35
View File
@@ -30,7 +30,7 @@ class BluetoothDeviceSlot(CenterBox):
Box(
spacing=8,
children=[
Image(icon_name=f"{device.icon_name}-symbolic", size=32),
Image(icon_name=device.icon_name + "-symbolic", size=32),
Label(label=device.name),
self.connection_label,
],
@@ -61,7 +61,7 @@ class BluetoothConnections(Box):
def __init__(self, **kwargs):
super().__init__(
name="bluetooth",
spacing=8,
spacing=4,
orientation="vertical",
**kwargs,
)
@@ -77,63 +77,54 @@ class BluetoothConnections(Box):
self.bt_menu_label = self.buttons.bluetooth_menu_label
self.client = BluetoothClient(on_device_added=self.on_device_added)
self.scan_label = Label(name="bluetooth-scan-label", markup=icons.radar)
self.scan_button = Button(
name="bluetooth-scan",
child=Label(name="bluetooth-scan-icon", markup=icons.scan_stop),
child=self.scan_label,
tooltip_text="Scan for Bluetooth devices",
on_clicked=lambda *_: self.client.toggle_scan(),
)
self.toggle_button = Button(
name="bluetooth-toggle",
child=Label(name="bluetooth-toggle-icon", markup=icons.bluetooth_off),
on_clicked=lambda *_: self.client.toggle_power(),
self.back_button = Button(
name="bluetooth-back",
child=Label(name="bluetooth-back-label", markup=icons.chevron_left),
on_clicked=lambda *_: self.launcher.open("launcher"),
)
self.client.connect(
"notify::enabled",
lambda *_: self.status_label(),
)
self.client.connect(
"notify::scanning",
lambda *_: self.scan_button.get_child().set_markup(
icons.scan_stop if self.client.scanning else icons.scan
),
)
self.client.connect("notify::enabled", lambda *_: self.status_label())
self.client.connect("notify::scanning", lambda *_: self.update_scan_label())
self.paired_box = Box(spacing=2, orientation="vertical")
self.available_box = Box(spacing=2, orientation="vertical")
# Create a single content container with the required structure:
# [Paired label] [Paired devices list] [Available label] [Available devices list]
content_box = Box(spacing=4, orientation="vertical")
content_box.add(self.paired_box)
content_box.add(Label(name="bluetooth-section", label="Available"))
content_box.add(self.available_box)
self.children = [
CenterBox(
name="bluetooth-header",
start_children=self.scan_button,
start_children=self.back_button,
center_children=Label(name="bluetooth-text", label="Bluetooth Devices"),
end_children=self.toggle_button,
end_children=self.scan_button,
),
Label(name="bluetooth-section", label="Paired"),
ScrolledWindow(
name="bluetooth-paired",
name="bluetooth-devices",
min_content_size=(-1, -1),
child=self.paired_box,
v_expand=True,
),
Label(name="bluetooth-section", label="Available"),
ScrolledWindow(
name="bluetooth-available",
min_content_size=(-1, -1),
child=self.available_box,
child=content_box,
v_expand=True,
),
]
# to run notify closures thus display the status
# without having to wait until an actual change
# Trigger initial notifications to update status without delay.
self.client.notify("scanning")
self.client.notify("enabled")
def status_label(self):
print(self.client.enabled)
if self.client.enabled:
self.toggle_button.get_child().set_markup(icons.bluetooth)
self.bt_status_text.set_label("Enabled")
for i in [
self.bt_status_button,
@@ -146,7 +137,6 @@ class BluetoothConnections(Box):
i.remove_style_class("disabled")
self.bt_icon.set_markup(icons.bluetooth)
else:
self.toggle_button.get_child().set_markup(icons.bluetooth_off)
self.bt_status_text.set_label("Disabled")
for i in [
self.bt_status_button,
@@ -165,6 +155,16 @@ class BluetoothConnections(Box):
slot = BluetoothDeviceSlot(device)
if device.paired:
self.paired_box.add(slot)
return self.paired_box.add(slot)
return self.available_box.add(slot)
def update_scan_label(self):
if self.client.scanning:
self.scan_label.add_style_class("scanning")
self.scan_button.add_style_class("scanning")
self.scan_button.set_tooltip_text("Stop scanning for Bluetooth devices")
else:
self.available_box.add(slot)
self.scan_label.remove_style_class("scanning")
self.scan_button.remove_style_class("scanning")
self.scan_button.set_tooltip_text("Scan for Bluetooth devices")
+36 -18
View File
@@ -1,11 +1,13 @@
import calendar
from datetime import datetime
import gi
import utils.icons as icons
from fabric.widgets.label import Label
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib
import utils.icons as icons
class Calendar(Gtk.Box):
@@ -17,36 +19,47 @@ class Calendar(Gtk.Box):
self.current_year = datetime.now().year
self.current_month = datetime.now().month
self.current_day = datetime.now().day
# Store previous month/year to determine transition direction.
self.previous_key = (self.current_year, self.current_month)
# Cache threshold in number of months away from the current view.
self.cache_threshold = 1 # Allow current month +/- 1 month
self.month_views = {}
self.header = Gtk.Box(spacing=4, name="header")
self.pack_start(self.header, False, False, 0)
# Dictionary to store built views for each month.
self.month_views = {}
self.prev_month_button = Gtk.Button(
name="prev-month-button",
child=Label(name="month-button-label", markup=icons.chevron_left),
)
self.prev_month_button.connect("clicked", self.on_prev_month_clicked)
self.header.pack_start(self.prev_month_button, False, False, 0)
self.month_label = Gtk.Label(name="month-label")
self.header.pack_start(self.month_label, True, True, 0)
self.next_month_button = Gtk.Button(
name="next-month-button",
child=Label(name="month-button-label", markup=icons.chevron_right),
)
self.next_month_button.connect("clicked", self.on_next_month_clicked)
self.header.pack_start(self.next_month_button, False, False, 0)
self.header = CenterBox(
spacing=4,
name="header",
start_children=[self.prev_month_button],
center_children=[
self.month_label,
],
end_children=[self.next_month_button],
)
self.add(self.header)
self.weekday_row = Gtk.Box(spacing=4, name="weekday-row")
self.pack_start(self.weekday_row, False, False, 0)
# Create a stack to hold month days views.
self.stack = Gtk.Stack(name="calendar-stack")
self.stack.set_transition_duration(500)
self.stack.set_transition_duration(250)
self.pack_start(self.stack, True, True, 0)
self.update_header()
@@ -54,14 +67,15 @@ class Calendar(Gtk.Box):
GLib.timeout_add_seconds(60, self.check_date_change)
def update_header(self):
# Update header month label and weekday row.
self.month_label.set_text(
datetime(self.current_year, self.current_month, 1)
.strftime("%B %Y")
.capitalize()
)
# Clear existing children from weekday_row.
for child in self.weekday_row.get_children():
self.weekday_row.remove(child)
days = self.get_weekday_initials()
for day in days:
label = Gtk.Label(label=day.upper(), name="weekday-label")
@@ -70,14 +84,15 @@ class Calendar(Gtk.Box):
def update_calendar(self):
new_key = (self.current_year, self.current_month)
# Set the transition type based on whether we're moving to a later or earlier month.
if new_key > self.previous_key:
self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT)
elif new_key < self.previous_key:
self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_RIGHT)
# Update previous key for next comparison.
self.previous_key = new_key
# Create the month view if it doesn't exist.
if new_key not in self.month_views:
month_view = self.create_month_view(self.current_year, self.current_month)
self.month_views[new_key] = month_view
@@ -86,24 +101,25 @@ class Calendar(Gtk.Box):
f"{self.current_year}_{self.current_month}",
f"{self.current_year}_{self.current_month}",
)
# Switch the visible child in the stack.
self.stack.set_visible_child_name(f"{self.current_year}_{self.current_month}")
self.update_header()
self.stack.show_all()
# Purge any cached month views that are too far away.
self.prune_cache()
def prune_cache(self):
# Compute a numerical value for a (year, month) key.
def month_index(key):
year, month = key
return year * 12 + (month - 1)
current_index = month_index((self.current_year, self.current_month))
keys_to_remove = [
key
for key in self.month_views
if abs(month_index(key) - current_index) > self.cache_threshold
]
keys_to_remove = []
for key in self.month_views:
if abs(month_index(key) - current_index) > self.cache_threshold:
keys_to_remove.append(key)
for key in keys_to_remove:
widget = self.month_views.pop(key)
self.stack.remove(widget)
@@ -167,6 +183,7 @@ class Calendar(Gtk.Box):
return grid
def get_weekday_initials(self):
# Returns localized weekday initials.
return [datetime(2023, 1, i + 1).strftime("%a")[:1] for i in range(7)]
def on_prev_month_clicked(self, widget):
@@ -197,3 +214,4 @@ class Calendar(Gtk.Box):
self.current_year = now.year
self.update_calendar()
return True
+454 -151
View File
@@ -1,201 +1,504 @@
import os
import subprocess
from typing import List
from fabric import Fabricator
from fabric.widgets.box import Box
from fabric.widgets.label import Label
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.scrolledwindow import ScrolledWindow
from gi.repository import GLib
from fabric.utils import idle_add, remove_handler
from fabric.utils.helpers import get_relative_path
from gi.repository import GLib, Gdk, GdkPixbuf
import subprocess
import os
import re
import sys
import tempfile
import utils.icons as icons
class Cliphist(Box):
class ClipHistory(Box):
def __init__(self, **kwargs):
super().__init__(
name="cliphist-launcher",
all_visible=False,
name="clip-history",
visible=False,
all_visible=False,
**kwargs,
)
self._arranger_handler = 0
self.cliphist_manager = CliphistManager(self)
self.viewport = None
self.launcher = kwargs["launcher"]
# Create a temporary directory for image icons
self.tmp_dir = tempfile.mkdtemp(prefix="cliphist-")
self.image_cache = {} # Cache for image previews
self.launcher = kwargs["launcher"]
self.selected_index = -1 # Track the selected item index
self._arranger_handler = 0
self.clipboard_items = []
self._loading = False
self._pending_updates = False
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder="Search Clipboard History...",
h_expand=True,
on_activate=self._on_search_activate,
notify_text=self.filter_items,
on_activate=lambda entry, *_: self.use_selected_item(),
on_key_press_event=self.on_search_entry_key_press,
)
self.search_entry.props.xalign = 0.5
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
min_content_size=(450, 105),
max_content_size=(450, 105),
child=self.viewport,
)
self.header_box = Box(
name="header-box",
name="header_box",
spacing=10,
orientation="h",
children=[
self.search_entry,
Button(
name="clear-button",
child=Label(name="cliphist-clear-button", markup=icons.clear),
tooltip_text="Clear Clipboard History",
on_clicked=self.handle_clear_history,
child=Label(name="clear-label", markup=icons.trash),
on_clicked=lambda *_: self.clear_history(),
),
self.search_entry,
],
)
self.launcher_box = Box(
name="cliphist-launcher-box",
self.history_box = Box(
name="launcher-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
orientation="v",
children=[
self.header_box,
self.scrolled_window,
],
)
self.add(self.launcher_box)
def _on_search_activate(self, entry, *args):
self.handle_search(entry.get_text())
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,
min_content_size=(-1, -1),
h_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.add(self.history_box)
self.show_all()
def close(self):
"""Close the clipboard history panel"""
self.viewport.children = []
self.cliphist_manager.update_cliphist_history()
self.viewport.show()
self.search_entry.grab_focus()
def handle_search(self, text: str):
self.cliphist_manager.arrange_viewport(query=text)
def close_launcher(self):
self.selected_index = -1 # Reset selection
self.launcher.close()
def handle_clear_history(self, *_):
GLib.spawn_command_line_async("cliphist wipe")
self.cliphist_manager.update_cliphist_history()
def open(self):
"""Open the clipboard history panel and load items"""
self.viewport.set_visible(True)
if self._loading:
return
self._loading = True
self.search_entry.set_text("") # Clear search
self.search_entry.grab_focus()
# Start loading in background using GLib.idle_add
GLib.idle_add(self._load_clipboard_items_thread)
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", self._on_wl_paste_changed)
def _on_wl_paste_changed(self, *args):
self.update_cliphist_history()
def get_clip_history(self) -> List[dict]:
def _load_clipboard_items_thread(self):
"""Worker for loading clipboard items, now runs in main loop via idle_add"""
try:
result = subprocess.run(
["cliphist", "list"], capture_output=True, text=True, check=True
)
return self._parse_clip_history(result.stdout)
lines = result.stdout.strip().split("\n")
new_items = []
for line in lines:
if not line or "<meta http-equiv" in line:
continue
new_items.append(line)
self._update_items(new_items)
except subprocess.CalledProcessError as e:
print(f"Error fetching cliphist history: {e}")
return []
print(f"Error loading clipboard history: {e}", file=sys.stderr)
except Exception as e:
print(f"Unexpected error: {e}", file=sys.stderr)
finally:
self._loading = False
if self._pending_updates:
self._pending_updates = False
GLib.idle_add(self._load_clipboard_items_thread)
return False # Ensure idle_add does not repeat
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
def _update_items(self, new_items):
"""Update the items list from main thread"""
self.clipboard_items = new_items
self.display_clipboard_items()
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 display_clipboard_items(self, filter_text=""):
"""Display clipboard items in the viewport"""
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
self.selected_index = -1 # Reset selection
def save_image_file(self, clip_id: str) -> str:
output_file = f"/tmp/cliphist-{clip_id}.png"
os.makedirs("/tmp", 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 image file for clip {clip_id}: {e}")
return ""
# Filter items if search text is provided
filtered_items = []
for item in self.clipboard_items:
# Extract just the content part (after the first tab)
content = item.split("\t", 1)[1] if "\t" in item else item
if filter_text.lower() in content.lower():
filtered_items.append(item)
def update_cliphist_history(self):
self.cliphist_history = self.get_clip_history()
self.arrange_viewport()
def query_clips(self, query: str = "") -> List[dict]:
if not query.strip():
return self.cliphist_history
return [
clip
for clip in self.cliphist_history
if query.lower() in clip["content"].lower()
]
def _on_clip_clicked(self, clip_id: str, *args):
self.copy_clip(clip_id)
def bake_clip_slot(self, item: dict) -> Button:
if "[[ binary data" 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_image_file(item["id"])
if output_file and os.path.exists(output_file):
button = Button(
h_align="start",
name="clip-img-item",
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
)
button.set_style(
f"background-image: url('{output_file}'); background-size: cover; background-position: center;"
)
return button
return None
def _create_text_button(self, item: dict) -> Button:
return Button(
child=Label(
label=item["content"][:35]
+ ("..." if len(item["content"]) > 35 else ""),
h_expand=True,
# Show message if no items are found
if not filtered_items:
# Create a container box to better center the message
container = Box(
name="no-clip-container",
orientation="v",
h_align="center",
v_align="center",
h_align="start",
),
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
name="clip-item",
h_expand=True,
v_expand=True,
)
# Show a message if no clipboard items
label = Label(
name="no-clip",
markup=icons.clipboard,
h_align="center",
v_align="center",
)
container.add(label)
self.viewport.add(container)
return
# Display items in batches to prevent UI freeze
self._display_items_batch(filtered_items, 0, 10)
def _display_items_batch(self, items, start, batch_size):
"""Display items in batches to keep UI responsive"""
end = min(start + batch_size, len(items))
for i in range(start, end):
item = items[i]
self.viewport.add(self.create_clipboard_item(item))
# Schedule next batch if there are more items
if end < len(items):
GLib.idle_add(self._display_items_batch, items, end, batch_size)
else:
# Auto-select first item if we have filter text
if self.search_entry.get_text() and self.viewport.get_children():
self.update_selection(0)
def create_clipboard_item(self, item):
"""Create a button for a clipboard item"""
# Extract ID and content
parts = item.split("\t", 1)
item_id = parts[0] if len(parts) > 1 else "0"
content = parts[1] if len(parts) > 1 else item
# Truncate content for display
display_text = content.strip()
if len(display_text) > 100:
display_text = display_text[:97] + "..."
# Check if this is an image by examining the content
is_image = self.is_image_data(content)
if is_image:
# For images, create item with image preview
button = Button(
name="slot-button",
child=Box(
name="slot-box",
orientation="h",
spacing=10,
children=[
Image(name="clip-icon", h_align="start"), # Placeholder
Label(
name="clip-label",
label="[Image]",
ellipsization="end",
v_align="center",
h_align="start",
h_expand=True,
),
],
),
tooltip_text="Image in clipboard",
on_clicked=lambda *_, id=item_id: self.paste_item(id),
)
# Load image preview in background
self._load_image_preview_async(item_id, button)
else:
# For text, create regular item
button = self.create_text_item_button(item_id, display_text)
# Add key press event handler for Enter key
button.connect(
"key-press-event",
lambda widget, event, id=item_id: self.on_item_key_press(widget, event, id),
)
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
# Make sure button can receive focus and key events
button.set_can_focus(True)
button.add_events(Gdk.EventMask.KEY_PRESS_MASK)
return button
def _load_image_preview_async(self, item_id, button):
"""Load image preview using GLib.idle_add instead of threads"""
def load_image():
try:
if item_id in self.image_cache:
pixbuf = self.image_cache[item_id]
else:
result = subprocess.run(
["cliphist", "decode", item_id], capture_output=True, check=True
)
loader = GdkPixbuf.PixbufLoader()
loader.write(result.stdout)
loader.close()
pixbuf = loader.get_pixbuf()
width, height = pixbuf.get_width(), pixbuf.get_height()
max_size = 72
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
pixbuf = pixbuf.scale_simple(
new_width, new_height, GdkPixbuf.InterpType.BILINEAR
)
self.image_cache[item_id] = pixbuf
self._update_image_button(button, pixbuf)
except Exception as e:
print(f"Error loading image preview: {e}", file=sys.stderr)
return False
GLib.idle_add(load_image)
def _update_image_button(self, button, pixbuf):
"""Update the button with the loaded image preview"""
box = button.get_child()
if box and len(box.get_children()) > 0:
image_widget = box.get_children()[0]
if isinstance(image_widget, Image):
image_widget.set_from_pixbuf(pixbuf)
def create_text_item_button(self, item_id, display_text):
"""Create a button for a text clipboard item"""
return Button(
name="slot-button",
child=Box(
name="slot-box",
orientation="h",
spacing=10,
children=[
Label(
name="clip-icon",
markup=icons.clip_text,
h_align="start",
),
Label(
name="clip-label",
label=display_text,
ellipsization="end",
v_align="center",
h_align="start",
h_expand=True,
),
],
),
tooltip_text=display_text,
on_clicked=lambda *_: self.paste_item(item_id),
)
def is_image_data(self, content):
"""Determine if clipboard content is likely an image"""
# Check for common image data patterns
return (
content.startswith("data:image/")
or content.startswith("\x89PNG")
or content.startswith("GIF8")
or content.startswith("\xff\xd8\xff") # JPEG
or re.match(r"^\s*<img\s+", content) is not None # HTML image tag
or "binary" in content.lower()
and any(
ext in content.lower() for ext in ["jpg", "jpeg", "png", "bmp", "gif"]
)
)
def paste_item(self, item_id):
"""Copy the selected item to the clipboard and close (GLib.idle_add)"""
def paste():
try:
result = subprocess.run(
["cliphist", "decode", item_id], capture_output=True, check=True
)
subprocess.run(["wl-copy"], input=result.stdout, check=True)
GLib.idle_add(self.close)
except subprocess.CalledProcessError as e:
print(f"Error pasting clipboard item: {e}", file=sys.stderr)
return False
GLib.idle_add(paste)
def delete_item(self, item_id):
"""Delete the selected clipboard item (GLib.idle_add)"""
def delete():
try:
subprocess.run(["cliphist", "delete", item_id], check=True)
self._pending_updates = True
if not self._loading:
GLib.idle_add(self._load_clipboard_items_thread)
except subprocess.CalledProcessError as e:
print(f"Error deleting clipboard item: {e}", file=sys.stderr)
return False
GLib.idle_add(delete)
def clear_history(self):
"""Clear all clipboard history (GLib.idle_add)"""
def clear():
try:
subprocess.run(["cliphist", "wipe"], check=True)
self._pending_updates = True
if not self._loading:
GLib.idle_add(self._load_clipboard_items_thread)
except subprocess.CalledProcessError as e:
print(f"Error clearing clipboard history: {e}", file=sys.stderr)
return False
GLib.idle_add(clear)
def filter_items(self, entry, *_):
"""Filter clipboard items based on search text"""
self.display_clipboard_items(entry.get_text())
def on_search_entry_key_press(self, widget, event):
"""Handle key presses in the search entry"""
if event.keyval == Gdk.KEY_Down:
self.move_selection(1)
return True
elif event.keyval == Gdk.KEY_Up:
self.move_selection(-1)
return True
elif event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
self.use_selected_item()
return True
elif event.keyval == Gdk.KEY_Delete:
self.delete_selected_item()
return True
elif event.keyval == Gdk.KEY_Escape:
self.close()
return True
return False
def update_selection(self, new_index):
"""Update the selected item in the viewport"""
children = self.viewport.get_children()
# Unselect current
if self.selected_index != -1 and self.selected_index < len(children):
current_button = children[self.selected_index]
current_button.get_style_context().remove_class("selected")
# Select new
if new_index != -1 and new_index < len(children):
new_button = 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 move_selection(self, delta):
"""Move the selection up or down"""
children = self.viewport.get_children()
if not children:
return
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)
# Allow starting selection from nothing
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)
def scroll_to_selected(self, button):
"""Scroll to ensure the selected item is visible"""
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)
return False
GLib.idle_add(scroll)
def use_selected_item(self):
"""Use (paste) the selected clipboard item"""
children = self.viewport.get_children()
if (
not children
or self.selected_index == -1
or self.selected_index >= len(self.clipboard_items)
):
return
# Get the item ID from the first part before the tab
item_line = self.clipboard_items[self.selected_index]
item_id = item_line.split("\t", 1)[0]
self.paste_item(item_id)
def delete_selected_item(self):
"""Delete the selected clipboard item"""
children = self.viewport.get_children()
if not children or self.selected_index == -1:
return
# Get the item ID from the first part before the tab
item_line = self.clipboard_items[self.selected_index]
item_id = item_line.split("\t", 1)[0]
self.delete_item(item_id)
def on_item_key_press(self, widget, event, item_id):
"""Handle key press events on clipboard items"""
if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
# Copy item to clipboard and close
self.paste_item(item_id)
return True
return False
def __del__(self):
"""Clean up temporary files on destruction"""
try:
if hasattr(self, "tmp_dir") and os.path.exists(self.tmp_dir):
import shutil
shutil.rmtree(self.tmp_dir)
self.image_cache.clear()
except Exception as e:
print(f"Error cleaning up temporary files: {e}", file=sys.stderr)
+258 -83
View File
@@ -1,12 +1,13 @@
import subprocess
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.utils.helpers import exec_shell_command_async, exec_shell_command
from fabric.utils.helpers import exec_shell_command_async
import gi
from gi.repository import Gtk, Gdk, GLib # Added Gdk import
from fabric.utils import get_relative_path
from gi.repository import Gtk, Gdk, GLib
from services import network_client
from services.powerprofile import PowerProfiles
from fabric import Fabricator
gi.require_version("Gtk", "3.0")
import utils.icons as icons
@@ -31,9 +32,14 @@ def add_hover_cursor(widget):
class NetworkButton(Box):
def __init__(self):
self.network_client = network_client
self._animation_timeout_id = None
self._animation_step = 0
self._animation_direction = 1
self.network_icon = Label(
name="network-icon",
markup=icons.wifi,
markup=None,
)
self.network_label = Label(
name="network-label",
@@ -43,7 +49,6 @@ class NetworkButton(Box):
self.network_label_box = Box(children=[self.network_label, Box(h_expand=True)])
self.network_ssid = Label(
name="network-ssid",
label="Hello_World!!",
justification="left",
)
self.network_ssid_box = Box(children=[self.network_ssid, Box(h_expand=True)])
@@ -64,6 +69,9 @@ class NetworkButton(Box):
name="network-status-button",
h_expand=True,
child=self.network_status_box,
on_clicked=lambda *_: self.network_client.wifi_device.toggle_wifi()
if self.network_client.wifi_device
else None,
)
add_hover_cursor(self.network_status_button) # <-- Added hover
@@ -88,6 +96,148 @@ class NetworkButton(Box):
children=[self.network_status_button, self.network_menu_button],
)
self.widgets = [
self,
self.network_icon,
self.network_label,
self.network_ssid,
self.network_status_button,
self.network_menu_button,
self.network_menu_label,
]
# Connect to wifi device signals when ready
self.network_client.connect("device-ready", self._on_wifi_ready)
# Check initial state using idle_add to defer until GTK loop is running
GLib.idle_add(self._initial_update)
def _initial_update(self):
self.update_state()
return False # Run only once
def _on_wifi_ready(self, *args):
if self.network_client.wifi_device:
self.network_client.wifi_device.connect(
"notify::enabled", self.update_state
)
self.network_client.wifi_device.connect("notify::ssid", self.update_state)
self.update_state()
def _animate_searching(self):
"""Animate wifi icon when searching for networks"""
wifi_icons = [
icons.wifi_0,
icons.wifi_1,
icons.wifi_2,
icons.wifi_3,
icons.wifi_2,
icons.wifi_1,
]
# Si el widget no existe o el WiFi está desactivado, detener la animación
wifi = self.network_client.wifi_device
if not self.network_icon or not wifi or not wifi.enabled:
self._stop_animation()
return False
# Si estamos conectados, detener la animación
if wifi.state == "activated" and wifi.ssid != "Disconnected":
self._stop_animation()
return False
GLib.idle_add(self.network_icon.set_markup, wifi_icons[self._animation_step])
# Reiniciar al principio cuando llegamos al final
self._animation_step = (self._animation_step + 1) % len(wifi_icons)
return True # Mantener la animación activa
def _start_animation(self):
if self._animation_timeout_id is None:
self._animation_step = 0
self._animation_direction = 1
# Ejecuta la animación cada 500ms sin usar idle_add
self._animation_timeout_id = GLib.timeout_add(500, self._animate_searching)
def _stop_animation(self):
if self._animation_timeout_id is not None:
GLib.source_remove(self._animation_timeout_id)
self._animation_timeout_id = None
def update_state(self, *args):
"""Update the button state based on network status"""
wifi = self.network_client.wifi_device
ethernet = self.network_client.ethernet_device
# Update enabled/disabled state
if wifi and not wifi.enabled:
self._stop_animation()
self.network_icon.set_markup(icons.wifi_off)
for widget in self.widgets:
widget.add_style_class("disabled")
self.network_ssid.set_label("Disabled")
return
# Remove disabled class if we got here
for widget in self.widgets:
widget.remove_style_class("disabled")
# Update text and animation based on state
if wifi and wifi.enabled:
if wifi.state == "activated" and wifi.ssid != "Disconnected":
self._stop_animation()
self.network_ssid.set_label(wifi.ssid)
# Update icon based on signal strength
if wifi.strength > 0:
strength = wifi.strength
if strength < 25:
self.network_icon.set_markup(icons.wifi_0)
elif strength < 50:
self.network_icon.set_markup(icons.wifi_1)
elif strength < 75:
self.network_icon.set_markup(icons.wifi_2)
else:
self.network_icon.set_markup(icons.wifi_3)
else:
self.network_ssid.set_label("Enabled")
self._start_animation()
# Handle primary device check safely
try:
primary_device = self.network_client.primary_device
except AttributeError:
primary_device = "wireless" # Default to wireless if error occurs
# Handle wired connection case
if primary_device == "wired":
self._stop_animation()
if ethernet and ethernet.internet == "activated":
self.network_icon.set_markup(icons.world)
else:
self.network_icon.set_markup(icons.world_off)
else:
if not wifi:
self._stop_animation()
self.network_icon.set_markup(icons.wifi_off)
elif (
wifi.state == "activated"
and wifi.ssid != "Disconnected"
and wifi.strength > 0
):
self._stop_animation()
strength = wifi.strength
if strength < 25:
self.network_icon.set_markup(icons.wifi_0)
elif strength < 50:
self.network_icon.set_markup(icons.wifi_1)
elif strength < 75:
self.network_icon.set_markup(icons.wifi_2)
else:
self.network_icon.set_markup(icons.wifi_3)
else:
self._start_animation()
class BluetoothButton(Box):
def __init__(self, launcher):
@@ -205,7 +355,16 @@ class NightModeButton(Button):
self.night_mode_status,
self.night_mode_icon,
]
self.check_hyprsunset()
# self.check_hyprsunset()
# **Monitor external changes every 3 seconds**
self.hyprsunset_watcher = Fabricator(
self.is_hyprsunset_running,
interval=3000,
stream=False,
default_value=False,
)
self.hyprsunset_watcher.changed.connect(self.update_night_mode_status)
self.update_night_mode_status(None, self.is_hyprsunset_running())
def toggle_hyprsunset(self, *args):
"""
@@ -225,16 +384,21 @@ class NightModeButton(Button):
for widget in self.widgets:
widget.remove_style_class("disabled")
def check_hyprsunset(self, *args):
"""
Update the button state based on whether hyprsunset is running.
"""
def is_hyprsunset_running(self, *args):
"""Returns True if hyprsunset is running."""
try:
subprocess.check_output(["pgrep", "hyprsunset"])
return True
except subprocess.CalledProcessError:
return False
def update_night_mode_status(self, _, is_running):
"""Update UI based on hyprsunset status."""
if is_running:
self.night_mode_status.set_label("Enabled")
for widget in self.widgets:
widget.remove_style_class("disabled")
except subprocess.CalledProcessError:
else:
self.night_mode_status.set_label("Disabled")
for widget in self.widgets:
widget.add_style_class("disabled")
@@ -289,117 +453,128 @@ class CaffeineButton(Button):
self.caffeine_status,
self.caffeine_icon,
]
self.check_wlinhibit()
# **Monitor external changes every 3 seconds**
self.wlinhibit_watcher = Fabricator(
self.is_wlinhibit_running,
interval=3000,
stream=False,
default_value=False,
)
self.wlinhibit_watcher.changed.connect(self.update_wlinhibit_status)
self.update_wlinhibit_status(None, self.is_wlinhibit_running())
def toggle_wlinhibit(self, *args):
"""
Toggle the 'wlinhibit' process:
- If running, kill it and mark as 'Disabled' (add 'disabled' class).
- If not running, start it and mark as 'Enabled' (remove 'disabled' class).
"""
try:
subprocess.check_output(["pgrep", "wlinhibit"])
"""Toggle the 'wlinhibit' process."""
if self.is_wlinhibit_running():
exec_shell_command_async("pkill wlinhibit")
self.caffeine_status.set_label("Disabled")
for i in self.widgets:
i.add_style_class("disabled")
except subprocess.CalledProcessError:
else:
exec_shell_command_async("wlinhibit")
self.caffeine_status.set_label("Enabled")
for i in self.widgets:
i.remove_style_class("disabled")
def check_wlinhibit(self, *args):
def is_wlinhibit_running(self, *args):
"""Returns True if wlinhibit is running. Accepts extra arguments to avoid Fabricator errors."""
try:
subprocess.check_output(["pgrep", "wlinhibit"])
self.caffeine_status.set_label("Enabled")
for i in self.widgets:
i.remove_style_class("disabled")
return True
except subprocess.CalledProcessError:
return False
def update_wlinhibit_status(self, _, is_running):
"""Update UI based on wlinhibit status."""
if is_running:
self.caffeine_status.set_label("Enabled")
for widget in self.widgets:
widget.remove_style_class("disabled")
else:
self.caffeine_status.set_label("Disabled")
for i in self.widgets:
i.add_style_class("disabled")
for widget in self.widgets:
widget.add_style_class("disabled")
class DarkModeButton(Button):
class PowerProfileButton(Button):
def __init__(self):
self.dark_mode_icon = Label(
name="dark-mode-icon",
markup=icons.darkmode,
self.power_profile_service = PowerProfiles.get_default()
self.power_profile_icon = Label(
name="power-profile-icon",
markup=icons.power_balanced, # Default icon
)
self.dark_mode_label = Label(
name="dark-mode-label", label="Dark Mode", justification="left"
self.power_profile_label = Label(
name="power-profile-label",
label="Power Profile",
justification="left",
)
self.dark_mode_label_box = Box(
children=[self.dark_mode_label, Box(h_expand=True)]
self.power_profile_label_box = Box(
children=[self.power_profile_label, Box(h_expand=True)]
)
self.dark_mode_status = Label(
name="dark-mode-status", label="Enabled", justification="left"
self.power_profile_status = Label(
name="power-profile-status",
label="Balanced",
justification="left",
)
self.dark_mode_status_box = Box(
children=[self.dark_mode_status, Box(h_expand=True)]
self.power_profile_status_box = Box(
children=[self.power_profile_status, Box(h_expand=True)]
)
self.dark_mode_text = Box(
name="dark-mode-text",
self.power_profile_text = Box(
name="power-profile-text",
orientation="v",
h_align="start",
v_align="center",
children=[self.dark_mode_label_box, self.dark_mode_status_box],
children=[self.power_profile_label_box, self.power_profile_status_box],
)
self.dark_mode_box = Box(
self.power_profile_box = Box(
h_align="start",
v_align="center",
spacing=10,
children=[self.dark_mode_icon, self.dark_mode_text],
children=[self.power_profile_icon, self.power_profile_text],
)
super().__init__(
name="dark-mode-button",
name="power-profile-button",
h_expand=True,
child=self.dark_mode_box,
on_clicked=self.toggle_darkmode,
child=self.power_profile_box,
on_clicked=self.toggle_power_profile,
)
add_hover_cursor(self)
self.widgets = [
self,
self.dark_mode_label,
self.dark_mode_status,
self.dark_mode_icon,
self.power_profile_label,
self.power_profile_status,
self.power_profile_icon,
]
self.check_darkmode()
def toggle_darkmode(self, *_):
current_state = self.check_darkmode()
new_mode = "dark" if not current_state else "light"
command = f"bash {get_relative_path('../../../config/scripts/dark-theme.sh')} --set {new_mode}"
GLib.spawn_command_line_async(command)
# Connect to power profile service signals
self.power_profile_service.connect("profile", self.update_power_profile_status)
# Initial update
self.update_power_profile_status(None, self.power_profile_service.get_current_profile())
self.dark_mode_status.set_label("Enabled" if new_mode == "dark" else "Disabled")
def toggle_power_profile(self, *args):
current_profile = self.power_profile_service.get_current_profile()
profiles = ["power-saver", "balanced", "performance"]
current_index = profiles.index(current_profile)
next_profile = profiles[(current_index + 1) % len(profiles)]
self.power_profile_service.set_power_profile(next_profile)
# Apply or remove 'disabled' class
if new_mode == "light":
def update_power_profile_status(self, _, profile):
# Map profiles to their display names and icons
profile_map = {
"power-saver": {"name": "Power Saver", "icon": icons.power_saving},
"balanced": {"name": "Balanced", "icon": icons.power_balanced},
"performance": {"name": "Performance", "icon": icons.power_performance},
}
profile_info = profile_map.get(profile, profile_map["balanced"])
self.power_profile_status.set_label(profile_info["name"])
self.power_profile_icon.set_markup(profile_info["icon"])
if profile == "balanced":
for widget in self.widgets:
widget.add_style_class("disabled")
else:
for widget in self.widgets:
widget.remove_style_class("disabled")
def check_darkmode(self):
result = exec_shell_command(
"gsettings get org.gnome.desktop.interface color-scheme"
)
is_dark_mode = result.strip().replace("'", "") == "prefer-dark"
if not is_dark_mode:
for widget in self.widgets:
widget.add_style_class("disabled")
else:
for widget in self.widgets:
widget.remove_style_class("disabled")
return is_dark_mode
class Dashboard(Gtk.Grid):
@@ -418,12 +593,12 @@ class Dashboard(Gtk.Grid):
self.bluetooth_button = BluetoothButton(self.launcher)
self.night_mode_button = NightModeButton()
self.caffeine_button = CaffeineButton()
self.dark_mode_button = DarkModeButton()
self.power_profile_button = PowerProfileButton()
# Attach buttons into the grid (one row, four columns)
# Attach buttons into the grid (two rows, three columns)
self.attach(self.network_button, 0, 0, 1, 1)
self.attach(self.bluetooth_button, 1, 0, 1, 1)
self.attach(self.dark_mode_button, 2, 0, 1, 1)
self.attach(self.power_profile_button, 2, 0, 1, 1)
self.attach(self.night_mode_button, 0, 1, 1, 1)
self.attach(self.caffeine_button, 1, 1, 1, 1)
+288 -91
View File
@@ -1,133 +1,330 @@
import subprocess
from typing import Generator, List
import ijson
from fabric.utils import remove_handler, get_relative_path
from fabric.widgets.box import Box
from fabric.widgets.label import Label
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 fabric.widgets.stack import Stack
from fabric.utils import remove_handler, get_relative_path
from gi.repository import Gdk
import utils.icons as icons
import os
import subprocess
import ijson
class Emoji(Box):
class EmojiPicker(Box):
def __init__(self, **kwargs):
super().__init__(
name="emoji-launcher",
all_visible=False,
name="emoji",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
self._arranger_handler: int = 0
self.emoji_manager = EmojiManager(self)
self.viewport = None
self.selected_index = -1
self.emojis_per_page = 9 * 3
self.current_page_index = 0
self.filtered_emojis = []
self.total_pages = 0
self._arranger_handler: int = 0
self._all_emojis = self._load_emoji_data()
self.stack = Stack(
name="viewport",
spacing=4,
orientation="v",
transition_type="slide-up-down",
transition_duration=200,
)
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()),
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,
)
self.search_entry.props.xalign = 0.5
self.header_box = Box(
name="header-box",
name="header_box",
spacing=10,
orientation="h",
children=[
self.search_entry,
# Button(
# name="close-button",
# child=Label(name="close-label", markup=icons.cancel),
# tooltip_text="Exit",
# on_clicked=lambda *_: self.close_picker(),
# ),
],
)
self.launcher_box = Box(
self.picker_box = Box(
name="picker-box",
spacing=10,
orientation="v",
h_expand=True,
children=[self.header_box],
orientation="v",
children=[
self.header_box,
self.stack,
],
)
self.add(self.launcher_box)
self.resize_viewport()
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.add(self.picker_box)
self.show_all()
self.viewport.children = []
self.emoji_manager.arrange_viewport()
def _load_emoji_data(self):
emoji_data = {}
emoji_file_path = get_relative_path("../../../config/assets/emoji.json")
if not os.path.exists(emoji_file_path):
print(f"Emoji JSON file not found at: {emoji_file_path}")
return {}
self.viewport.show()
self.search_entry.grab_focus()
with open(emoji_file_path, "r") as f:
for emoji_char, emoji_info in ijson.kvitems(f, ""):
emoji_data[emoji_char] = emoji_info
return emoji_data
def close_launcher(self):
def close_picker(self):
self.stack.children = []
self.selected_index = -1
self.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 = get_relative_path("../../../config/assets/emoji.json")
def load_emojis(self) -> Generator[tuple, None, None]:
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) as e:
print(f"Error loading emojis: {e}")
return
def query_emojis(self, query: str) -> List[tuple]:
query = query.lower()
return [
(emoji_str, name, slug, group)
for emoji_str, name, slug, group in self.load_emojis()
if query in name.lower() or query in slug.lower() or query in group.lower()
][:48]
def copy_emoji(self, emoji: tuple):
subprocess.run(["wl-copy"], input=emoji[0].encode(), check=True)
self.launcher.close_launcher()
def bake_emoji_slot(self, emoji: tuple, **kwargs) -> Button:
return Button(
name="emoji-item",
child=Label(label=emoji[0], h_align="center"),
tooltip_text=emoji[1],
on_clicked=lambda *_: self.copy_emoji(emoji),
**kwargs,
)
def open_picker(self):
self.search_entry.set_text("")
self.current_page_index = 0
self.arrange_viewport()
self.search_entry.grab_focus()
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.stack.children = []
self.selected_index = -1
self.current_page_index = 0
self.filtered_emojis = [
(emoji_char, emoji_info)
for emoji_char, emoji_info in self._all_emojis.items()
if query.casefold()
in (
emoji_info.get("name", "") + " " + emoji_info.get("group", "")
).casefold()
]
self.total_pages = (
(len(self.filtered_emojis) + self.emojis_per_page - 1)
// self.emojis_per_page
if self.filtered_emojis
else 0
)
self.load_page(self.current_page_index)
should_resize = not query
if should_resize:
self.resize_viewport()
if query.strip() != "" and self.get_all_emoji_buttons():
self.update_selection(0)
def load_page(self, page_index):
self.update_selection(-1)
page_box = Box(name=f"page-box-{page_index}", orientation="v", spacing=4)
start_index = page_index * self.emojis_per_page
end_index = min(
(page_index + 1) * self.emojis_per_page, len(self.filtered_emojis)
)
page_emojis = self.filtered_emojis[start_index:end_index]
grid_box = Box(name="emoji-grid-box", orientation="v", spacing=2)
row_box = None
for i, (emoji_char, emoji_info) in enumerate(page_emojis):
if i % 9 == 0:
row_box = Box(name="emoji-row-box", orientation="h", spacing=2)
grid_box.add(row_box)
if row_box is not None:
row_box.add(self.bake_emoji_slot(emoji_char, emoji_info))
page_box.add(grid_box)
self.stack.add_named(page_box, f"page-{page_index}")
self.stack.set_visible_child_name(f"page-{page_index}")
page_box.show_all()
buttons = self.get_all_emoji_buttons()
if buttons and self.selected_index != -1:
page_relative_index = self.selected_index % self.emojis_per_page
if page_relative_index < len(buttons):
self.update_selection(page_relative_index)
else:
self.update_selection(len(buttons) - 1)
def resize_viewport(self):
return False
def bake_emoji_slot(self, emoji_char: str, emoji_info: dict, **kwargs) -> Button:
button = Button(
name="emoji-slot-button",
child=Box(
name="emoji-slot-box",
orientation="horizontal",
halign="center",
valign="center",
children=[
Label(
name="emoji-char-label",
label=emoji_char,
use_markup=True,
v_align="center",
h_align="center",
css_name="emoji-char-label",
),
],
),
tooltip_text=emoji_info.get("name", "Unknown"),
on_clicked=lambda *_: (
self.copy_emoji_to_clipboard(emoji_char),
self.close_picker(),
),
**kwargs,
)
return button
def update_selection(self, new_index: int):
buttons = self.get_all_emoji_buttons()
if not buttons:
self.selected_index = -1
return
(
remove_handler(self.launcher._arranger_handler)
if self.launcher._arranger_handler
else None
)
self.launcher.viewport.children = []
if self.selected_index != -1 and self.selected_index < len(buttons):
current_button = buttons[self.selected_index]
current_button.get_style_context().remove_class("selected")
if not buttons or current_button not in buttons:
self.selected_index = -1
filtered_emojis = self.query_emojis(query)
if 0 <= new_index < len(buttons):
new_button = buttons[new_index]
new_button.get_style_context().add_class("selected")
self.selected_index = new_index
else:
self.selected_index = -1
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")
def get_all_emoji_buttons(self):
buttons = []
current_page = self.stack.get_visible_child()
if current_page and current_page.get_children():
if current_page.get_children()[0].get_children():
for row_box in current_page.get_children()[0].get_children():
buttons.extend(row_box.get_children())
return buttons
if row.children:
self.launcher.viewport.add(row)
def on_search_entry_activate(self, text):
buttons = self.get_all_emoji_buttons()
if buttons:
if self.selected_index != -1:
buttons[self.selected_index].clicked()
elif buttons and text.strip() != "":
buttons[0].clicked()
def on_search_entry_key_press(self, widget, event):
if event.keyval in (Gdk.KEY_Up, Gdk.KEY_Down, Gdk.KEY_Left, Gdk.KEY_Right):
self.move_selection_2d(event.keyval)
return True
elif event.keyval == Gdk.KEY_Escape:
self.close_picker()
return True
return False
def move_selection_2d(self, keyval):
buttons = self.get_all_emoji_buttons()
total_items_current_page = len(buttons)
if total_items_current_page == 0:
return
rows = 3
columns = 9
if self.selected_index == -1:
if keyval in (Gdk.KEY_Down, Gdk.KEY_Right):
new_index = 0
elif keyval in (Gdk.KEY_Up, Gdk.KEY_Left):
new_index = total_items_current_page - 1
else:
return
else:
current_index_page = self.selected_index
row = current_index_page // columns
col = current_index_page % columns
if keyval == Gdk.KEY_Right:
new_col = (col + 1) % columns
new_row = row
if new_col == 0:
new_row = row + 1
elif keyval == Gdk.KEY_Left:
new_col = (col - 1) % columns
new_row = row
if new_col == (columns - 1):
new_row = row - 1
elif keyval == Gdk.KEY_Down:
new_row = row + 1
new_col = col
elif keyval == Gdk.KEY_Up:
new_row = row - 1
new_col = col
else:
return
if new_row >= rows:
if self.current_page_index < self.total_pages - 1:
current_col = col # Keep track of current column
self.current_page_index += 1
self.load_page(self.current_page_index)
new_index = current_col # Try to keep the same column
if (
new_index >= total_items_current_page
): # if column is out of bound, select last
new_index = total_items_current_page - 1
self.selected_index = -1
self.update_selection(new_index)
return
else:
new_index = total_items_current_page - 1
elif new_row < 0:
if self.current_page_index > 0:
current_col = col # Keep track of current column
self.current_page_index -= 1
self.load_page(self.current_page_index)
new_index = (
rows - 1
) * columns + current_col # Select last row, same column
if (
new_index >= total_items_current_page
): # if column is out of bound, select last
new_index = total_items_current_page - 1
self.selected_index = -1
self.update_selection(new_index)
return
else:
new_index = 0
else:
new_index = new_row * columns + new_col
if new_index >= total_items_current_page:
new_index = total_items_current_page - 1
if new_index < 0:
new_index = 0
elif new_index >= total_items_current_page:
new_index = total_items_current_page - 1
self.update_selection(new_index)
def copy_emoji_to_clipboard(self, emoji_char: str):
try:
subprocess.run(["wl-copy"], input=emoji_char.encode("utf-8"), check=True)
except subprocess.CalledProcessError as e:
print(f"Clipboard copy failed: {e}")
+365
View File
@@ -0,0 +1,365 @@
import gi
import json
import os
from pathlib import Path
import cairo # For rendering the drag preview
from fabric.widgets.label import Label
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
import utils.icons as icons
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GObject, GLib
def createSurfaceFromWidget(widget: Gtk.Widget) -> cairo.ImageSurface:
alloc = widget.get_allocation()
surface = cairo.ImageSurface(cairo.Format.ARGB32, alloc.width, alloc.height)
cr = cairo.Context(surface)
# Use a transparent background.
cr.set_source_rgba(0, 0, 0, 0)
cr.rectangle(0, 0, alloc.width, alloc.height)
cr.fill()
widget.draw(cr)
return surface
class InlineEditor(Gtk.Box):
__gsignals__ = {
"confirmed": (GObject.SignalFlags.RUN_LAST, None, (str,)),
"canceled": (GObject.SignalFlags.RUN_LAST, None, ()),
}
def __init__(self, initial_text=""):
super().__init__(name="inline-editor", spacing=4)
# Replace Gtk.Entry with a Gtk.TextView for multiline editing.
self.text_view = Gtk.TextView()
self.text_view.set_wrap_mode(Gtk.WrapMode.WORD)
buffer = self.text_view.get_buffer()
buffer.set_text(initial_text)
# Connect key press events to handle Return and SHIFT+Return.
self.text_view.connect("key-press-event", self.on_key_press)
confirm_btn = Gtk.Button(
name="kanban-btn", child=Label(name="kanban-btn-label", markup=icons.accept)
)
confirm_btn.connect("clicked", self.on_confirm)
confirm_btn.get_style_context().add_class("flat")
cancel_btn = Gtk.Button(
name="kanban-btn", child=Label(name="kanban-btn-neg", markup=icons.cancel)
)
cancel_btn.connect("clicked", self.on_cancel)
cancel_btn.get_style_context().add_class("flat")
# Pack the TextView inside a ScrolledWindow for better appearance.
sw = Gtk.ScrolledWindow()
sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
sw.set_min_content_height(50)
sw.add(self.text_view)
self.button_box = Box(children=[confirm_btn, cancel_btn], spacing=4)
self.center_box = CenterBox(center_children=[self.button_box], orientation="v")
self.pack_start(sw, True, True, 0)
self.pack_start(self.center_box, False, False, 0)
self.show_all()
def on_confirm(self, widget):
buffer = self.text_view.get_buffer()
start, end = buffer.get_bounds()
text = buffer.get_text(start, end, True).strip()
if text:
self.emit("confirmed", text)
else:
self.emit("canceled")
def on_cancel(self, widget):
self.emit("canceled")
def on_key_press(self, widget, event):
# Check for Escape to cancel.
if event.keyval == Gdk.KEY_Escape:
self.emit("canceled")
return True
# If Return is pressed...
if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
state = event.get_state()
if state & Gdk.ModifierType.SHIFT_MASK:
# SHIFT+Return: insert a newline.
buffer = self.text_view.get_buffer()
cursor_iter = buffer.get_iter_at_mark(buffer.get_insert())
buffer.insert(cursor_iter, "\n")
return True # Prevent further handling.
else:
# Plain Return: confirm the edit.
self.on_confirm(widget)
return True
return False
class KanbanNote(Gtk.EventBox):
__gsignals__ = {
"changed": (GObject.SignalFlags.RUN_LAST, None, ()),
}
def __init__(self, text):
super().__init__()
self.text = text
# Variables to store the click offset for drag preview.
self.setup_ui()
self.setup_dnd()
self.connect("button-press-event", self.on_button_press)
def setup_ui(self):
self.box = Gtk.Box(name="kanban-note", spacing=4)
self.label = Gtk.Label(label=self.text)
self.label.set_line_wrap(True)
# Wrap long lines.
self.label.set_line_wrap_mode(Gtk.WrapMode.WORD)
self.delete_btn = Gtk.Button(
name="kanban-btn", child=Label(name="kanban-btn-neg", markup=icons.trash)
)
self.delete_btn.connect("clicked", self.on_delete_clicked)
self.center_btn = CenterBox(orientation="v", start_children=[self.delete_btn])
self.box.pack_start(self.label, True, True, 0)
self.box.pack_start(self.center_btn, False, False, 0)
self.add(self.box)
self.show_all()
def setup_dnd(self):
self.drag_source_set(
Gdk.ModifierType.BUTTON1_MASK,
[Gtk.TargetEntry.new("UTF8_STRING", Gtk.TargetFlags.SAME_APP, 0)],
Gdk.DragAction.MOVE,
)
self.connect("drag-data-get", self.on_drag_data_get)
self.connect("drag-data-delete", self.on_drag_data_delete)
# Set up drag-begin to display a preview of the card.
self.connect("drag-begin", self.on_drag_begin)
def on_button_press(self, widget, event):
if event.type != Gdk.EventType._2BUTTON_PRESS:
return True
self.start_edit()
return False
def on_drag_begin(self, widget, context):
surface = createSurfaceFromWidget(self)
Gtk.drag_set_icon_surface(context, surface)
def on_drag_data_get(self, widget, drag_context, data, info, time):
data.set_text(self.label.get_text(), -1)
def on_drag_data_delete(self, widget, drag_context):
self.get_parent().destroy()
def on_delete_clicked(self, button):
self.get_parent().destroy()
def start_edit(self):
row = self.get_parent()
editor = InlineEditor(self.label.get_text())
def on_confirmed(editor, text):
self.label.set_text(text)
row.remove(editor)
row.add(self)
row.show_all()
self.emit("changed")
def on_canceled(editor):
row.remove(editor)
row.add(self)
row.show_all()
editor.connect("confirmed", on_confirmed)
editor.connect("canceled", on_canceled)
row.remove(self)
row.add(editor)
row.show_all()
# Usamos un retardo de 50 milisegundos:
GLib.timeout_add(50, lambda: (editor.text_view.grab_focus(), False))
class KanbanColumn(Gtk.Frame):
__gsignals__ = {
"changed": (GObject.SignalFlags.RUN_LAST, None, ()),
}
def __init__(self, title):
super().__init__(name="kanban-column")
self.title = title
self.setup_ui()
self.setup_dnd()
self.set_hexpand(True)
self.set_vexpand(True)
def setup_ui(self):
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
self.listbox = Gtk.ListBox()
self.listbox.set_selection_mode(Gtk.SelectionMode.NONE)
self.add_btn = Gtk.Button(
name="kanban-btn-add",
child=Label(name="kanban-btn-label", markup=icons.add),
)
header = CenterBox(
name="kanban-header",
center_children=[Label(name="column-header", label=self.title)],
end_children=[self.add_btn],
)
self.box.pack_start(header, False, False, 0)
self.add_btn.connect("clicked", self.on_add_clicked)
scrolled = Gtk.ScrolledWindow(name="kanban-scroll")
scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
scrolled.add(self.listbox)
scrolled.set_vexpand(True)
self.box.pack_start(scrolled, True, True, 0)
self.box.pack_start(self.add_btn, False, False, 0)
self.add(self.box)
self.show_all()
def setup_dnd(self):
self.listbox.drag_dest_set(
Gtk.DestDefaults.ALL,
[Gtk.TargetEntry.new("UTF8_STRING", Gtk.TargetFlags.SAME_APP, 0)],
Gdk.DragAction.MOVE,
)
self.listbox.connect("drag-data-received", self.on_drag_data_received)
self.listbox.connect("drag-motion", self.on_drag_motion)
self.listbox.connect("drag-leave", self.on_drag_leave)
def on_add_clicked(self, button):
editor = InlineEditor()
row = Gtk.ListBoxRow(name="kanban-row")
row.add(editor)
self.listbox.add(row)
self.listbox.show_all()
editor.text_view.grab_focus()
def on_confirmed(editor, text):
note = KanbanNote(text)
note.connect("changed", lambda x: self.emit("changed"))
row.remove(editor)
row.add(note)
self.listbox.show_all()
self.emit("changed") # Emit on add
def on_canceled(editor):
row.destroy()
editor.connect("confirmed", on_confirmed)
editor.connect("canceled", on_canceled)
def add_note(self, text, suppress_signal=False):
note = KanbanNote(text)
note.connect("changed", lambda x: self.emit("changed"))
row = Gtk.ListBoxRow(name="kanban-row")
row.add(note)
row.connect("destroy", lambda x: self.emit("changed"))
self.listbox.add(row)
self.listbox.show_all()
if not suppress_signal:
self.emit("changed")
def get_notes(self):
return [
row.get_children()[0].label.get_text()
for row in self.listbox.get_children()
if isinstance(row.get_children()[0], KanbanNote)
]
def clear_notes(self, suppress_signal=False):
for row in self.listbox.get_children():
row.destroy()
if not suppress_signal:
self.emit("changed")
def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
text = data.get_text()
if text:
row = self.listbox.get_row_at_y(y)
new_note = KanbanNote(text)
new_note.connect("changed", lambda x: self.emit("changed"))
new_row = Gtk.ListBoxRow(name="kanban-row")
new_row.add(new_note)
new_row.connect("destroy", lambda x: self.emit("changed"))
if row:
self.listbox.insert(new_row, row.get_index())
else:
self.listbox.add(new_row)
self.listbox.show_all()
drag_context.finish(True, False, time)
self.emit("changed") # Emit on move
def on_drag_motion(self, widget, drag_context, x, y, time):
Gdk.drag_status(drag_context, Gdk.DragAction.MOVE, time)
return True
def on_drag_leave(self, widget, drag_context, time):
widget.get_parent().get_parent().drag_unhighlight()
class Kanban(Gtk.Box):
STATE_FILE = Path(os.path.expanduser("~/.local/state/modus/kanban.json"))
def __init__(self):
super().__init__(name="kanban")
self.grid = Gtk.Grid(column_spacing=4, column_homogeneous=True)
self.grid.set_vexpand(True)
self.add(self.grid)
self.columns = [
KanbanColumn("To Do"),
KanbanColumn("In Progress"),
KanbanColumn("Done"),
]
for i, column in enumerate(self.columns):
self.grid.attach(column, i, 0, 1, 1)
column.connect("changed", lambda x: self.save_state())
self.load_state()
self.show_all()
def save_state(self):
state = {
"columns": [
{"title": col.title, "notes": col.get_notes()} for col in self.columns
]
}
try:
with open(self.STATE_FILE, "w") as f:
json.dump(state, f, indent=2)
except Exception as e:
print(f"Error saving state: {e}")
def load_state(self):
try:
with open(self.STATE_FILE, "r") as f:
state = json.load(f)
for col_data in state["columns"]:
for column in self.columns:
if column.title == col_data["title"]:
column.clear_notes(suppress_signal=True)
for note_text in col_data["notes"]:
column.add_note(note_text, suppress_signal=True)
break
except FileNotFoundError:
pass
except Exception as e:
print(f"Error loading state: {e}")
@@ -0,0 +1,409 @@
from fabric.notifications import Notification
from services import notification_service
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from fabric.widgets.image import Image
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.widgets.revealer import Revealer
from loguru import logger
import utils.icons as icons
from gi.repository import GdkPixbuf, GLib
from utils import CustomImage
import os
from gi.repository import Gtk
from fabric.widgets.centerbox import CenterBox
class NotificationCenter(Box):
def __init__(self, **kwargs):
super().__init__(
name="notification-center",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
self.notification_service = notification_service
# Main container for notifications
self.notifications = Box(
v_expand=True,
h_expand=True,
orientation="v",
spacing=8,
)
self.header_switch = Gtk.Switch(name="matugen-switcher")
self.header_switch.set_vexpand(False)
self.header_switch.set_valign(Gtk.Align.CENTER)
self.header_switch.set_active(self.notification_service.dont_disturb)
self.do_not_disturb_enabled = self.notification_service.dont_disturb
self.header_switch.connect("notify::active", self.on_do_not_disturb_changed)
self.dnd_label = Label(name="dnd-label", markup=icons.notifications_off)
# Header with clear all button
header = CenterBox(
h_expand=True,
start_children=[self.header_switch, self.dnd_label],
center_children=[
Label(
label="Notifications",
name="nhh",
)
],
end_children=[
Button(
name="nhh-button",
child=Label(name="nhh-button-label", markup=icons.trash),
on_clicked=lambda *args: self.clear_all_notifications(),
)
],
)
self.scrolledwindow = ScrolledWindow(
name="scrolled-window",
child=self.notifications,
min_content_size=(400, 300),
max_content_size=(400, 300),
v_expand=True,
h_expand=True,
)
# Main container
main_container = Box(
v_expand=True,
h_expand=True,
orientation="v",
children=[header, self.scrolledwindow],
)
self.add(main_container)
# Connect to notification service signals
self.notification_service.connect(
"notification-added", self.on_new_notification
)
self.notification_service.connect("clear_all", self.on_clear_all)
# Load existing notifications
self.load_notifications()
def load_notifications(self):
"""Load existing notifications from the service."""
notifications = self.notification_service.get_deserialized()
if not notifications:
# Create a container box to better center the message
container = Box(
name="no-notifications-container",
orientation="v",
h_align="center",
v_align="center",
h_expand=True,
v_expand=True,
)
# Show a message if no notifications
label = Label(
name="no-notifications-label",
markup=icons.notifications_clear,
v_align="fill",
h_align="fill",
v_expand=True,
h_expand=True,
justification="center",
)
container.add(label)
self.notifications.add(container)
return
for notification in notifications:
self.add_notification(notification)
def toggle_notification_body(self, revealer, chevron_label):
"""Toggle the visibility of notification body."""
is_revealed = revealer.get_reveal_child()
revealer.set_reveal_child(not is_revealed)
# Update chevron icon
chevron_label.set_markup(
icons.chevron_up if not is_revealed else icons.chevron_down
)
def add_notification(self, notification: Notification):
"""Add a notification to the center."""
# Remove empty state container if it exists
for child in self.notifications.get_children():
if child.get_name() == "no-notifications-container":
self.notifications.remove(child)
break
# Get timestamp from notification object
timestamp = getattr(notification, 'timestamp', GLib.get_real_time() / 1000000)
time_str = GLib.DateTime.new_from_unix_local(timestamp).format("%I:%M %p")
# Create the notification header (summary) box
header_box = Box(
name="notification-header",
# h_expand=True,
spacing=8,
children=[
Box(
orientation="h",
h_expand=True,
spacing=8,
style="min-width: 0;",
children=[
# Summary
Label(
name="notification-app-name",
markup=notification.app_name + " | ",
h_align="start",
ellipsization="end",
),
Label(
markup=notification.summary.replace("\n", " "),
h_align="start",
ellipsization="end",
),
Label(
name="notification-time",
markup=f" | {time_str}",
h_align="end",
style="color: var(--outline);",
),
],
),
# Add chevron button if there's content to show
*(
[
Button(
name="chevron-button",
child=Label(
name="chevron-label", markup=icons.chevron_down
),
)
]
if notification.body or notification.image_pixbuf
else []
),
Button(
name="notif-close-button",
child=Label(name="notif-close-label", markup=icons.cancel),
on_clicked=lambda *args: self.remove_notification(notification),
),
],
)
# Create content box that will be revealed
# Create content box in vertical layout for body + actions
content_box = Box(
name="notification-content",
spacing=8,
orientation="v",
)
# Create horizontal box for image and body
body_box = Box(
name="notification-body-box",
spacing=8,
orientation="h",
)
# Add image if available
if notification.image_pixbuf:
image_box = Box(
name="notification-image",
children=[
CustomImage(
pixbuf=notification.image_pixbuf.scale_simple(
48, 48, GdkPixbuf.InterpType.BILINEAR
)
if notification.image_pixbuf
else self.get_pixbuf(notification.app_icon, 48, 48)
),
],
)
body_box.add(image_box)
# Add body text if available
if notification.body:
body_box.add(
Label(
markup=notification.body.replace("\n", " "),
name="notification-body",
h_align="start",
ellipsization="end",
)
)
# Add body box to content
content_box.add(body_box)
# Add action buttons if available
if notification.actions:
action_box = Box(
name="notification-action-buttons",
spacing=4,
h_expand=True,
)
for i, action in enumerate(notification.actions):
style_class = (
"start-action"
if i == 0
else "end-action"
if i == len(notification.actions) - 1
else "middle-action"
)
button = Button(
name="action-button",
h_expand=True,
child=Label(name="button-label", label=action.label),
on_clicked=lambda btn, act=action, notif=notification: [
act.invoke(),
self.notification_service.remove_notification(notif.id),
self.remove_notification(notif)
],
)
button.add_style_class(style_class)
action_box.add(button)
content_box.add(action_box)
# Create revealer for content
body_revealer = None
if notification.body or notification.image_pixbuf:
body_revealer = Revealer(
name="body-revealer",
transition_type="slide-down",
reveal_child=False,
child=content_box,
)
# Create main notification box
notification_box = Box(
name="notification-box",
orientation="v",
h_expand=True,
style="margin: 4px; padding: 16px; border-radius: 20px; background-color: var(--surface-container-low); min-width: 200px;",
children=[header_box],
)
# Add body revealer if exists
if body_revealer:
notification_box.add(body_revealer)
# Get the chevron button from header_box children
chevron_button = [
c for c in header_box.get_children() if c.get_name() == "chevron-button"
][0]
chevron_label = chevron_button.get_child()
chevron_button.connect(
"clicked",
lambda *args: self.toggle_notification_body(
body_revealer, chevron_label
),
)
self.notifications.add(notification_box)
def on_do_not_disturb_changed(self, switch, pspec):
"""Handle Do Not Disturb toggle."""
self.do_not_disturb_enabled = switch.get_active()
self.notification_service.dont_disturb = self.do_not_disturb_enabled
def on_new_notification(self, fabric_notif, id):
"""Handle new notification event."""
notification = fabric_notif.get_notification_from_id(id)
self.add_notification(notification)
def remove_notification(self, notification: Notification):
"""Remove a notification from the center."""
self.notification_service.remove_notification(notification.id)
# Find and remove the notification box
for child in self.notifications.get_children():
if child.get_name() == "notification-box":
# Get the header box
header_box = child.get_children()[0]
# Get the text container box
text_box = header_box.get_children()[0]
# Get the summary label (second child of text box)
summary_label = text_box.get_children()[1]
if summary_label.get_text() == notification.summary:
self.notifications.remove(child)
break
def clear_all_notifications(self, *args):
"""Clear all notifications."""
self.notification_service.clear_all_notifications()
# Remove all child widgets
for child in self.notifications.get_children():
self.notifications.remove(child)
# Add empty state
container = Box(
name="no-notifications-container",
orientation="v",
h_align="center",
v_align="center",
h_expand=True,
v_expand=True,
)
label = Label(
name="no-notifications-label",
markup=icons.notifications_clear,
v_align="fill",
h_align="fill",
v_expand=True,
h_expand=True,
justification="center",
)
container.add(label)
self.notifications.add(container)
def on_clear_all(self, *args):
"""Handle clear all event from service."""
# Remove all child widgets
for child in self.notifications.get_children():
self.notifications.remove(child)
# Add empty state
container = Box(
name="no-notifications-container",
orientation="v",
h_align="center",
v_align="center",
h_expand=True,
v_expand=True,
)
label = Label(
name="no-notifications-label",
markup=icons.notifications_clear,
v_align="fill",
h_align="fill",
v_expand=True,
h_expand=True,
justification="center",
)
container.add(label)
self.notifications.add(container)
def get_pixbuf(self, icon_path, width, height):
if icon_path.startswith("file://"):
icon_path = icon_path[7:]
if not os.path.exists(icon_path):
logger.warning(f"Icon path does not exist: {icon_path}")
return None
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon_path)
return pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
except Exception as e:
logger.error(f"Failed to load or scale icon: {e}")
return None
def open_center(self):
"""Open the notification center."""
self.show_all()
+203
View File
@@ -0,0 +1,203 @@
import os
import subprocess
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
import utils.icons as icons
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.launcher = kwargs["launcher"]
self.search_entry = Entry(
name="search-entry",
placeholder="Search Clipboard History...",
h_expand=True,
on_activate=self._on_search_activate,
)
self.search_entry.props.xalign = 0.5
self.header_box = Box(
name="header-box",
spacing=10,
orientation="h",
children=[
self.search_entry,
Button(
name="clear-button",
child=Label(name="clear-label", markup=icons.clear),
tooltip_text="Clear Clipboard History",
on_clicked=self.handle_clear_history,
),
],
)
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 _on_search_activate(self, entry, *args):
self.handle_search(entry.get_text())
def open_cliphist(self):
if not self.viewport:
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
min_content_size=(-1, -1),
h_scrollbar_policy="never",
child=self.viewport,
)
self.launcher_box.add(self.scrolled_window)
self.viewport.children = []
self.cliphist_manager.update_cliphist_history()
self.viewport.show()
self.search_entry.grab_focus()
def handle_search(self, text: str):
self.cliphist_manager.arrange_viewport(query=text)
def close_launcher(self):
self.launcher.close()
def handle_clear_history(self, *_):
GLib.spawn_command_line_async("cliphist wipe")
self.cliphist_manager.update_cliphist_history()
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", self._on_wl_paste_changed)
def _on_wl_paste_changed(self, *args):
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
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_image_file(self, clip_id: str) -> str:
output_file = f"/tmp/cliphist-{clip_id}.png"
os.makedirs("/tmp", 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 image file for clip {clip_id}: {e}")
return ""
def update_cliphist_history(self):
self.cliphist_history = self.get_clip_history()
self.arrange_viewport()
def query_clips(self, query: str = "") -> List[dict]:
if not query.strip():
return self.cliphist_history
return [
clip
for clip in self.cliphist_history
if query.lower() in clip["content"].lower()
]
def _on_clip_clicked(self, clip_id: str, *args):
self.copy_clip(clip_id)
def bake_clip_slot(self, item: dict) -> Button:
if "[[ binary data" 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_image_file(item["id"])
if output_file and os.path.exists(output_file):
button = Button(
h_align="start",
name="clip-item-img",
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
)
button.set_style(
f"background-image: url('{output_file}'); background-size: cover; background-position: center;"
)
return button
return None
def _create_text_button(self, item: dict) -> Button:
return Button(
child=Label(
label=item["content"][:50]
+ ("..." if len(item["content"]) > 50 else ""),
h_expand=True,
v_align="center",
h_align="start",
),
on_clicked=lambda _, clip_id=item["id"]: self.copy_clip(clip_id),
name="slot-button",
)
def arrange_viewport(self, query: str = ""):
if not self.launcher.viewport:
return
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)
+7 -8
View File
@@ -6,12 +6,9 @@ from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
import config.data as data
CACHE_DIR = os.getenv(
"XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache", "modus")
)
BINS = os.path.join(CACHE_DIR, "binaries")
BINS = f"{data.CACHE_DIR}/binaries"
class Sh(Box):
@@ -29,10 +26,12 @@ class Sh(Box):
self.search_entry = Entry(
name="search-entry",
placeholder="Search Shell Commands...",
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.search_entry.props.xalign = 0.5
self.header_box = Box(
spacing=10,
@@ -49,7 +48,7 @@ class Sh(Box):
self.add(self.launcher_box)
def open_launcher(self):
def open_sh(self):
if not self.viewport:
self.viewport = Box(name="viewport", spacing=10, orientation="v")
self.scrolled_window = ScrolledWindow(
@@ -112,7 +111,7 @@ class ShellCommandManager:
def query_binaries(self, filter_str: str) -> List[str]:
filter_str = filter_str.lower()
filtered_bins = (cmd for cmd in self.binaries if filter_str in cmd)
return list(dict.fromkeys(filtered_bins))[:16]
return list(dict.fromkeys(filtered_bins))[:8]
def display_results(self, viewport, results: List[str]):
for command in results:
@@ -123,7 +122,7 @@ class ShellCommandManager:
h_align="start",
),
on_clicked=lambda _, cmd=command: self.execute_command(cmd),
name="sh-item",
name="app-slot-button",
)
viewport.add(button)
+540
View File
@@ -0,0 +1,540 @@
import subprocess
import os
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.utils import idle_add, remove_handler, exec_shell_command_async
from gi.repository import GLib, Gdk, Gtk
import utils.icons as icons
import config.data as data
class TmuxManager(Box):
def __init__(self, **kwargs):
super().__init__(
name="tmux-manager",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
self.selected_index = -1 # Track the selected item index
self._arranger_handler: int = 0
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.session_name_entry = Entry(
name="session-name-entry",
placeholder="Create Tmux Session...",
h_expand=True,
on_activate=lambda entry, *_: self.create_session(entry.get_text()),
on_key_press_event=self.on_entry_key_press,
)
self.session_name_entry.props.xalign = 0.5
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
min_content_size=(450, 105),
max_content_size=(450, 105),
child=self.viewport,
)
self.header_box = Box(
name="header_box",
spacing=10,
orientation="h",
children=[
Button(
name="new-session-button",
child=Label(name="new-session-label", markup=icons.add),
tooltip_text="Create New Session",
on_clicked=lambda *_: self.create_session(self.session_name_entry.get_text()),
),
self.session_name_entry,
],
)
self.tmux_box = Box(
name="tmux-box",
spacing=10,
h_expand=True,
orientation="v",
children=[
self.header_box,
self.scrolled_window,
],
)
self.add(self.tmux_box)
self.show_all()
def close_manager(self):
"""Close the tmux manager"""
self.viewport.children = []
self.selected_index = -1 # Reset selection
self.launcher.close()
def open_manager(self):
"""Open the tmux manager and refresh sessions"""
self.viewport.set_visible(True)
self.refresh_sessions()
self.session_name_entry.set_text("")
self.session_name_entry.grab_focus()
def refresh_sessions(self):
"""Get tmux sessions and populate the viewport"""
remove_handler(self._arranger_handler) if self._arranger_handler else None
self.viewport.children = []
self.selected_index = -1 # Clear selection when viewport changes
# Get tmux sessions
sessions = self.get_tmux_sessions()
if not sessions:
# Create a container box to better center the message
container = Box(
name="no-tmux-container",
orientation="v",
h_align="center",
v_align="center",
h_expand=True,
v_expand=True
)
# Show a message if no sessions
label = Label(
name="no-tmux",
markup=icons.terminal,
h_align="center",
v_align="center",
)
container.add(label)
self.viewport.add(container)
return
# Add session slots to viewport
for session in sessions:
self.viewport.add(self.create_session_slot(session))
def get_tmux_sessions(self):
"""Get list of tmux sessions"""
try:
result = subprocess.run(
["tmux", "list-sessions", "-F", "#{session_name}"],
capture_output=True,
text=True
)
if result.returncode == 0:
return [s.strip() for s in result.stdout.strip().split('\n') if s.strip()]
return []
except Exception as e:
print(f"Error getting tmux sessions: {e}")
return []
def create_session_slot(self, session_name):
"""Create a button for a tmux session"""
# Create an entry for inline editing (initially hidden)
name_entry = Entry(
name="session-name-entry",
text=session_name,
visible=False,
on_activate=lambda entry, *_: self.finish_rename(button, session_name, entry),
on_key_press_event=self.on_rename_key_press,
)
# Create the label showing the session name
name_label = Label(
name="app-label",
label=session_name,
ellipsization="end",
v_align="center",
h_align="center",
)
# Session slot content box
slot_box = Box(
name="slot-box",
orientation="h",
spacing=10,
children=[
Label(
name="tmux-icon",
markup=icons.terminal, # Use existing terminal icon
),
name_label,
name_entry,
],
)
button = Button(
name="slot-button", # reuse existing CSS styling
child=slot_box,
tooltip_text=f"Attach to session: {session_name}",
on_clicked=lambda *_: self.attach_to_session(session_name),
can_focus=True, # Ensure the button can receive focus
)
# Add double-click handler to start renaming
button.connect("button-press-event", self.on_session_click, session_name, name_label, name_entry)
# Add key press handler for 'r' to rename
button.connect("key-press-event", self.on_slot_key_press, session_name, name_label, name_entry)
# Store reference to entry and label in button for later access
button.name_entry = name_entry
button.name_label = name_label
button.session_name = session_name
return button
def on_session_click(self, button, event, session_name, label, entry):
"""Handle clicks on session buttons"""
# Handle double-click to rename
if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS and event.button == 1:
self.start_rename(button, session_name, label, entry)
return True
# Handle right click for context menu
elif event.button == 3:
menu = Gtk.Menu()
# Rename option
rename_item = Gtk.MenuItem(label="Rename")
rename_item.connect("activate", lambda _: self.start_rename(button, session_name, label, entry))
menu.append(rename_item)
# Kill option
kill_item = Gtk.MenuItem(label="Kill Session")
kill_item.connect("activate", lambda _: self.kill_session(session_name))
menu.append(kill_item)
menu.show_all()
menu.popup_at_pointer(event)
return True
return False
def start_rename(self, button, session_name, label, entry):
"""Start inline renaming of a session"""
# Hide label, show entry
label.set_visible(False)
entry.set_visible(True)
# Focus entry and select all text
entry.grab_focus()
entry.select_region(0, -1)
# Mark button as being edited
button.get_style_context().add_class("editing")
def finish_rename(self, button, old_name, entry):
"""Finish renaming a session"""
new_name = entry.get_text().strip()
# Only rename if the name changed and isn't empty
if new_name and new_name != old_name:
self.rename_session(old_name, new_name)
# Reset UI state
self.cancel_rename(button)
def cancel_rename(self, button):
"""Cancel renaming operation"""
# Restore original view
button.name_entry.set_visible(False)
button.name_label.set_visible(True)
# Remove editing style
button.get_style_context().remove_class("editing")
# Return focus to session name entry
self.session_name_entry.grab_focus()
def on_rename_key_press(self, entry, event):
"""Handle key presses in the rename entry"""
if event.keyval == Gdk.KEY_Escape:
# Find the parent button
parent = entry.get_parent()
while parent and not isinstance(parent, Button):
parent = parent.get_parent()
if parent:
self.cancel_rename(parent)
return True
return False
def on_session_right_click(self, button, event, session_name):
"""Handle right-click on a session button to show context menu"""
if event.button == 3: # Right click
menu = Gtk.Menu()
# Rename option
rename_item = Gtk.MenuItem(label="Rename")
rename_item.connect("activate", lambda _: self.start_rename(
button,
session_name,
button.name_label,
button.name_entry
))
menu.append(rename_item)
# Kill option
kill_item = Gtk.MenuItem(label="Kill Session")
kill_item.connect("activate", lambda _: self.kill_session(session_name))
menu.append(kill_item)
menu.show_all()
menu.popup_at_pointer(event)
return True
return False
def on_entry_key_press(self, widget, event):
"""Handle key press events in the entry"""
if event.keyval == Gdk.KEY_Escape:
self.close_manager()
return True
# Custom navigation with UP/DOWN keys removed
return False
def scroll_to_selected(self, button):
"""Scroll to ensure the selected button is visible"""
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 create_session(self, session_name):
"""Create a new tmux session"""
if not session_name:
# Get existing session names
existing_sessions = self.get_tmux_sessions()
# Find the next available number
counter = 0
while str(counter) in existing_sessions:
counter += 1
session_name = str(counter)
try:
# Clean the session name (replace spaces with underscores)
clean_name = session_name.strip().replace(" ", "_")
# Create session
subprocess.run(
["tmux", "new-session", "-d", "-s", clean_name],
check=True
)
# Refresh the session list
self.refresh_sessions()
# Clear entry
self.session_name_entry.set_text("")
# Launch a terminal and attach to this session
terminal_cmd = self.get_terminal_command(f"tmux attach-session -t {clean_name}")
exec_shell_command_async(terminal_cmd)
# Close manager
self.close_manager()
except Exception as e:
print(f"Error creating tmux session: {e}")
def attach_to_session(self, session_name):
"""Attach to an existing tmux session"""
try:
# Launch a terminal and attach to this session
terminal_cmd = self.get_terminal_command(f"tmux attach-session -t {session_name}")
exec_shell_command_async(terminal_cmd)
self.close_manager()
except Exception as e:
print(f"Error attaching to tmux session: {e}")
def get_terminal_command(self, cmd):
"""Get terminal command based on configured terminal or available terminals"""
# First try to use the configured terminal command
if hasattr(data, 'TERMINAL_COMMAND') and data.TERMINAL_COMMAND:
parts = data.TERMINAL_COMMAND.split()
terminal = parts[0]
try:
# Check if the configured terminal is available
subprocess.run(["which", terminal], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return f"{data.TERMINAL_COMMAND} {cmd}"
except subprocess.CalledProcessError:
# If configured terminal is not available, fall back to defaults
pass
# Fallback to checking available terminals
terminals = [
("kitty", f"kitty -e {cmd}"),
("alacritty", f"alacritty -e {cmd}"),
("foot", f"foot {cmd}"),
("gnome-terminal", f"gnome-terminal -- {cmd}"),
("konsole", f"konsole -e {cmd}"),
("xfce4-terminal", f"xfce4-terminal -e '{cmd}'"),
]
for term, term_cmd in terminals:
try:
# Check if terminal is available
subprocess.run(["which", term], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return term_cmd
except subprocess.CalledProcessError:
continue
# Default fallback
return f"kitty -e {cmd}"
def rename_session_dialog(self, old_name):
"""Show dialog to rename a session"""
dialog = Gtk.Dialog(
title="Rename Session",
transient_for=None,
flags=0
)
dialog.add_buttons(
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK
)
content_area = dialog.get_content_area()
entry = Gtk.Entry()
entry.set_text(old_name)
entry.set_activates_default(True)
content_area.add(entry)
dialog.set_default_response(Gtk.ResponseType.OK)
dialog.show_all()
response = dialog.run()
if response == Gtk.ResponseType.OK:
new_name = entry.get_text()
if new_name and new_name != old_name:
self.rename_session(old_name, new_name)
dialog.destroy()
def rename_session(self, old_name, new_name):
"""Rename a tmux session"""
try:
# Clean the session name (replace spaces with underscores)
clean_name = new_name.strip().replace(" ", "_")
# Rename session
subprocess.run(
["tmux", "rename-session", "-t", old_name, clean_name],
check=True
)
# Refresh the session list
self.refresh_sessions()
except Exception as e:
print(f"Error renaming tmux session: {e}")
def kill_session(self, session_name):
"""Kill a tmux session"""
try:
# Kill session
subprocess.run(
["tmux", "kill-session", "-t", session_name],
check=True
)
# Refresh the session list
self.refresh_sessions()
# Close the launcher after killing session
self.close_manager()
except Exception as e:
print(f"Error killing tmux session: {e}")
# Add new method to handle key presses on session slots
def on_slot_key_press(self, button, event, session_name, label, entry):
"""Handle key presses on session buttons"""
# Print debugging info
print(f"Key pressed: {event.keyval}, State: {event.state}")
# Check if 'r' key was pressed for renaming
if event.keyval == Gdk.KEY_r:
self.start_rename(button, session_name, label, entry)
return True
# Check for 'K' (capital K) which indicates Shift is pressed
elif event.keyval == Gdk.KEY_K:
print("Shift+K detected - killing session without confirmation")
self.kill_session(session_name)
return True
# Check for lowercase 'k'
elif event.keyval == Gdk.KEY_k:
print("Regular k detected - showing confirmation")
self.show_kill_confirmation_menu(button, session_name)
return True
# Check if Delete key was pressed for killing session
elif event.keyval == Gdk.KEY_Delete:
self.show_kill_confirmation_menu(button, session_name)
return True
return False
def show_kill_confirmation_menu(self, button, session_name):
"""Show a confirmation menu for killing a session"""
menu = Gtk.Menu()
# Confirmation message as a disabled menu item
msg_item = Gtk.MenuItem(label=f"Kill session '{session_name}'?")
msg_item.set_sensitive(False)
menu.append(msg_item)
# Separator
menu.append(Gtk.SeparatorMenuItem())
# Confirm option
confirm_item = Gtk.MenuItem(label="Confirm")
confirm_item.connect("activate", lambda _: self.kill_session(session_name))
menu.append(confirm_item)
# Cancel option
cancel_item = Gtk.MenuItem(label="Cancel")
# Close launcher on cancel
cancel_item.connect("activate", lambda _: self.close_manager())
menu.append(cancel_item)
menu.show_all()
# Show the menu positioned at the button
menu.popup_at_widget(
button,
Gdk.Gravity.SOUTH_WEST,
Gdk.Gravity.NORTH_WEST,
None
)
-170
View File
@@ -1,170 +0,0 @@
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.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
import utils.icons as icons
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",
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=Label(name="todo-add-button", markup=icons.add),
tooltip_text="Add Todo",
on_clicked=lambda *_: self.handle_add_todo(
self.todo_entry.get_text()
),
),
],
)
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,
min_content_size=(-1, -1),
h_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 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/state/modus/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="checkbox",
child=Label(
name="todo-checkbox",
markup=icons.check_box if todo["completed"] else icons.box,
),
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=Label(name="todo-delete-button", markup=icons.trash),
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)
+370
View File
@@ -0,0 +1,370 @@
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.utils.helpers import exec_shell_command_async, get_relative_path
import utils.icons as icons
from gi.repository import Gdk, GLib
import os
import subprocess
import threading
CAPTURE_SCRIPT = get_relative_path("../../../config/scripts/capture.sh")
GAMEMODE_SCRIPT = get_relative_path("../../../config/scripts/gamemode.sh")
class Toolbox(Box):
def __init__(self, **kwargs):
super().__init__(
name="toolbox",
orientation="h",
spacing=4,
v_align="center",
h_align="center",
visible=True,
**kwargs,
)
self.launcher = kwargs["launcher"]
self.btn_ssregion = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.ssregion),
on_clicked=self.ssregion,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
# Enable keyboard focus and connect events
self.btn_ssregion.set_can_focus(True)
self.btn_ssregion.connect("button-press-event", self.on_ssregion_click)
self.btn_ssregion.connect("key-press-event", self.on_ssregion_key)
self.btn_ssfull = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.ssfull),
on_clicked=self.ssfull,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
# Enable keyboard focus and connect events
self.btn_ssfull.set_can_focus(True)
self.btn_ssfull.connect("button-press-event", self.on_ssfull_click)
self.btn_ssfull.connect("key-press-event", self.on_ssfull_key)
self.btn_screenrecord = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.screenrecord),
on_clicked=self.screenrecord,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_ocr = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.ocr),
on_clicked=self.ocr,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_color = Button(
name="toolbox-button",
tooltip_text="Color Picker\nLeft Click: HEX\nMiddle Click: HSV\nRight Click: RGB\n\nKeyboard:\nEnter: HEX\nShift+Enter: RGB\nCtrl+Enter: HSV",
child=Label(name="button-bar-label", markup=icons.colorpicker),
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_gamemode = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.gamemode),
on_clicked=self.gamemode,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
# Enable keyboard focus for the colorpicker button.
self.btn_color.set_can_focus(True)
# Connect both mouse and keyboard events.
self.btn_color.connect("button-press-event", self.colorpicker)
self.btn_color.connect("key_press_event", self.colorpicker_key)
self.btn_emoji = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.emoji),
on_clicked=self.emoji,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_screenshots_folder = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.screenshots),
on_clicked=self.open_screenshots_folder,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_recordings_folder = Button(
name="toolbox-button",
child=Label(name="button-label", markup=icons.recordings),
on_clicked=self.open_recordings_folder,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.buttons = [
self.btn_ssregion,
self.btn_ssfull,
self.btn_screenshots_folder,
Box(
name="tool-sep",
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
),
self.btn_screenrecord,
self.btn_recordings_folder,
Box(
name="tool-sep",
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
),
self.btn_ocr,
self.btn_color,
Box(
name="tool-sep",
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
),
self.btn_gamemode,
self.btn_emoji,
]
for button in self.buttons:
self.add(button)
self.show_all()
# Start polling for process state every second.
self.recorder_timer_id = GLib.timeout_add_seconds(
1, self.update_screenrecord_state
)
def close_menu(self):
self.launcher.close()
# Action methods
def ssfull(self, *args):
exec_shell_command_async(f"bash {CAPTURE_SCRIPT} screenshot p")
self.close_menu()
def on_ssfull_click(self, button, event):
if event.type == Gdk.EventType.BUTTON_PRESS:
if event.button == 1: # Left click
self.ssfull()
elif event.button == 3: # Right click
exec_shell_command_async(
f"bash {CAPTURE_SCRIPT} screenshot p mockup")
self.close_menu()
return True
return False
def on_ssfull_key(self, widget, event):
if event.keyval in {Gdk.KEY_Return, Gdk.KEY_KP_Enter}:
modifiers = event.get_state()
if modifiers & Gdk.ModifierType.SHIFT_MASK:
exec_shell_command_async(
f"bash {CAPTURE_SCRIPT} screenshot p mockup")
self.close_menu()
else:
self.ssfull()
return True
return False
def ssregion(self, *args):
exec_shell_command_async(f"bash {CAPTURE_SCRIPT} screenshot sf")
self.close_menu()
def on_ssregion_click(self, button, event):
if event.type == Gdk.EventType.BUTTON_PRESS:
if event.button == 1: # Left click
self.ssregion()
elif event.button == 3: # Right click
exec_shell_command_async(
f"bash {CAPTURE_SCRIPT} screenshot sf mockup")
self.close_menu()
return True
return False
def on_ssregion_key(self, widget, event):
if event.keyval in {Gdk.KEY_Return, Gdk.KEY_KP_Enter}:
modifiers = event.get_state()
if modifiers & Gdk.ModifierType.SHIFT_MASK:
exec_shell_command_async(
f"bash {CAPTURE_SCRIPT} screenshot sf mockup")
self.close_menu()
else:
self.ssregion()
return True
return False
def screenrecord(self, *args):
# Launch screenrecord script in detached mode so that it remains running independently of this program.
exec_shell_command_async(
f"bash -c 'nohup bash {CAPTURE_SCRIPT} record > /dev/null 2>&1 & disown'"
)
self.close_menu()
def ocr(self, *args):
exec_shell_command_async(f"bash {CAPTURE_SCRIPT} ocr sf")
self.close_menu()
def gamemode(self, *args):
exec_shell_command_async(f"bash {GAMEMODE_SCRIPT}")
self.gamemode_check()
self.close_menu()
def gamemode_check(self):
def check():
try:
result = subprocess.run(
f"bash {GAMEMODE_SCRIPT} check",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
enabled = result.stdout == b"t\n"
except Exception:
enabled = False
def update_ui():
if enabled:
self.btn_gamemode.get_child().set_markup(icons.gamemode_off)
else:
self.btn_gamemode.get_child().set_markup(icons.gamemode)
return False
GLib.idle_add(update_ui)
return False
GLib.idle_add(lambda: threading.Thread(target=check).start())
return True
def ssregion(self, *args):
exec_shell_command_async(f"bash {CAPTURE_SCRIPT} screenshot sf")
self.close_menu()
def colorpicker(self, button, event):
if event.type == Gdk.EventType.BUTTON_PRESS:
cmd = {
1: "-hex", # Left click
2: "-hsv", # Middle click
3: "-rgb", # Right click
}.get(event.button)
if cmd:
exec_shell_command_async(
f"bash {
get_relative_path(
'../../../config/scripts/hyprpicker.sh')
} {cmd}"
)
self.close_menu()
def colorpicker_key(self, widget, event):
if event.keyval in {Gdk.KEY_Return, Gdk.KEY_KP_Enter}:
modifiers = event.get_state()
cmd = "-hex" # Default
match modifiers & (
Gdk.ModifierType.SHIFT_MASK | Gdk.ModifierType.CONTROL_MASK
):
case Gdk.ModifierType.SHIFT_MASK:
cmd = "-rgb"
case Gdk.ModifierType.CONTROL_MASK:
cmd = "-hsv"
exec_shell_command_async(
f"bash {get_relative_path('../../../config/scripts/hyprpicker.sh')} {
cmd
}"
)
self.close_menu()
return True
return False
def update_screenrecord_state(self):
def check():
try:
result = subprocess.run(
"pgrep -f gpu-screen-recorder",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
running = result.returncode == 0
except Exception:
running = False
def update_ui():
if running:
self.btn_screenrecord.get_child().set_markup(icons.stop)
self.btn_screenrecord.add_style_class("recording")
else:
self.btn_screenrecord.get_child().set_markup(icons.screenrecord)
self.btn_screenrecord.remove_style_class("recording")
return False
GLib.idle_add(update_ui)
return False
GLib.idle_add(lambda: threading.Thread(target=check).start())
return True
def open_screenshots_folder(self, *args):
screenshots_dir = os.path.join(
os.environ.get("XDG_PICTURES_DIR",
os.path.expanduser("~/Pictures")),
"Screenshots",
)
# Create directory if it doesn't exist
os.makedirs(screenshots_dir, exist_ok=True)
exec_shell_command_async(f"xdg-open {screenshots_dir}")
self.close_menu()
def open_recordings_folder(self, *args):
recordings_dir = os.path.join(
os.environ.get("XDG_VIDEOS_DIR", os.path.expanduser("~/Videos")),
"Recordings",
)
# Create directory if it doesn't exist
os.makedirs(recordings_dir, exist_ok=True)
exec_shell_command_async(f"xdg-open {recordings_dir}")
self.close_menu()
def emoji(self, *args):
self.launcher.open("emoji")
+174 -256
View File
@@ -1,33 +1,21 @@
import hashlib, json, os, colorsys
from PIL import Image
import os
import hashlib
from gi.repository import GdkPixbuf, Gtk, GLib, Gio, Gdk
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from gi.repository import GdkPixbuf, GLib, Gtk, Gio, Gdk
from fabric.utils import get_relative_path, exec_shell_command_async
from concurrent.futures import ThreadPoolExecutor, wait
from utils import WALLPAPERS_DIR
from fabric.widgets.label import Label
from fabric.utils.helpers import exec_shell_command_async
from PIL import Image
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
import utils.icons as icons
import config.data as data
class WallpaperSelector(Box):
CACHE_DIR = os.path.expanduser("~/.cache/modus/wallpapers")
SETTINGS_FILE = get_relative_path("../../../config/assets/settings.json")
CURRENT_WALLPAPER_FILE = os.path.expanduser("~/.cache/current_wallpaper")
SCHEMES = {
"TonalSpot": "tonalSpot",
"Expressive": "expressive",
"FruitSalad": "fruitSalad",
"Monochrome": "monochrome",
"Rainbow": "rainbow",
"Vibrant": "vibrant",
"Neutral": "neutral",
"Fidelity": "fidelity",
"Content": "content",
}
ITEM_WIDTH = 108
CACHE_DIR = f"{data.CACHE_DIR}/thumbnails"
def __init__(self, **kwargs):
super().__init__(
@@ -38,33 +26,44 @@ class WallpaperSelector(Box):
v_expand=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
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.thumbnail_queue = [], []
self.executor = ThreadPoolExecutor(max_workers=4)
self.selected_index, self.current_wallpaper = -1, None
self._init_widgets()
self._start_thumbnail_thread()
self.setup_file_monitor()
if os.path.exists(self.CURRENT_WALLPAPER_FILE):
gfile = Gio.File.new_for_path(self.CURRENT_WALLPAPER_FILE)
self.current_wp_monitor = gfile.monitor_file(
Gio.FileMonitorFlags.NONE, None
)
self.current_wp_monitor.connect(
"changed", self.on_current_wallpaper_changed
)
self.show_all()
self.search_entry.grab_focus()
def _init_widgets(self):
with os.scandir(data.WALLPAPERS_DIR) as entries:
for entry in entries:
if entry.is_file() and self._is_image(entry.name):
# Check if the file needs renaming: file should be lowercase and have hyphens instead of spaces
if entry.name != entry.name.lower() or " " in entry.name:
new_name = entry.name.lower().replace(" ", "-")
full_path = os.path.join(data.WALLPAPERS_DIR, entry.name)
new_full_path = os.path.join(data.WALLPAPERS_DIR, new_name)
try:
os.rename(full_path, new_full_path)
print(
f"Renamed old wallpaper '{full_path}' to '{new_full_path}'"
)
except Exception as e:
print(f"Error renaming file {full_path}: {e}")
# Refresh the file list after possible renaming
self.files = sorted(
[f for f in os.listdir(data.WALLPAPERS_DIR) if self._is_image(f)]
)
self.thumbnails = []
self.thumbnail_queue = []
self.executor = ThreadPoolExecutor(max_workers=4) # Shared executor
# Variable to control the selection (similar to AppLauncher)
self.selected_index = -1
# Initialize UI components
self.viewport = Gtk.IconView(name="wallpaper-icons")
self.viewport.set_model(Gtk.ListStore(GdkPixbuf.Pixbuf, str))
self.viewport.set_pixbuf_column(0)
# Hide text column so only the image is shown
self.viewport.set_text_column(-1)
self.viewport.set_item_width(self.ITEM_WIDTH)
self.viewport.set_item_width(0)
self.viewport.connect("item-activated", self.on_wallpaper_selected)
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
@@ -72,117 +71,122 @@ class WallpaperSelector(Box):
v_expand=True,
child=self.viewport,
)
self.search_entry = Entry(
name="search-entry-walls",
placeholder="Search Wallpapers...",
h_expand=True,
notify_text=lambda entry, *_: self.arrange_viewport(entry.get_text()),
on_key_press_event=self.on_search_entry_key_press,
)
self.search_entry.props.xalign = 0.5
self.search_entry.connect("focus-out-event", self.on_search_entry_focus_out)
self.schemes = {
"scheme-tonal-spot": "Tonal Spot",
"scheme-content": "Content",
"scheme-expressive": "Expressive",
"scheme-fidelity": "Fidelity",
"scheme-fruit-salad": "Fruit Salad",
"scheme-monochrome": "Monochrome",
"scheme-neutral": "Neutral",
"scheme-rainbow": "Rainbow",
}
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")
for key, display_name in self.schemes.items():
self.scheme_dropdown.append(key, display_name)
self.scheme_dropdown.set_active_id("scheme-tonal-spot")
self.scheme_dropdown.connect("changed", self.on_scheme_changed)
self.materialyoucolor_switcher = Gtk.Switch(name="materialyoucolor-switcher")
self.materialyoucolor_switcher.set_vexpand(False)
self.materialyoucolor_switcher.set_hexpand(False)
self.materialyoucolor_switcher.set_valign(Gtk.Align.CENTER)
self.materialyoucolor_switcher.set_halign(Gtk.Align.CENTER)
self.materialyoucolor_switcher.set_active(True)
# Create a switcher to enable/disable Matugen (enabled by default)
self.matugen_switcher = Gtk.Switch(name="matugen-switcher")
self.matugen_switcher.set_vexpand(False)
self.matugen_switcher.set_hexpand(False)
self.matugen_switcher.set_valign(Gtk.Align.CENTER)
self.matugen_switcher.set_halign(Gtk.Align.CENTER)
self.matugen_switcher.set_active(True)
self.mat_icon = Label(name="mat-label", markup=icons.palette)
self.dropdown_box = Box(name="dropdown-box", children=[self.scheme_dropdown])
self.custom_color_entry = Entry(
name="entry-custom-color",
h_expand=True,
notify_text=lambda entry, *_: self.on_custom_color_submitted(entry),
on_key_press_event=self.on_custom_color_key_press,
)
# Add the switcher to the header_box's start_children
self.header_box = CenterBox(
name="header-box",
spacing=10,
spacing=8,
orientation="h",
start_children=[self.materialyoucolor_switcher, self.mat_icon],
center_children=[
self.search_entry,
Label(label="Custom Color:"),
self.custom_color_entry,
],
end_children=[self.dropdown_box],
start_children=[self.matugen_switcher, self.mat_icon],
center_children=[self.search_entry],
end_children=[self.scheme_dropdown],
)
self.add(self.header_box)
self.add(self.scrolled_window)
self._start_thumbnail_thread()
self.setup_file_monitor() # Initialize file monitoring
self.show_all()
# Ensure the search entry gets focus when starting
self.search_entry.grab_focus()
def setup_file_monitor(self):
gfile = Gio.File.new_for_path(WALLPAPERS_DIR)
gfile = Gio.File.new_for_path(data.WALLPAPERS_DIR)
self.file_monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None)
self.file_monitor.connect("changed", self.on_directory_changed)
def on_current_wallpaper_changed(self, monitor, file, other_file, event_type):
if event_type in (Gio.FileMonitorEvent.CHANGED, Gio.FileMonitorEvent.CREATED):
try:
with open(self.CURRENT_WALLPAPER_FILE, "r") as f:
new_wp = f.read().strip()
if new_wp and new_wp != self.current_wallpaper:
self.current_wallpaper = new_wp
if self.custom_color_entry.get_text().strip().lower() in [
"",
"none",
]:
scheme = self.scheme_dropdown.get_active_id()
color_generator = get_relative_path(
"../../../config/material-colors/generate.py"
)
command = f'python -O {color_generator} --scheme "{scheme}" --image "{self.current_wallpaper}"'
self._run_command(command)
except Exception as e:
print(f"Error updating current wallpaper: {e}")
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)
self._delete_cache(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())
return
if event_type in (
Gio.FileMonitorEvent.CREATED,
Gio.FileMonitorEvent.CHANGED,
) and self._is_image(file_name):
if (
event_type == Gio.FileMonitorEvent.CREATED
and file_name not in self.files
):
self.files.append(file_name)
self.files.sort()
elif event_type == Gio.FileMonitorEvent.CHANGED and file_name in self.files:
self._delete_cache(file_name)
self.executor.submit(self._process_file, file_name)
def _delete_cache(self, file_name: str):
cache_path = self._get_cache_path(file_name)
if os.path.exists(cache_path):
try:
os.remove(cache_path)
except Exception:
pass
elif event_type == Gio.FileMonitorEvent.CREATED:
if self._is_image(file_name):
# Convert filename to lowercase and replace spaces with "-"
new_name = file_name.lower().replace(" ", "-")
full_path = os.path.join(data.WALLPAPERS_DIR, file_name)
new_full_path = os.path.join(data.WALLPAPERS_DIR, new_name)
if new_name != file_name:
try:
os.rename(full_path, new_full_path)
file_name = new_name
print(f"Renamed file '{full_path}' to '{new_full_path}'")
except Exception as e:
print(f"Error renaming file {full_path}: {e}")
if 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 arrange_viewport(self, query: str = ""):
model = self.viewport.get_model()
model.clear()
for pixbuf, file_name in sorted(
[
(thumb, name)
for thumb, name in self.thumbnails
if query.casefold() in name.casefold()
],
key=lambda x: x[1].lower(),
):
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:
model.append([pixbuf, file_name])
if not query.strip():
# If the search entry is empty, no icon is selected; otherwise, select the first one.
if query.strip() == "":
self.viewport.unselect_all()
self.selected_index = -1
elif len(model) > 0:
@@ -191,39 +195,40 @@ class WallpaperSelector(Box):
def on_wallpaper_selected(self, iconview, path):
model = iconview.get_model()
file_name = model[path][1]
full_path = os.path.join(WALLPAPERS_DIR, file_name)
full_path = os.path.join(data.WALLPAPERS_DIR, file_name)
selected_scheme = self.scheme_dropdown.get_active_id()
wallpaper_script = get_relative_path("../../../config/scripts/wallpaper.py")
if self.materialyoucolor_switcher.get_active():
command = f"python -O {wallpaper_script} -I {full_path}"
GLib.spawn_command_line_async(command)
self.update_scheme(selected_scheme)
if self.matugen_switcher.get_active():
# Matugen is enabled: run the normal command.
exec_shell_command_async(f"matugen image {full_path} -t {selected_scheme}")
else:
cmd = f"swww img {full_path} -t outer --transition-duration 1.5 --transition-step 255 --transition-fps 60 -f Nearest"
exec_shell_command_async(cmd)
# Matugen is disabled: run the alternative swww command.
exec_shell_command_async(
f"swww img {full_path} -t outer --transition-duration 1.5 --transition-step 255 --transition-fps 60 -f Nearest"
)
def on_scheme_changed(self, combo):
selected_scheme = combo.get_active_id()
print(f"Color scheme selected: {selected_scheme}")
def on_search_entry_key_press(self, widget, event):
if event.state & Gdk.ModifierType.SHIFT_MASK:
if event.keyval in (Gdk.KEY_Up, Gdk.KEY_Down):
scheme_list = [
scheme_id for _, scheme_id in sorted(self.SCHEMES.items())
]
try:
current_index = scheme_list.index(
self.scheme_dropdown.get_active_id()
)
except ValueError:
current_index = 0
schemes_list = list(self.schemes.keys())
current_id = self.scheme_dropdown.get_active_id()
current_index = (
schemes_list.index(current_id) if current_id in schemes_list else 0
)
new_index = (
(current_index - 1) % len(scheme_list)
(current_index - 1) % len(schemes_list)
if event.keyval == Gdk.KEY_Up
else (current_index + 1) % len(scheme_list)
else (current_index + 1) % len(schemes_list)
)
self.scheme_dropdown.set_active(new_index)
return True
elif event.keyval == Gdk.KEY_Right:
self.scheme_dropdown.popup()
return True
if event.keyval in (Gdk.KEY_Up, Gdk.KEY_Down, Gdk.KEY_Left, Gdk.KEY_Right):
self.move_selection_2d(event.keyval)
return True
@@ -239,6 +244,7 @@ class WallpaperSelector(Box):
total_items = len(model)
if total_items == 0:
return
if self.selected_index == -1:
new_index = (
0 if keyval in (Gdk.KEY_Down, Gdk.KEY_Right) else total_items - 1
@@ -246,39 +252,45 @@ class WallpaperSelector(Box):
else:
current_index = self.selected_index
allocation = self.viewport.get_allocation()
columns = max(1, allocation.width // self.ITEM_WIDTH)
new_index = current_index + (
1
if keyval == Gdk.KEY_Right
else -1
if keyval == Gdk.KEY_Left
else columns
if keyval == Gdk.KEY_Down
else -columns
)
new_index = max(0, min(new_index, total_items - 1))
item_width = 108 # Approximate item width including margins
columns = max(1, allocation.width // item_width)
if keyval == Gdk.KEY_Right:
new_index = current_index + 1
elif keyval == Gdk.KEY_Left:
new_index = current_index - 1
elif keyval == Gdk.KEY_Down:
new_index = current_index + columns
elif keyval == Gdk.KEY_Up:
new_index = current_index - columns
if new_index < 0:
new_index = 0
if new_index >= total_items:
new_index = total_items - 1
self.update_selection(new_index)
def update_selection(self, new_index: int):
self.viewport.unselect_all()
path = Gtk.TreePath.new_from_indices([new_index])
self.viewport.select_path(path)
self.viewport.scroll_to_path(path, False, 0.5, 0.5)
self.viewport.scroll_to_path(
path, False, 0.5, 0.5
) # Ensure the selected icon is visible
self.selected_index = new_index
def _start_thumbnail_thread(self):
GLib.Thread.new("thumbnail-loader", self._preload_thumbnails, None)
thread = GLib.Thread.new("thumbnail-loader", self._preload_thumbnails, None)
def _preload_thumbnails(self, _data):
futures = [
self.executor.submit(self._process_file, file_name)
for file_name in self.files
]
wait(futures)
concurrent.futures.wait(futures)
GLib.idle_add(self._process_batch)
def _process_file(self, file_name):
full_path = os.path.join(WALLPAPERS_DIR, file_name)
full_path = os.path.join(data.WALLPAPERS_DIR, file_name)
cache_path = self._get_cache_path(file_name)
if not os.path.exists(cache_path):
try:
@@ -287,10 +299,13 @@ class WallpaperSelector(Box):
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
img_cropped = img.crop((left, top, left + side, top + side))
right = left + side
bottom = top + side
img_cropped = img.crop((left, top, right, bottom))
img_cropped.thumbnail((96, 96), Image.Resampling.LANCZOS)
img_cropped.save(cache_path, "PNG")
except Exception:
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)
@@ -313,110 +328,13 @@ class WallpaperSelector(Box):
file_hash = hashlib.md5(file_name.encode("utf-8")).hexdigest()
return os.path.join(self.CACHE_DIR, f"{file_hash}.png")
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
)
self.update_scheme(scheme_id)
color_generator = get_relative_path(
"../../../config/material-colors/generate.py"
)
command = f'python -O {color_generator} -R --scheme "{scheme_id}"'
self._run_command(
command,
success_message=f"Applied color scheme: {display_name}",
failure_message="Failed to apply color scheme:",
)
def update_scheme(self, scheme: str):
self._update_settings_field("generation-scheme", scheme)
def on_custom_color_submitted(self, entry: Entry):
color = entry.get_text().strip()
if not color:
self.update_custom_color("")
return
if self.is_valid_hex_color(color):
color_value = color
elif self.is_valid_hue(color):
color_value = self.hue_to_hex(float(color))
else:
return
self.update_custom_color(color_value)
def on_custom_color_key_press(self, widget, event):
if event.keyval == Gdk.KEY_Return:
self.on_custom_color_submitted(widget)
return True
return False
def _fetch_current_wallpaper(self):
if not self.current_wallpaper or not os.path.exists(self.current_wallpaper):
if os.path.exists(self.CURRENT_WALLPAPER_FILE):
try:
with open(self.CURRENT_WALLPAPER_FILE, "r") as f:
self.current_wallpaper = f.read().strip()
except Exception as e:
print(f"Error reading current wallpaper: {e}")
return self.current_wallpaper
def update_custom_color(self, color: str):
color = color if color and color.lower() != "none" else "none"
self._update_settings_field("custom-color", color)
color_generator = get_relative_path(
"../../../config/material-colors/generate.py"
)
if color == "none":
scheme = self.scheme_dropdown.get_active_id()
current_wp = self._fetch_current_wallpaper()
command = f'python -O {color_generator} --scheme "{scheme}" --image "{current_wp}"'
else:
command = f'python -O {color_generator} --color "{color}"'
self._run_command(command)
@staticmethod
def _is_image(file_name: str) -> bool:
return file_name.lower().endswith(
(".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp")
)
@staticmethod
def is_valid_hex_color(value: str) -> bool:
return (
value.startswith("#")
and len(value) == 7
and all(c in "0123456789ABCDEFabcdef" for c in value[1:])
)
@staticmethod
def is_valid_hue(value: str) -> bool:
try:
return 0 <= float(value) <= 360
except ValueError:
return False
def hue_to_hex(self, hue: float) -> str:
r, g, b = colorsys.hls_to_rgb(hue / 360.0, 0.5, 1.0)
return f"#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
def _update_settings_field(self, field: str, value):
try:
with open(self.SETTINGS_FILE, "r") as f:
settings = json.load(f)
settings[field] = value
with open(self.SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=2)
except Exception:
pass
def _run_command(
self, command: str, success_message: str = None, failure_message: str = None
):
try:
GLib.spawn_command_line_async(command)
if success_message:
print(success_message)
except Exception:
if failure_message:
print(failure_message)
def on_search_entry_focus_out(self, widget, event):
if self.get_mapped():
widget.grab_focus()
return False
+3 -3
View File
@@ -4,12 +4,12 @@ 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 services import NetworkClient
from services import network_client
import utils.icons as icons
class WifiNetworkSlot(CenterBox):
def __init__(self, network, client: NetworkClient, **kwargs):
def __init__(self, network, client: network_client, **kwargs):
super().__init__(name="wifi-device", **kwargs)
self.network = network
self.client = client
@@ -81,7 +81,7 @@ class WifiManager(Box):
**kwargs,
)
self.client = NetworkClient()
self.client = network_client
self.scan_icon = Label(name="wifi-scan-icon", markup=icons.scan)
self.toggle_icon = Label(name="wifi-toggle-icon", markup=icons.wifi_off)
@@ -0,0 +1,312 @@
import subprocess
import json
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.widgets.entry import Entry
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.widgets.image import Image
from fabric.utils import idle_add, remove_handler, exec_shell_command_async
from utils import IconResolver
from gi.repository import GLib, Gdk, Gtk
import utils.icons as icons
import config.data as data
class WindowSwitcher(Box):
def __init__(self, **kwargs):
super().__init__(
name="window-switcher",
visible=False,
all_visible=False,
**kwargs,
)
self.launcher = kwargs["launcher"]
self.selected_index = -1 # Track the selected item index
self.icon_resolver = IconResolver()
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder="Search Windows...",
h_expand=True,
notify_text=lambda entry, *_: self.handle_search(entry.get_text()),
on_activate=lambda entry, *_: self.handle_search(entry.get_text()),
on_key_press_event=self.on_entry_key_press,
)
self.search_entry.props.xalign = 0.5
self.scrolled_window = ScrolledWindow(
name="scrolled-window",
spacing=10,
min_content_size=(450, 305),
max_content_size=(450, 305),
child=self.viewport,
)
self.header_box = Box(
name="header_box",
spacing=10,
orientation="h",
children=[
self.search_entry,
],
)
self.window_switcher_box = Box(
name="window-switcher-box",
spacing=10,
h_expand=True,
orientation="v",
children=[
self.header_box,
self.scrolled_window,
],
)
self.add(self.window_switcher_box)
self.show_all()
def close_switcher(self):
"""Close the window switcher"""
self.viewport.hide()
self.selected_index = -1 # Reset selection
self.launcher.close()
def open_switcher(self):
"""Open the window switcher and refresh windows"""
self.refresh_windows()
self.search_entry.set_text("")
self.search_entry.grab_focus()
self.viewport.show()
def refresh_windows(self):
"""Get Hyprland windows and populate the viewport"""
remove_handler(self._arranger_handler) if hasattr(self, '_arranger_handler') else None
self.viewport.children = []
self.selected_index = -1 # Clear selection when viewport changes
# Get Hyprland windows
windows = self.get_hyprland_windows()
if not windows:
# Create a container box to better center the message
container = Box(
name="no-windows-container",
orientation="v",
h_align="center",
v_align="center",
h_expand=True,
v_expand=True
)
# Show a message if no windows
label = Label(
name="no-windows",
markup=icons.window,
h_align="center",
v_align="center",
)
container.add(label)
self.viewport.add(container)
return
# Add window slots to viewport
for window in windows:
self.viewport.add(self.create_window_slot(window))
def get_hyprland_windows(self):
"""Get list of windows from Hyprland"""
try:
# Get clients info from Hyprland
result = subprocess.run(
["hyprctl", "clients", "-j"],
capture_output=True,
text=True,
check=True
)
clients = json.loads(result.stdout)
# Filter out special windows and sort by workspace
windows = []
for client in clients:
if client.get("class") and not client.get("class").startswith("special"):
windows.append(client)
# Sort windows by workspace number
windows.sort(key=lambda x: int(x.get("workspace", {}).get("id", 0)))
return windows
except Exception as e:
print(f"Error getting Hyprland windows: {e}")
return []
def create_window_slot(self, window):
"""Create a button slot for a window"""
# Get window title or class as fallback
title = window.get("title", window.get("class", "Unknown"))
workspace = window.get("workspace", {}).get("id", 0)
window_class = window.get("class", "")
# Get window icon using IconResolver
icon = self.get_window_icon(window_class)
# Create the button with window info
button = Button(
name="slot-button",
child=Box(
name="window-slot-box",
orientation="h",
spacing=10,
children=[
Image(
name="window-icon",
pixbuf=icon,
h_align="start",
),
Label(
name="workspace-label",
label=f"Workspace {workspace}",
h_align="start",
),
Label(
name="window-title",
label=title,
ellipsization="end",
v_align="center",
h_align="center",
),
],
),
on_clicked=lambda *_: self.focus_window(window.get("address")),
on_key_press_event=lambda btn, event, addr=window.get("address"): self.on_slot_key_press(btn, event, addr),
)
return button
def get_window_icon(self, window_class):
"""Get the appropriate icon for a window class using IconResolver"""
try:
# Try to get icon from IconResolver
icon = self.icon_resolver.get_icon_pixbuf(window_class, size=24)
if icon:
return icon
except Exception as e:
print(f"Error resolving icon for {window_class}: {e}")
# Fallback to default window icon if resolution fails
return icons.window
def focus_window(self, address):
"""Focus a window by its address"""
try:
subprocess.run(
["hyprctl", "dispatch", "focuswindow", f"address:{address}"],
check=True
)
self.close_switcher()
except Exception as e:
print(f"Error focusing window: {e}")
def handle_search(self, query):
"""Handle search input"""
if not query:
self.refresh_windows()
return
# Filter windows based on search query
windows = self.get_hyprland_windows()
filtered_windows = [
window for window in windows
if query.lower() in window.get("title", "").lower() or
query.lower() in window.get("class", "").lower()
]
# Update viewport with filtered results
self.viewport.children = []
self.selected_index = -1
for window in filtered_windows:
self.viewport.add(self.create_window_slot(window))
def on_entry_key_press(self, widget, event):
"""Handle key presses on the search entry"""
if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
if self.selected_index != -1:
children = self.viewport.get_children()
if 0 <= self.selected_index < len(children):
children[self.selected_index].clicked()
return True
elif event.keyval == Gdk.KEY_Down:
self.move_selection(1)
return True
elif event.keyval == Gdk.KEY_Up:
self.move_selection(-1)
return True
elif event.keyval == Gdk.KEY_Escape:
self.close_switcher()
return True
return False
def on_slot_key_press(self, button, event, address):
"""Handle key presses on window slots"""
if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
self.focus_window(address)
return True
elif event.keyval == Gdk.KEY_Escape:
self.close_switcher()
return True
return False
def move_selection(self, direction):
"""Move the selection up or down"""
children = self.viewport.get_children()
if not children:
return
new_index = self.selected_index + direction
if 0 <= new_index < len(children):
self.update_selection(new_index)
def update_selection(self, new_index):
"""Update the selected item"""
# 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):
"""Scroll to ensure the selected button is visible"""
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)
+53 -29
View File
@@ -5,15 +5,19 @@ from fabric.widgets.box import Box
from modules.launcher.components import (
AppLauncher,
BluetoothConnections,
Cliphist,
Emoji,
EmojiPicker,
PowerMenu,
Sh,
TodoManager,
WallpaperSelector,
WifiManager,
Calendar,
Dashboard,
Toolbox,
Kanban,
TmuxManager,
WindowSwitcher,
NotificationCenter,
ClipHistory,
)
@@ -22,6 +26,8 @@ class Launcher(Window):
super().__init__(
layer="top",
anchor="center",
keyboard_mode="none",
exclusivity="normal",
visible=False,
all_visible=False,
**kwargs,
@@ -30,13 +36,17 @@ class Launcher(Window):
self.dashboard = Dashboard(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.emoji = EmojiPicker(launcher=self)
self.bluetooth = BluetoothConnections(launcher=self)
self.sh = Sh(launcher=self)
self.wifi = WifiManager()
self.calendar = Calendar()
self.tools = Toolbox(launcher=self)
self.kanban = Kanban()
self.tmux = TmuxManager(launcher=self)
self.window_switcher = WindowSwitcher(launcher=self)
self.notification_center = NotificationCenter(launcher=self)
self.cliphist = ClipHistory(launcher=self)
# Wrap the dashboard in a Box container
self.dashboard = Box(
@@ -59,11 +69,15 @@ class Launcher(Window):
self.power,
self.emoji,
self.cliphist,
self.todo,
self.bluetooth,
self.sh,
self.wifi,
self.calendar,
self.tools,
self.kanban,
self.tmux,
self.window_switcher,
self.notification_center,
],
)
@@ -77,10 +91,7 @@ class Launcher(Window):
self.add(self.launcher_box)
self.show_all()
self.hide()
self.add_keybinding("Escape", self._on_escape)
def _on_escape(self, *args):
return self.close()
self.add_keybinding("Escape", lambda *_: self.close())
def close(self):
self.set_keyboard_mode("none")
@@ -92,11 +103,15 @@ class Launcher(Window):
self.power,
self.emoji,
self.cliphist,
self.todo,
self.bluetooth,
self.sh,
self.wifi,
self.calendar,
self.tools,
self.kanban,
self.tmux,
self.window_switcher,
self.notification_center,
]:
if hasattr(widget, "viewport") and widget.viewport:
widget.viewport.hide()
@@ -107,32 +122,39 @@ class Launcher(Window):
"power",
"emoji",
"cliphist",
"todo",
"bluetooth",
"sh",
"wifi",
"calendar",
"tools",
"kanban",
"tmux",
"window-switcher",
"notification-center",
]:
self.stack.remove_style_class(style)
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,
"wifi": self.wifi,
"calendar": self.calendar,
"tools": self.tools,
"kanban": self.kanban,
"tmux": self.tmux,
"window-switcher": self.window_switcher,
"notification-center": self.notification_center,
}
self.set_keyboard_mode("exclusive")
self.show()
for w in widgets.values():
w.hide()
@@ -156,22 +178,24 @@ class Launcher(Window):
self.wallpapers.search_entry.grab_focus()
self.wallpapers.viewport.show()
elif widget == "tmux":
self.tmux.open_manager()
self.tmux.search_entry.set_text("")
self.tmux.search_entry.grab_focus()
elif widget == "emoji":
self.emoji.open_launcher()
self.emoji.open_picker()
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()
self.cliphist.open()
elif widget == "sh":
self.sh.open_launcher()
self.sh.search_entry.set_text("")
self.sh.search_entry.grab_focus()
self.sh.open_sh()
elif widget == "window-switcher":
self.window_switcher.open_switcher()
elif widget == "notification-center":
self.notification_center.open_center()