This commit is contained in:
sankalp committed 2025-07-21 00:55:51 +05:45
1 parent 532d3ceb39
commit 4a2fc70ff9
4 files changed
+70 -60

No files matched your search

+2 -2
View File
@@ -808,7 +808,7 @@ class HyprConfGUI(Window):
return scrolled_window return scrolled_window
def _add_disk_entry_widget(self, path): def _add_disk_entry_widget(self, path):
"""Helper para añadir una fila de entrada de disco al Box disk_entries.""" """Helper to add a disk entry row to the disk_entries Box."""
bar = Box(orientation="h", spacing=10, h_align="start") bar = Box(orientation="h", spacing=10, h_align="start")
entry = Entry(text=path, h_expand=True) entry = Entry(text=path, h_expand=True)
bar.add(entry) bar.add(entry)
@@ -1123,7 +1123,7 @@ class HyprConfGUI(Window):
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
) )
kill_proc.wait(timeout=2) kill_proc.wait(timeout=2)
print(f"{time.time():.4f}: killall process finished (o timed out).") print(f"{time.time():.4f}: killall process finished (or timed out).")
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
print("Warning: killall command timed out.") print("Warning: killall command timed out.")
except Exception as e: except Exception as e:
+37 -38
View File
@@ -8,7 +8,7 @@ import gi
import toml import toml
from fabric.utils.helpers import exec_shell_command_async from fabric.utils.helpers import exec_shell_command_async
from config.data import ( # CONFIG_DIR, HOME_DIR no se usan aquí directamente from config.data import (
APP_NAME, APP_NAME,
APP_NAME_CAP, APP_NAME_CAP,
) )
@@ -16,10 +16,9 @@ from config.settings import constants as settings_constants
gi.require_version("Gtk", "3.0") gi.require_version("Gtk", "3.0")
# Importar settings_constants para DEFAULTS
# Global variable to store binding variables, managed by this module # Global variable to store binding variables, managed by this module
bind_vars = {} # Se inicializa vacío, load_bind_vars lo poblará bind_vars = {}
def deep_update(target: dict, update: dict) -> dict: def deep_update(target: dict, update: dict) -> dict:
@@ -29,13 +28,13 @@ def deep_update(target: dict, update: dict) -> dict:
""" """
for key, value in update.items(): for key, value in update.items():
if isinstance(value, dict) and key in target and isinstance(target[key], dict): if isinstance(value, dict) and key in target and isinstance(target[key], dict):
# Si el valor es un diccionario y la clave ya existe en target como diccionario, # If the value is a dictionary and the key already exists in target as a dictionary,
# entonces actualiza recursivamente. # then update recursively.
deep_update(target[key], value) deep_update(target[key], value)
else: else:
# De lo contrario, simplemente establece/sobrescribe el valor. # Otherwise, simply set/overwrite the value.
target[key] = value target[key] = value
return target # Aunque modifica in-place, devolverlo es una convención común return target # Although it modifies in-place, returning it is a common convention
def ensure_matugen_config(): def ensure_matugen_config():
@@ -101,19 +100,19 @@ def ensure_matugen_config():
config_path config_path
}. A new default config will be created." }. A new default config will be created."
) )
existing_config = {} # Resetear si está corrupto existing_config = {} # Reset if corrupted
except Exception as e: except Exception as e:
print(f"Error reading or backing up {config_path}: {e}") print(f"Error reading or backing up {config_path}: {e}")
# existing_config podría estar parcialmente cargado o vacío. # existing_config could be partially loaded or empty.
# Continuar para intentar fusionar con defaults. # Continue to try merging with defaults.
# Usamos una copia de existing_config para deep_update si no queremos modificarlo directamente # We use a copy of existing_config for deep_update if we don't want to modify it directly
# o asegurarse que deep_update no lo haga si no es deseado. # or ensure that deep_update doesn't do it if not desired.
# La implementación actual de deep_update modifica 'target'. # The current implementation of deep_update modifies 'target'.
# Para ser más seguros, podemos pasar una copia si existing_config no debe cambiar. # To be safer, we can pass a copy if existing_config should not change.
# merged_config = deep_update(existing_config.copy(), expected_config) # merged_config = deep_update(existing_config.copy(), expected_config)
# O si existing_config puede ser modificado: # Or if existing_config can be modified:
# existing_config se modifica in-place # existing_config is modified in-place
merged_config = deep_update(existing_config, expected_config) merged_config = deep_update(existing_config, expected_config)
try: try:
@@ -143,8 +142,8 @@ def ensure_matugen_config():
) )
if os.path.exists(example_wallpaper_path): if os.path.exists(example_wallpaper_path):
try: try:
# Si ya existe (posiblemente un enlace roto o archivo regular), eliminar y re-enlazar # If it already exists (possibly a broken link or regular file), remove and re-link
# lexists para no seguir el enlace si es uno # lexists to not follow the link if it is one
if os.path.lexists(current_wall): if os.path.lexists(current_wall):
os.remove(current_wall) os.remove(current_wall)
os.symlink(example_wallpaper_path, current_wall) os.symlink(example_wallpaper_path, current_wall)
@@ -172,7 +171,7 @@ def ensure_matugen_config():
print( print(
"Warning: No wallpaper path determined to generate matugen theme from." "Warning: No wallpaper path determined to generate matugen theme from."
) )
else: # image_path existe pero el archivo no else: # image_path exists but the file doesn't
print( print(
f"Warning: Wallpaper at { f"Warning: Wallpaper at {
image_path image_path
@@ -185,12 +184,12 @@ def load_bind_vars():
Load saved key binding variables from JSON, if available. Load saved key binding variables from JSON, if available.
Populates the global `bind_vars` in-place. Populates the global `bind_vars` in-place.
""" """
global bind_vars # Necesario para modificar el objeto global bind_vars global bind_vars # Necessary to modify the global bind_vars object
# 1. Limpiar el diccionario bind_vars existente. # 1. Clear the existing bind_vars dictionary.
bind_vars.clear() bind_vars.clear()
# 2. Actualizarlo con una copia de DEFAULTS. # 2. Update it with a copy of DEFAULTS.
# Usar .copy() para no modificar DEFAULTS accidentalmente # Use .copy() to not accidentally modify DEFAULTS
bind_vars.update(settings_constants.DEFAULTS.copy()) bind_vars.update(settings_constants.DEFAULTS.copy())
config_json = os.path.expanduser( config_json = os.path.expanduser(
@@ -200,22 +199,22 @@ def load_bind_vars():
try: try:
with open(config_json, "r") as f: with open(config_json, "r") as f:
saved_vars = json.load(f) saved_vars = json.load(f)
# 3. Usar deep_update para fusionar saved_vars en el bind_vars existente. # 3. Use deep_update to merge saved_vars into the existing bind_vars.
deep_update(bind_vars, saved_vars) deep_update(bind_vars, saved_vars)
# La lógica para asegurar la estructura de diccionarios anidados # The logic to ensure the structure of nested dictionaries
# como 'metrics_visible' y 'metrics_small_visible' # like 'metrics_visible' and 'metrics_small_visible'
# debe operar sobre el 'bind_vars' ya actualizado. # should operate on the already updated 'bind_vars'.
for vis_key in ["metrics_visible"]: for vis_key in ["metrics_visible"]:
# Asegurar que la clave exista en DEFAULTS como referencia de estructura # Ensure that the key exists in DEFAULTS as a structure reference
if vis_key in settings_constants.DEFAULTS: if vis_key in settings_constants.DEFAULTS:
default_sub_dict = settings_constants.DEFAULTS[vis_key] default_sub_dict = settings_constants.DEFAULTS[vis_key]
# Si la clave no está en bind_vars o no es un diccionario después de deep_update, # If the key is not in bind_vars or is not a dictionary after deep_update,
# restaurarla desde una copia de DEFAULTS para esa clave. # restore it from a copy of DEFAULTS for that key.
if not isinstance(bind_vars.get(vis_key), dict): if not isinstance(bind_vars.get(vis_key), dict):
bind_vars[vis_key] = default_sub_dict.copy() bind_vars[vis_key] = default_sub_dict.copy()
else: else:
# Si es un diccionario, asegurar que todas las sub-claves de DEFAULTS estén presentes. # If it is a dictionary, ensure that all sub-keys from DEFAULTS are present.
current_sub_dict = bind_vars[vis_key] current_sub_dict = bind_vars[vis_key]
for m_key, m_val in default_sub_dict.items(): for m_key, m_val in default_sub_dict.items():
if m_key not in current_sub_dict: if m_key not in current_sub_dict:
@@ -226,16 +225,16 @@ def load_bind_vars():
config_json config_json
}. Using defaults (already initialized)." }. Using defaults (already initialized)."
) )
# bind_vars ya está poblado con DEFAULTS, no se necesita acción adicional aquí. # bind_vars is already populated with DEFAULTS, no additional action needed here.
except Exception as e: except Exception as e:
print( print(
f"Error loading config from {config_json}: { f"Error loading config from {config_json}: {
e e
}. Using defaults (already initialized)." }. Using defaults (already initialized)."
) )
# bind_vars ya está poblado con DEFAULTS. # bind_vars is already populated with DEFAULTS.
# else: # else:
# Si config_json no existe, bind_vars ya está poblado con DEFAULTS. # If config_json doesn't exist, bind_vars is already populated with DEFAULTS.
# print(f"Config file {config_json} not found. Using defaults (already initialized).") # print(f"Config file {config_json} not found. Using defaults (already initialized).")
@@ -358,7 +357,7 @@ def backup_and_replace(src: str, dest: str, config_name: str):
try: try:
if os.path.exists(dest): if os.path.exists(dest):
backup_path = dest + ".bak" backup_path = dest + ".bak"
# Asegurarse que el directorio de backup existe si es diferente # Ensure that the backup directory exists if it's different
# os.makedirs(os.path.dirname(backup_path), exist_ok=True) # os.makedirs(os.path.dirname(backup_path), exist_ok=True)
shutil.copy(dest, backup_path) shutil.copy(dest, backup_path)
print(f"{config_name} config backed up to {backup_path}") print(f"{config_name} config backed up to {backup_path}")
@@ -382,7 +381,7 @@ def start_config():
hypr_config_dir = os.path.expanduser(f"~/.config/{APP_NAME_CAP}/config/hypr/") hypr_config_dir = os.path.expanduser(f"~/.config/{APP_NAME_CAP}/config/hypr/")
os.makedirs(hypr_config_dir, exist_ok=True) os.makedirs(hypr_config_dir, exist_ok=True)
# Usar APP_NAME para el nombre del archivo .conf para que coincida con SOURCE_STRING corregido # Use APP_NAME for the .conf file name to match the corrected SOURCE_STRING
hypr_conf_path = os.path.join(hypr_config_dir, f"{APP_NAME}.conf") hypr_conf_path = os.path.join(hypr_config_dir, f"{APP_NAME}.conf")
try: try:
with open(hypr_conf_path, "w") as f: with open(hypr_conf_path, "w") as f:
@@ -395,7 +394,7 @@ def start_config():
print(f"{time.time():.4f}: start_config: Initiating hyprctl reload...") print(f"{time.time():.4f}: start_config: Initiating hyprctl reload...")
try: try:
# subprocess.run(["hyprctl", "reload"], check=True, capture_output=True, text=True) # subprocess.run(["hyprctl", "reload"], check=True, capture_output=True, text=True)
# Mantener async para no bloquear # Keep async to not block
exec_shell_command_async("hyprctl reload") exec_shell_command_async("hyprctl reload")
print( print(
f"{time.time():.4f}: start_config: Hyprland configuration reload initiated." f"{time.time():.4f}: start_config: Hyprland configuration reload initiated."
@@ -404,7 +403,7 @@ def start_config():
print("Error: hyprctl command not found. Cannot reload Hyprland.") print("Error: hyprctl command not found. Cannot reload Hyprland.")
except ( except (
subprocess.CalledProcessError subprocess.CalledProcessError
) as e: # Si usáramos subprocess.run con check=True ) as e: # If we used subprocess.run with check=True
print( print(
f"Error reloading Hyprland with hyprctl: {e}\nOutput:\n{e.stdout}\n{ f"Error reloading Hyprland with hyprctl: {e}\nOutput:\n{e.stdout}\n{
e.stderr e.stderr
+20 -10
View File
@@ -27,7 +27,8 @@ class ClipboardPlugin(PluginBase):
# Initialize cache and temp directory # Initialize cache and temp directory
self.tmp_dir = tempfile.mkdtemp(prefix="cliphist-") self.tmp_dir = tempfile.mkdtemp(prefix="cliphist-")
self.image_cache: Dict[str, GdkPixbuf.Pixbuf] = {} # Cache images forever like example_cliphist.py # Cache images forever like example_cliphist.py
self.image_cache: Dict[str, GdkPixbuf.Pixbuf] = {}
self.clipboard_items_cache: List[str] = [] self.clipboard_items_cache: List[str] = []
self.cache_timestamp = 0 self.cache_timestamp = 0
@@ -212,11 +213,14 @@ class ClipboardPlugin(PluginBase):
def _is_image_data(self, content: str) -> bool: def _is_image_data(self, content: str) -> bool:
"""Determine if clipboard content is likely an image (like example_cliphist.py).""" """Determine if clipboard content is likely an image (like example_cliphist.py)."""
return ( return (
content.startswith("data:image/") or content.startswith("data:image/")
content.startswith("\x89PNG") or or content.startswith("\x89PNG")
content.startswith("GIF8") or or content.startswith("GIF8")
content.startswith("\xff\xd8\xff") or or content.startswith("\xff\xd8\xff")
"binary" in content.lower() and any(ext in content.lower() for ext in ["jpg", "jpeg", "png", "bmp", "gif"]) or "binary" in content.lower()
and any(
ext in content.lower() for ext in ["jpg", "jpeg", "png", "bmp", "gif"]
)
) )
def _get_text_preview(self, content: str) -> str: def _get_text_preview(self, content: str) -> str:
@@ -288,13 +292,15 @@ class ClipboardPlugin(PluginBase):
elif query_lower in content_lower: elif query_lower in content_lower:
# Position-based scoring: earlier matches get higher scores # Position-based scoring: earlier matches get higher scores
position = content_lower.find(query_lower) position = content_lower.find(query_lower)
relevance = max(0.5, 1.0 - (position / len(content_lower)) * 0.4) relevance = max(
0.5, 1.0 - (position / len(content_lower)) * 0.4
)
filtered_items.append((item, relevance)) filtered_items.append((item, relevance))
# Sort by relevance (highest first) and then limit results # Sort by relevance (highest first) and then limit results
filtered_items.sort(key=lambda x: x[1], reverse=True) filtered_items.sort(key=lambda x: x[1], reverse=True)
filtered_items = filtered_items[:self.max_results] filtered_items = filtered_items[: self.max_results]
# Process items with lazy image loading # Process items with lazy image loading
for i, (item, relevance) in enumerate(filtered_items): for i, (item, relevance) in enumerate(filtered_items):
@@ -334,7 +340,9 @@ class ClipboardPlugin(PluginBase):
icon=immediate_pixbuf, icon=immediate_pixbuf,
relevance=relevance, relevance=relevance,
plugin_name=self.name, plugin_name=self.name,
action=lambda id=item_id: self._copy_to_clipboard(id), action=lambda id=item_id: self._copy_to_clipboard(
id
),
data={"bypass_max_results": True}, data={"bypass_max_results": True},
) )
else: else:
@@ -346,7 +354,9 @@ class ClipboardPlugin(PluginBase):
icon_name="image-x-generic", icon_name="image-x-generic",
relevance=relevance, relevance=relevance,
plugin_name=self.name, plugin_name=self.name,
action=lambda id=item_id: self._copy_to_clipboard(id), action=lambda id=item_id: self._copy_to_clipboard(
id
),
data={"bypass_max_results": True}, data={"bypass_max_results": True},
) )
except Exception: except Exception:
+11 -10
View File
@@ -115,7 +115,6 @@ class ScreencapturePlugin(PluginBase):
def _get_command_result(self, command: str) -> Result: def _get_command_result(self, command: str) -> Result:
"""Get a Result object for a specific command.""" """Get a Result object for a specific command."""
# Import here to avoid circular imports # Import here to avoid circular imports
from utils.icons import screenrecord, screenshots, ssfull, ssregion, stop
command_info = { command_info = {
# Screenshot commands # Screenshot commands
@@ -436,7 +435,6 @@ class ScreencapturePlugin(PluginBase):
def query(self, query_string: str) -> List[Result]: def query(self, query_string: str) -> List[Result]:
"""Search for screencapture actions based on query.""" """Search for screencapture actions based on query."""
# Import here to avoid circular imports # Import here to avoid circular imports
from utils.icons import screenrecord, screenshots, ssfull, ssregion, stop
# Clean the query string # Clean the query string
query = query_string.strip().lower() query = query_string.strip().lower()
@@ -463,14 +461,17 @@ class ScreencapturePlugin(PluginBase):
if command in file_conversion_commands: if command in file_conversion_commands:
format_type = file_conversion_commands[command] format_type = file_conversion_commands[command]
return [Result( return [
title=f"Convert {file_param} to {format_type.upper()}", Result(
subtitle=f"Convert specified file to {format_type} format", title=f"Convert {file_param} to {format_type.upper()}",
icon_markup=screenrecord, subtitle=f"Convert specified file to {format_type} format",
action=lambda fp=file_param, ft=format_type: self._run_script_with_file(ft, fp), icon_markup=screenrecord,
relevance=1.0, action=lambda fp=file_param,
plugin_name=self.display_name, ft=format_type: self._run_script_with_file(ft, fp),
)] relevance=1.0,
plugin_name=self.display_name,
)
]
# Check if query matches a command and return it as a result # Check if query matches a command and return it as a result
command_result = self._get_command_result(query) command_result = self._get_command_result(query)