♻️ refactor(bluetooth): return multiple values in tuple for connected devices and status messages

This commit is contained in:
sankalp committed 2025-06-19 13:00:45 +05:45
1 parent 78bc260e7a
commit 18c296f863
1 file changed
+59 -21
+59 -21
View File
@@ -29,7 +29,7 @@ class BluetoothPlugin(PluginBase):
def initialize(self): def initialize(self):
"""Initialize the bluetooth plugin.""" """Initialize the bluetooth plugin."""
self.set_triggers(["bluetooth", "bt", "blue"]) self.set_triggers(["bt", "bt "])
def cleanup(self): def cleanup(self):
"""Cleanup the bluetooth plugin.""" """Cleanup the bluetooth plugin."""
@@ -41,6 +41,7 @@ class BluetoothPlugin(PluginBase):
if self._scan_timeout_id: if self._scan_timeout_id:
try: try:
from gi.repository import GLib from gi.repository import GLib
GLib.source_remove(self._scan_timeout_id) GLib.source_remove(self._scan_timeout_id)
self._scan_timeout_id = None self._scan_timeout_id = None
except Exception: except Exception:
@@ -116,9 +117,15 @@ class BluetoothPlugin(PluginBase):
battery_info = "" battery_info = ""
if device.battery_percentage > 0: if device.battery_percentage > 0:
battery_info = f" ({device.battery_percentage:.0f}%)" battery_info = f" ({device.battery_percentage:.0f}%)"
return f"Connected to {device.alias}", f"Device: {device.type}{battery_info}" return (
f"Connected to {device.alias}",
f"Device: {device.type}{battery_info}",
)
else: else:
return f"Connected to {len(connected_devices)} devices", "Multiple devices connected" return (
f"Connected to {len(connected_devices)} devices",
"Multiple devices connected",
)
elif self.bluetooth_client.scanning: elif self.bluetooth_client.scanning:
return "Scanning for devices...", "Looking for nearby Bluetooth devices" return "Scanning for devices...", "Looking for nearby Bluetooth devices"
else: else:
@@ -128,7 +135,11 @@ class BluetoothPlugin(PluginBase):
"""Get appropriate icon for a bluetooth device based on its type.""" """Get appropriate icon for a bluetooth device based on its type."""
device_type = device.type.lower() device_type = device.type.lower()
if "audio" in device_type or "headphone" in device_type or "headset" in device_type: if (
"audio" in device_type
or "headphone" in device_type
or "headset" in device_type
):
return icons.headphones return icons.headphones
elif "mouse" in device_type or "keyboard" in device_type: elif "mouse" in device_type or "keyboard" in device_type:
return icons.keyboard return icons.keyboard
@@ -155,6 +166,7 @@ class BluetoothPlugin(PluginBase):
if self._scan_timeout_id: if self._scan_timeout_id:
try: try:
from gi.repository import GLib from gi.repository import GLib
GLib.source_remove(self._scan_timeout_id) GLib.source_remove(self._scan_timeout_id)
self._scan_timeout_id = None self._scan_timeout_id = None
except Exception: except Exception:
@@ -189,6 +201,7 @@ class BluetoothPlugin(PluginBase):
if self._scan_timeout_id: if self._scan_timeout_id:
try: try:
from gi.repository import GLib from gi.repository import GLib
GLib.source_remove(self._scan_timeout_id) GLib.source_remove(self._scan_timeout_id)
self._scan_timeout_id = None self._scan_timeout_id = None
except Exception: except Exception:
@@ -203,6 +216,7 @@ class BluetoothPlugin(PluginBase):
# Stop scanning if plugin hasn't been used for 10 seconds # Stop scanning if plugin hasn't been used for 10 seconds
import time import time
current_time = time.time() current_time = time.time()
if current_time - self._last_query_time > 10: if current_time - self._last_query_time > 10:
print("Stopping bluetooth scan due to inactivity...") print("Stopping bluetooth scan due to inactivity...")
@@ -228,14 +242,18 @@ class BluetoothPlugin(PluginBase):
def _create_connect_action(self, device: BluetoothDevice): def _create_connect_action(self, device: BluetoothDevice):
"""Create a connect action function with proper closure.""" """Create a connect action function with proper closure."""
def connect_action(): def connect_action():
return self._connect_device(device) return self._connect_device(device)
return connect_action return connect_action
def _create_disconnect_action(self, device: BluetoothDevice): def _create_disconnect_action(self, device: BluetoothDevice):
"""Create a disconnect action function with proper closure.""" """Create a disconnect action function with proper closure."""
def disconnect_action(): def disconnect_action():
return self._disconnect_device(device) return self._disconnect_device(device)
return disconnect_action return disconnect_action
def _force_launcher_refresh(self): def _force_launcher_refresh(self):
@@ -248,13 +266,16 @@ class BluetoothPlugin(PluginBase):
try: try:
# Try to access the launcher through the fabric Application # Try to access the launcher through the fabric Application
from fabric import Application from fabric import Application
app = Application.get_default() app = Application.get_default()
if app and hasattr(app, 'launcher'): if app and hasattr(app, "launcher"):
launcher = app.launcher launcher = app.launcher
if launcher and hasattr(launcher, '_perform_search'): if launcher and hasattr(launcher, "_perform_search"):
# Get current query and trigger a search # Get current query and trigger a search
current_query = launcher.query if hasattr(launcher, 'query') else "" current_query = (
launcher.query if hasattr(launcher, "query") else ""
)
if not current_query: if not current_query:
# If no query, use the trigger to force refresh # If no query, use the trigger to force refresh
current_query = "bt list" current_query = "bt list"
@@ -265,9 +286,15 @@ class BluetoothPlugin(PluginBase):
# Fallback: try to find launcher instance through other means # Fallback: try to find launcher instance through other means
import gc import gc
for obj in gc.get_objects(): for obj in gc.get_objects():
if hasattr(obj, '__class__') and obj.__class__.__name__ == 'Launcher': if (
if hasattr(obj, '_perform_search') and hasattr(obj, 'query'): hasattr(obj, "__class__")
and obj.__class__.__name__ == "Launcher"
):
if hasattr(obj, "_perform_search") and hasattr(
obj, "query"
):
current_query = obj.query if obj.query else "bt list" current_query = obj.query if obj.query else "bt list"
obj._perform_search(current_query) obj._perform_search(current_query)
return False return False
@@ -287,12 +314,16 @@ class BluetoothPlugin(PluginBase):
"""Process bluetooth queries.""" """Process bluetooth queries."""
# Update last query time to track plugin activity # Update last query time to track plugin activity
import time import time
self._last_query_time = time.time() self._last_query_time = time.time()
# Schedule periodic check for inactive scanning # Schedule periodic check for inactive scanning
try: try:
from gi.repository import GLib from gi.repository import GLib
GLib.timeout_add_seconds(15, lambda: (self._check_and_stop_inactive_scanning(), False))
GLib.timeout_add_seconds(
15, lambda: (self._check_and_stop_inactive_scanning(), False)
)
except Exception: except Exception:
pass pass
@@ -346,7 +377,6 @@ class BluetoothPlugin(PluginBase):
) )
) )
else: else:
results.append( results.append(
Result( Result(
@@ -417,7 +447,10 @@ class BluetoothPlugin(PluginBase):
relevance = 1.0 relevance = 1.0
elif device.connecting: elif device.connecting:
subtitle = f"Connecting... • {device.type}" subtitle = f"Connecting... • {device.type}"
action = lambda: None
def action():
return None
relevance = 0.9 relevance = 0.9
else: else:
subtitle = f"Disconnected • {device.type} • Click to connect" subtitle = f"Disconnected • {device.type} • Click to connect"
@@ -437,7 +470,7 @@ class BluetoothPlugin(PluginBase):
"device_address": device.address, "device_address": device.address,
"device_name": device.alias, "device_name": device.alias,
"connected": device.connected, "connected": device.connected,
"keep_launcher_open": True "keep_launcher_open": True,
}, },
) )
) )
@@ -476,14 +509,14 @@ class BluetoothPlugin(PluginBase):
return results return results
# Search for devices by name (like network plugin search) # Search for devices by name (like network plugin search)
if self.bluetooth_client and self.bluetooth_client.enabled: if self.bluetooth_client and self.bluetooth_client.enabled:
devices = self.bluetooth_client.devices devices = self.bluetooth_client.devices
matching_devices = [ matching_devices = [
device for device in devices device
if query_lower in device.alias.lower() or query_lower in device.name.lower() for device in devices
if query_lower in device.alias.lower()
or query_lower in device.name.lower()
] ]
if matching_devices: if matching_devices:
@@ -507,7 +540,10 @@ class BluetoothPlugin(PluginBase):
relevance = 1.0 relevance = 1.0
elif device.connecting: elif device.connecting:
subtitle = f"Connecting... • {device.type}" subtitle = f"Connecting... • {device.type}"
action = lambda: None
def action():
return None
relevance = 0.9 relevance = 0.9
else: else:
subtitle = f"Disconnected • {device.type} • Click to connect" subtitle = f"Disconnected • {device.type} • Click to connect"
@@ -527,7 +563,7 @@ class BluetoothPlugin(PluginBase):
"device_address": device.address, "device_address": device.address,
"device_name": device.alias, "device_name": device.alias,
"connected": device.connected, "connected": device.connected,
"keep_launcher_open": True "keep_launcher_open": True,
}, },
) )
) )
@@ -555,11 +591,13 @@ class BluetoothPlugin(PluginBase):
title="Bluetooth Not Available", title="Bluetooth Not Available",
subtitle="Enable Bluetooth to search for devices", subtitle="Enable Bluetooth to search for devices",
icon_markup=icons.bluetooth_off, icon_markup=icons.bluetooth_off,
action=lambda: self._toggle_bluetooth() if self.bluetooth_client else None, action=lambda: self._toggle_bluetooth()
if self.bluetooth_client
else None,
relevance=0.5, relevance=0.5,
plugin_name=self.display_name, plugin_name=self.display_name,
data={"type": "info"}, data={"type": "info"},
) )
) )
return results return results