-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmouselock-test.py
More file actions
633 lines (557 loc) · 25.5 KB
/
mouselock-test.py
File metadata and controls
633 lines (557 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import sys
import os
import threading
import time
import http.server
import socketserver
import queue
import urllib.parse
import json
import getpass
from PyQt5.QtCore import QUrl, Qt, QTimer, QBuffer, QPoint
from PyQt5.QtWidgets import (QApplication, QMainWindow, QToolBar,
QLineEdit, QPushButton, QAction, QVBoxLayout,
QWidget, QTabWidget, QStatusBar)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage
from PyQt5.QtWebEngineCore import QWebEngineHttpRequest
from PyQt5.QtGui import QKeySequence, QPixmap, QImage
runtime_dir = os.path.expanduser(f"~/.runtime-{getpass.getuser()}")
# Set environment variables for headless operation
os.environ["QT_QPA_PLATFORM"] = "offscreen"
os.environ["XDG_RUNTIME_DIR"] = f"/tmp/runtime-{getpass.getuser()}"
os.environ["QTWEBENGINE_DISABLE_GPU"] = "1"
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = ""
if not os.path.exists(os.environ["XDG_RUNTIME_DIR"]):
os.makedirs(os.environ["XDG_RUNTIME_DIR"])
socketserver.TCPServer.allow_reuse_address = True
if not os.path.exists(runtime_dir):
os.makedirs(runtime_dir)
os.chmod(runtime_dir, 0o700) # Set permissions to 0700
elif os.stat(runtime_dir).st_mode & 0o777 != 0o700: # Check if permissions are not 0700
os.chmod(runtime_dir, 0o700) # Fix permissions if they exist but are wrong
socketserver.TCPServer.allow_reuse_address = True
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class WebBrowser(QMainWindow):
def __init__(self):
super().__init__()
self.image_lock = threading.Lock()
self.image_condition = threading.Condition(self.image_lock)
self.latest_image = None
self.is_mouse_locked = False
self.last_mouse_pos = None
self.initialize_ui()
def initialize_ui(self):
self.setWindowTitle("Python Web Browser")
self.setGeometry(100, 100, 1024, 768)
self.server_dir = os.path.join(os.getcwd(), "server_files")
if not os.path.exists(self.server_dir):
os.makedirs(self.server_dir)
self.write_static_html()
self.command_queue = queue.Queue()
self.command_timer = QTimer(self)
self.command_timer.timeout.connect(self.process_commands)
self.command_timer.start(100)
self.server_port = 8000
self.stream_enabled = True
self.stream_interval = 25 # 25fps
self.stream_timer = QTimer(self)
self.stream_timer.timeout.connect(self.update_stream)
self.stream_timer.start(self.stream_interval)
self.tabs = QTabWidget()
self.tabs.setTabsClosable(True)
self.tabs.tabCloseRequested.connect(self.close_tab)
self.create_actions()
self.create_toolbar()
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.add_new_tab()
self.setCentralWidget(self.tabs)
self.start_http_server()
self.show()
def write_static_html(self):
html_content = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f0f0f0; text-align: center; }
h1 { color: #333; padding: 20px; margin: 0; background-color: #e0e0e0; }
.control-panel { margin: 20px auto; text-align: center; }
.scroll-buttons { margin-top: 10px; }
.browser-view { margin: 20px auto; max-width: 95%; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
.browser-view img { width: 100%; border: 1px solid #ddd; }
</style>
<script>
let isDragging = false;
let lastX, lastY;
function handleClick(event) {
const img = document.getElementById('stream-image');
const rect = img.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const scaleX = img.naturalWidth / rect.width;
const scaleY = img.naturalHeight / rect.height;
const actualX = Math.round(x * scaleX);
const actualY = Math.round(y * scaleY);
fetch(`/click?x=${actualX}&y=${actualY}`);
}
function handleMouseDown(event) {
isDragging = true;
const img = document.getElementById('stream-image');
const rect = img.getBoundingClientRect();
lastX = event.clientX - rect.left;
lastY = event.clientY - rect.top;
}
function handleMouseMove(event) {
if (isDragging) {
const img = document.getElementById('stream-image');
const rect = img.getBoundingClientRect();
const scaleX = img.naturalWidth / rect.width;
const scaleY = img.naturalHeight / rect.height;
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const actualX = Math.round(x * scaleX);
const actualY = Math.round(y * scaleY);
const deltaX = Math.round((x - lastX) * scaleX);
const deltaY = Math.round((y - lastY) * scaleY);
fetch(`/drag?dx=${deltaX}&dy=${deltaY}`);
lastX = x;
lastY = y;
}
}
function handleMouseUp(event) {
isDragging = false;
}
function requestMouseLock() {
fetch('/request_mouse_lock');
}
function scroll(direction, amount) {
fetch(`/scroll?direction=${direction}&amount=${amount}`);
}
document.addEventListener('keydown', function(event) {
event.preventDefault();
const key = event.key;
const modifiers = {
ctrl: event.ctrlKey,
shift: event.shiftKey,
alt: event.altKey
};
fetch(`/type?key=${encodeURIComponent(key)}&modifiers=${encodeURIComponent(JSON.stringify(modifiers))}`);
});
document.addEventListener('wheel', function(event) {
event.preventDefault();
const direction = event.deltaY > 0 ? 'down' : 'up';
const amount = Math.round(Math.abs(event.deltaY));
scroll(direction, amount);
});
document.addEventListener('DOMContentLoaded', function() {
const img = document.getElementById('stream-image');
img.addEventListener('click', handleClick);
img.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
});
</script>
</head>
<body>
<div class="control-panel">
<form action="/navigate" method="get">
<input type="text" name="url" placeholder="Enter URL" style="width: 300px;">
<button type="submit">Go</button>
</form>
<button onclick="location.href='/switch_tab?direction=prev'">Previous Tab</button>
<button onclick="location.href='/switch_tab?direction=next'">Next Tab</button>
<button onclick="requestMouseLock()">Request Mouse Lock</button>
</div>
<div class="browser-view">
<img id="stream-image" src="/stream" alt="Browser Stream View">
</div>
</body>
</html>
"""
with open(os.path.join(self.server_dir, "index.html"), "w") as f:
f.write(html_content)
def create_actions(self):
self.back_action = QAction("Back", self)
self.back_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Left))
self.back_action.triggered.connect(self.navigate_back)
self.forward_action = QAction("Forward", self)
self.forward_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Right))
self.forward_action.triggered.connect(self.navigate_forward)
self.reload_action = QAction("Reload", self)
self.reload_action.setShortcut(QKeySequence(Qt.Key_F5))
self.reload_action.triggered.connect(self.reload_page)
self.home_action = QAction("Home", self)
self.home_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_H))
self.home_action.triggered.connect(self.navigate_home)
self.new_tab_action = QAction("New Tab", self)
self.new_tab_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_T))
self.new_tab_action.triggered.connect(self.add_new_tab)
self.toggle_stream_action = QAction("Toggle Stream", self)
self.toggle_stream_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_A))
self.toggle_stream_action.triggered.connect(self.toggle_stream)
self.toggle_stream_action.setCheckable(True)
self.toggle_stream_action.setChecked(True)
def create_toolbar(self):
navigation_bar = QToolBar("Navigation")
self.addToolBar(navigation_bar)
navigation_bar.addAction(self.back_action)
navigation_bar.addAction(self.forward_action)
navigation_bar.addAction(self.reload_action)
navigation_bar.addAction(self.home_action)
navigation_bar.addAction(self.new_tab_action)
navigation_bar.addAction(self.toggle_stream_action)
self.url_bar = QLineEdit()
self.url_bar.returnPressed.connect(self.navigate_to_url)
navigation_bar.addWidget(self.url_bar)
go_button = QPushButton("Go")
go_button.clicked.connect(self.navigate_to_url)
navigation_bar.addWidget(go_button)
def add_new_tab(self, url=None):
browser = QWebEngineView()
page = QWebEnginePage()
browser.setPage(page)
page.featurePermissionRequested.connect(self.handle_feature_permission)
browser.page().loadProgress.connect(self.update_loading_progress)
browser.page().loadFinished.connect(self.update_url)
browser.page().titleChanged.connect(self.update_title)
layout = QVBoxLayout()
layout.addWidget(browser)
layout.setContentsMargins(0, 0, 0, 0)
tab = QWidget()
tab.setLayout(layout)
index = self.tabs.addTab(tab, "New Tab")
self.tabs.setCurrentIndex(index)
if url:
browser.load(QUrl(url))
else:
browser.load(QUrl("https://www.google.com"))
def close_tab(self, index):
if self.tabs.count() > 1:
self.tabs.removeTab(index)
else:
current_browser = self.get_current_browser()
current_browser.load(QUrl("https://www.google.com"))
def get_current_browser(self):
current_tab = self.tabs.currentWidget()
layout = current_tab.layout()
return layout.itemAt(0).widget()
def navigate_to_url(self):
url = self.url_bar.text()
self.load_url(url)
def load_url(self, url):
if not url.startswith(("http://", "https://")):
url = "http://" + url
current_browser = self.get_current_browser()
current_browser.load(QUrl(url))
def navigate_back(self):
current_browser = self.get_current_browser()
current_browser.back()
def navigate_forward(self):
current_browser = self.get_current_browser()
current_browser.forward()
def reload_page(self):
current_browser = self.get_current_browser()
current_browser.reload()
def navigate_home(self):
current_browser = self.get_current_browser()
current_browser.load(QUrl("https://www.google.com"))
def update_url(self):
current_browser = self.get_current_browser()
self.url_bar.setText(current_browser.url().toString())
def update_title(self, title):
index = self.tabs.currentIndex()
if title:
self.tabs.setTabText(index, title[:15] + "..." if len(title) > 15 else title)
def update_loading_progress(self, progress):
self.status_bar.showMessage(f"Loading: {progress}%")
if progress == 100:
self.status_bar.showMessage("Done", 2000)
def update_stream(self):
if not self.stream_enabled:
return
current_tab = self.tabs.currentWidget()
pixmap = current_tab.grab()
image = QImage(pixmap.toImage())
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
image.save(buffer, "JPEG", quality=70)
image_bytes = bytes(buffer.data())
with self.image_lock:
self.latest_image = image_bytes
self.image_condition.notify_all()
def toggle_stream(self):
self.stream_enabled = not self.stream_enabled
if self.stream_enabled:
self.stream_timer.start(self.stream_interval)
self.status_bar.showMessage("Stream enabled", 2000)
else:
self.stream_timer.stop()
self.status_bar.showMessage("Stream disabled", 2000)
self.toggle_stream_action.setChecked(self.stream_enabled)
def handle_feature_permission(self, url, feature):
if feature == QWebEnginePage.Feature.PointerLock:
current_browser = self.get_current_browser()
current_browser.page().setFeaturePermission(
url,
feature,
QWebEnginePage.PermissionGrantedByUser
)
self.is_mouse_locked = True
self.status_bar.showMessage("Mouse lock enabled", 2000)
def handle_drag(self, dx, dy):
current_browser = self.get_current_browser()
if self.is_mouse_locked:
js_code = f"""
(function() {{
var event = new MouseEvent('mousemove', {{
bubbles: true,
cancelable: true,
view: window,
movementX: {dx},
movementY: {dy}
}});
document.dispatchEvent(event);
}})();
"""
current_browser.page().runJavaScript(js_code)
else:
current_browser.page().runJavaScript(f"window.scrollBy({-dx}, {-dy});")
def start_http_server(self):
class BrowserHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.browser = kwargs.pop('browser', None)
self.server_directory = kwargs.pop('directory', None)
super().__init__(*args, **kwargs)
def log_message(self, format, *args):
pass
def do_GET(self):
if self.path == '/stream':
self.send_response(200)
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=frame')
self.end_headers()
try:
while True:
with self.browser.image_lock:
self.browser.image_condition.wait()
image_bytes = self.browser.latest_image
self.wfile.write(b'--frame\r\n')
self.wfile.write(b'Content-Type: image/jpeg\r\n\r\n')
self.wfile.write(image_bytes)
self.wfile.write(b'\r\n')
except Exception as e:
print(f"Stream closed: {e}")
elif self.path.startswith('/navigate?'):
query = self.path.split('?')[1]
params = urllib.parse.parse_qs(query)
url = params.get('url', [''])[0]
if url:
self.browser.command_queue.put(('navigate', url))
self.send_response(303)
self.send_header('Location', '/')
self.end_headers()
elif self.path.startswith('/scroll?'):
try:
query = self.path.split('?')[1]
params = urllib.parse.parse_qs(query)
direction = params.get('direction', [''])[0]
amount_str = params.get('amount', ['100'])[0]
try:
amount = int(float(amount_str))
except ValueError:
amount = 100
self.browser.command_queue.put(('scroll', direction, amount))
self.send_response(200)
self.end_headers()
except Exception as e:
print(f"Error processing scroll request: {e}")
self.send_response(400)
self.end_headers()
elif self.path.startswith('/type?'):
query = self.path.split('?')[1]
params = urllib.parse.parse_qs(query)
key = urllib.parse.unquote(params.get('key', [''])[0])
modifiers = json.loads(urllib.parse.unquote(params.get('modifiers', ['{}'])[0]))
self.browser.command_queue.put(('type', key, modifiers))
self.send_response(200)
self.end_headers()
elif self.path.startswith('/click?'):
query = self.path.split('?')[1]
params = urllib.parse.parse_qs(query)
x = int(params.get('x', [0])[0])
y = int(params.get('y', [0])[0])
self.browser.command_queue.put(('click', x, y))
self.send_response(200)
self.end_headers()
elif self.path.startswith('/drag?'):
query = self.path.split('?')[1]
params = urllib.parse.parse_qs(query)
dx = int(params.get('dx', [0])[0])
dy = int(params.get('dy', [0])[0])
self.browser.command_queue.put(('drag', dx, dy))
self.send_response(200)
self.end_headers()
elif self.path == '/request_mouse_lock':
self.browser.command_queue.put(('request_mouse_lock',))
self.send_response(200)
self.end_headers()
else:
super().do_GET()
def handler_factory(*args, **kwargs):
kwargs['browser'] = self
kwargs['directory'] = self.server_dir
return BrowserHandler(*args, **kwargs)
self.server = ThreadedTCPServer(("", self.server_port), handler_factory)
server_thread = threading.Thread(target=self.server.serve_forever)
server_thread.daemon = True
server_thread.start()
print(f"Browser stream server running at http://localhost:{self.server_port}")
time.sleep(0.5)
def handle_click(self, x, y):
current_browser = self.get_current_browser()
if not current_browser or not current_browser.page():
print("Error: No valid browser or page found.")
return
js_code = f"""
(function() {{
var element = document.elementFromPoint({x}, {y});
if (element) {{
var mousedownEvent = new MouseEvent('mousedown', {{
bubbles: true,
cancelable: true,
view: window,
clientX: {x},
clientY: {y}
}});
element.dispatchEvent(mousedownEvent);
var mouseupEvent = new MouseEvent('mouseup', {{
bubbles: true,
cancelable: true,
view: window,
clientX: {x},
clientY: {y}
}});
element.dispatchEvent(mouseupEvent);
var clickEvent = new MouseEvent('click', {{
bubbles: true,
cancelable: true,
view: window,
clientX: {x},
clientY: {y}
}});
element.dispatchEvent(clickEvent);
}}
}})();
"""
current_browser.page().runJavaScript(js_code)
def process_commands(self):
try:
while not self.command_queue.empty():
command = self.command_queue.get_nowait()
if command[0] == 'navigate':
self.load_url(command[1])
elif command[0] == 'scroll':
self.handle_scroll(command[1], command[2])
elif command[0] == 'type':
self.handle_key_press(command[1], command[2])
elif command[0] == 'click':
self.handle_click(command[1], command[2])
elif command[0] == 'drag':
self.handle_drag(command[1], command[2])
elif command[0] == 'request_mouse_lock':
current_browser = self.get_current_browser()
current_browser.page().runJavaScript("document.body.requestPointerLock();")
self.command_queue.task_done()
except queue.Empty:
pass
def handle_scroll(self, direction, amount):
current_browser = self.get_current_browser()
if direction == 'up':
current_browser.page().runJavaScript(f"window.scrollBy(0, -{amount});")
elif direction == 'down':
current_browser.page().runJavaScript(f"window.scrollBy(0, {amount});")
def handle_key_press(self, key, modifiers):
current_browser = self.get_current_browser()
key_escaped = key.replace("'", "\\'")
shift = 'true' if key == 'Shift' else 'false'
ctrl = 'true' if key == 'Control' else 'false'
alt = 'true' if key == 'Alt' else 'false'
meta = 'true' if key == 'Meta' else 'false'
js_code = f"""
(function() {{
var activeEl = document.activeElement;
if (!activeEl) return;
if ('{key_escaped}' === 'Enter') {{
var keyDownEvent = new KeyboardEvent('keydown', {{
key: 'Enter',
code: 'Enter',
keyCode: 13,
which: 13,
shiftKey: {shift},
ctrlKey: {ctrl},
altKey: {alt},
metaKey: {meta},
bubbles: true,
cancelable: true
}});
activeEl.dispatchEvent(keyDownEvent);
var keyUpEvent = new KeyboardEvent('keyup', {{
key: 'Enter',
code: 'Enter',
keyCode: 13,
which: 13,
shiftKey: {shift},
ctrlKey: {ctrl},
altKey: {alt},
metaKey: {meta},
bubbles: true,
cancelable: true
}});
activeEl.dispatchEvent(keyUpEvent);
if (activeEl.tagName === 'INPUT' && activeEl.form) {{
activeEl.form.submit();
}}
}} else if ('{key_escaped}' === 'Backspace' && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA')) {{
if (activeEl.value.length > 0) {{
activeEl.value = activeEl.value.slice(0, -1);
}}
var keyDownEvent = new KeyboardEvent('keydown', {{
key: 'Backspace',
code: 'Backspace',
keyCode: 8,
which: 8,
bubbles: true,
cancelable: true
}});
activeEl.dispatchEvent(keyDownEvent);
}} else {{
var keyDownEvent = new KeyboardEvent('keydown', {{
key: '{key_escaped}',
code: '{key_escaped}',
bubbles: true,
cancelable: true,
shiftKey: {shift},
ctrlKey: {ctrl},
altKey: {alt},
metaKey: {meta}
}});
activeEl.dispatchEvent(keyDownEvent);
if (!['Shift', 'Control', 'Alt', 'Meta', 'Enter', 'Backspace'].includes('{key_escaped}')) {{
if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {{
activeEl.value += '{key_escaped}';
}}
}}
}}
}})();
"""
current_browser.page().runJavaScript(js_code)
if __name__ == "__main__":
QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
app = QApplication(sys.argv)
browser = WebBrowser()
print(f"Browser stream server running at http://localhost:{browser.server_port}")
sys.exit(app.exec_())
#xvfb-run /home/codespace/.python/current/bin/python /workspaces/brow/mouselock-test.py