51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
from i3ipc.aio import Connection
|
|
from i3ipc import Event
|
|
from .workspace_tree import WorkspaceTree
|
|
from .utils import async_debounce
|
|
|
|
|
|
class SwayConnection:
|
|
|
|
def __init__(self, workspace_tree: WorkspaceTree):
|
|
self.connection = Connection(auto_reconnect=True)
|
|
self.workspace_tree = workspace_tree
|
|
self.on_change_callbacks = []
|
|
|
|
async def on_workspace(self, connection=None, _=None):
|
|
new_data = {ws.name: ws for ws in await self.connection.get_workspaces()}
|
|
self.workspace_tree.update_workspaces(new_data)
|
|
for callback in self.on_change_callbacks:
|
|
await callback(self.workspace_tree)
|
|
|
|
@async_debounce(2)
|
|
async def on_output(self, connection, event):
|
|
"""On output event, after 2 seconds, update the workspace tree"""
|
|
self.workspace_tree.update_context(connection)
|
|
|
|
async def on_mode(self, event):
|
|
"""On mode change event, do something. Not sure what yet."""
|
|
pass
|
|
|
|
async def run(self):
|
|
# Connect to sway
|
|
await self.connection.connect()
|
|
|
|
# Register event listeners
|
|
self.connection.on(Event.WORKSPACE, self.on_workspace)
|
|
self.connection.on(Event.OUTPUT, self.on_output)
|
|
self.connection.on(Event.MODE, self.on_mode)
|
|
|
|
# Update the workspace tree
|
|
await self.workspace_tree.update_context(self.connection)
|
|
await self.on_workspace()
|
|
|
|
# Wait for events
|
|
await self.connection.main()
|
|
|
|
def on_change(self, callback):
|
|
"""Register a callback to be called when the workspace tree changes. The callback should be a coroutine, and should take the workspace tree as an argument."""
|
|
self.on_change_callbacks.append(callback)
|
|
|
|
async def close(self):
|
|
await self.connection.close()
|