Skip to content

Commit e719567

Browse files
committed
examples: Add script to auto attach to any compositor
1 parent 27a8008 commit e719567

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

examples/auto-attach.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/env python
2+
3+
import asyncio
4+
import json
5+
import re
6+
import os
7+
import glob
8+
9+
class Program:
10+
command_seq = 0
11+
reader = None
12+
writer = None
13+
read_buffer = ""
14+
message_queue = asyncio.Queue()
15+
reply_queue = asyncio.Queue()
16+
decoder = json.JSONDecoder()
17+
tasks = []
18+
19+
async def read_message(self):
20+
while True:
21+
try:
22+
result, index = self.decoder.raw_decode(self.read_buffer)
23+
self.read_buffer = self.read_buffer[index:].lstrip()
24+
return result
25+
except json.JSONDecodeError:
26+
data = await self.reader.read(4096)
27+
self.read_buffer += data.decode('utf-8')
28+
29+
async def send_command(self, method, params = None):
30+
cmd = {
31+
"method": method,
32+
"id": self.command_seq,
33+
}
34+
35+
if not params is None:
36+
cmd['params'] = params
37+
38+
self.command_seq += 1
39+
self.writer.write(json.dumps(cmd).encode())
40+
await self.writer.drain()
41+
42+
reply = await self.reply_queue.get()
43+
self.reply_queue.task_done()
44+
return reply['code'] == 0
45+
46+
async def attach(self, display):
47+
return await self.send_command('attach', {'display': display})
48+
49+
async def attach_any(self):
50+
for path in glob.iglob('/run/user/*/wayland-*'):
51+
if path.endswith('.lock'):
52+
continue
53+
54+
if await self.attach(path):
55+
return True
56+
57+
return False
58+
59+
async def handle_detached(self):
60+
while not await self.attach_any():
61+
await asyncio.sleep(1.0)
62+
63+
async def process_message(self, message):
64+
method = message['method']
65+
if (method == 'detached'):
66+
await self.handle_detached()
67+
68+
async def message_processor(self):
69+
while True:
70+
message = await self.read_message()
71+
if 'method' in message:
72+
await self.message_queue.put(message)
73+
elif 'code' in message:
74+
await self.reply_queue.put(message)
75+
76+
async def main(self):
77+
self.reader, self.writer = await asyncio.open_unix_connection("/tmp/wayvncctl-0")
78+
self.tasks.append(asyncio.create_task(self.message_processor()))
79+
80+
await self.attach_any()
81+
await self.send_command("event-receive")
82+
83+
while True:
84+
message = await self.message_queue.get()
85+
await self.process_message(message)
86+
87+
prog = Program()
88+
asyncio.run(prog.main())

0 commit comments

Comments
 (0)