Debian Codegraph @

DisplayCAL/wx_scripting_client.py

raw
1 """Scripting client for DisplayCAL with a graphical command interface.
2
3 It features a terminal-like interface built with wxPython, supporting command
4 history, text highlighting, and basic scripting capabilities.
5 """
6
7 import errno
8 import os
9 import socket
10 import sys
11 from time import sleep
12
13 from wx.lib import delayedresult
14
15 from DisplayCAL import (
16 config,
17 )
18 from DisplayCAL import localization as lang
19 from DisplayCAL.config import CONFIG_HOME, getcfg, setcfg, writecfg
20 from DisplayCAL.meta import NAME as APPNAME
21 from DisplayCAL.util_str import safe_str, universal_newlines
22 from DisplayCAL.wexpect import split_command_line
23 from DisplayCAL.wx_addons import wx
24 from DisplayCAL.wx_windows import NUMPAD_KEYCODES, BaseApp, SimpleTerminal
25
26 ERRORCOLOR = "#FF3300"
27 RESPONSECOLOR = "#CCCCCC"
28
29
30 class ScriptingClientFrame(SimpleTerminal):
31 """A wxPython frame that serves as a scripting client for DisplayCAL."""
32
33 def __init__(self):
34 SimpleTerminal.__init__(
35 self,
36 None,
37 wx.ID_ANY,
38 lang.getstr("scripting-client"),
39 start_timer=False,
40 pos=(getcfg("position.scripting.x"), getcfg("position.scripting.y")),
41 size=(getcfg("size.scripting.w"), getcfg("size.scripting.h")),
42 consolestyle=wx.TE_CHARWRAP
43 | wx.TE_MULTILINE
44 | wx.TE_PROCESS_ENTER
45 | wx.TE_RICH
46 | wx.VSCROLL
47 | wx.NO_BORDER,
48 show=False,
49 name="scriptingframe",
50 )
51 self.SetIcons(
52 config.get_icon_bundle([256, 48, 32, 16], f"{APPNAME}-scripting-client")
53 )
54 self.console.SetForegroundColour("#EEEEEE")
55 self.console.SetDefaultStyle(wx.TextAttr("#EEEEEE"))
56
57 self.busy = False
58 self.commands = []
59 self.history = []
60 self.historyfilename = os.path.join(
61 CONFIG_HOME, f"{config.APPBASENAME}-scripting-client.history"
62 )
63 if os.path.isfile(self.historyfilename):
64 try:
65 with open(self.historyfilename) as historyfile:
66 for line in historyfile:
67 self.history.append(line.rstrip("\r\n"))
68 except OSError as exception:
69 print("Warning - couldn't read history file:", exception)
70 # Always have empty selection at bottom
71 self.history.append("")
72 self.historypos = len(self.history) - 1
73
74 self.overwrite = False
75
76 # Determine which application we should connect to by default (if any)
77 self.conn = None
78 scripting_hosts = self.get_scripting_hosts()
79
80 self.sizer.Layout()
81 if sys.platform != "darwin":
82 # Under Mac OS X, the transparency messes up the window shadow if
83 # there is another window's border behind
84 self.SetTransparent(240)
85
86 self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
87 self.Bind(wx.EVT_SIZE, self.OnSize)
88 self.Unbind(wx.EVT_CHAR_HOOK)
89 self.console.Unbind(wx.EVT_KEY_DOWN, self.console)
90 self.console.Bind(wx.EVT_KEY_DOWN, self.key_handler)
91 self.console.Bind(wx.EVT_TEXT_COPY, self.copy_text_handler)
92 self.console.Bind(wx.EVT_TEXT_PASTE, self.paste_text_handler)
93 if sys.platform == "darwin":
94 # Under Mac OS X, pasting text via the context menu isn't catched
95 # by EVT_TEXT_PASTE. TODO: Implement custom context menu.
96 self.console.Bind(wx.EVT_CONTEXT_MENU, lambda event: None)
97
98 if scripting_hosts:
99 self.add_text("> getscriptinghosts" + "\n")
100 for host in scripting_hosts:
101 self.add_text(host + "\n")
102 ip_port = scripting_hosts[0].split()[0]
103 self.add_text("> connect " + ip_port + "\n")
104 self.connect_handler(ip_port)
105
106 def OnActivate(self, event):
107 """Handle the activation of the console window.
108
109 Args:
110 event (wx.Event): The event triggered by activating the window.
111 """
112 self.console.SetFocus()
113 linecount = self.console.GetNumberOfLines()
114 lastline = self.console.GetLineText(linecount - 1)
115 lastpos = self.console.GetLastPosition()
116 start, end = self.console.GetSelection()
117 if start == end and self.console.GetInsertionPoint() < lastpos - len(lastline):
118 self.console.SetInsertionPoint(lastpos)
119
120 def OnClose(self, event):
121 """Handle the closing of the console window.
122
123 Args:
124 event (wx.Event): The event triggered by closing the window.
125 """
126 # So we can send_command('close') ourselves without prematurely exiting
127 # the wx main loop
128 while self.busy:
129 wx.Yield()
130 sleep(0.05)
131 # Hide first (looks nicer)
132 self.Hide()
133 try:
134 with open(self.historyfilename, "wb") as historyfile:
135 for command in self.history:
136 if command:
137 historyfile.write(
138 (safe_str(command, "UTF-8") + os.linesep).encode("utf-8")
139 )
140 except OSError as exception:
141 print("Warning - couldn't write history file:", exception)
142 self.listening = False
143 # Need to use CallAfter to prevent hang under Windows if minimized
144 wx.CallAfter(self.Destroy)
145
146 def OnMove(self, event=None):
147 """Handle the movement of the console window and save its position.
148
149 Args:
150 event (wx.Event, optional): The event triggered by moving the
151 window.
152 """
153 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
154 x, y = self.GetScreenPosition()
155 setcfg("position.scripting.x", x)
156 setcfg("position.scripting.y", y)
157 if event:
158 event.Skip()
159
160 def OnSize(self, event=None):
161 """Handle the resizing of the console window and save its size.
162
163 Args:
164 event (wx.Event, optional): The event triggered by resizing the
165 window.
166 """
167 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
168 w, h = self.ClientSize
169 setcfg("size.scripting.w", w)
170 setcfg("size.scripting.h", h)
171 if event:
172 event.Skip()
173
174 def add_error_text(self, text):
175 """Add error text to the console and highlight it in red.
176
177 Args:
178 text (str): The error text to add to the console.
179 """
180 self.add_text(text)
181 end = self.console.GetLastPosition()
182 start = end - len(text)
183 self.mark_text(start, end, ERRORCOLOR)
184
185 def check_result(
186 self,
187 delayed_result,
188 get_response=False,
189 additional_commands=None,
190 colorize=True,
191 ):
192 """Check the result of a delayed operation and update the console.
193
194 Args:
195 delayed_result (delayedresult.DelayedResult): The delayed result to
196 check.
197 get_response (bool): Whether to retrieve the response from the
198 application.
199 additional_commands (list): Additional commands to process after
200 the initial command.
201 colorize (bool): Whether to colorize the result text.
202 """
203 try:
204 result = delayed_result.get()
205 except Exception as exception:
206 if hasattr(exception, "originalTraceback"):
207 self.add_text(exception.originalTraceback)
208 result = exception
209 if result:
210 if isinstance(result, socket.socket):
211 self.conn = result
212 result = lang.getstr("connection.established")
213 text = f"{result}\n"
214 self.add_text(text)
215 if colorize or isinstance(result, Exception):
216 end = self.console.GetLastPosition()
217 start = end - len(text)
218 color = ERRORCOLOR if isinstance(result, Exception) else RESPONSECOLOR
219 self.mark_text(start, end, color)
220 if get_response and not isinstance(result, Exception):
221 delayedresult.startWorker(
222 self.check_result, get_response, cargs=(False, additional_commands)
223 )
224 else:
225 self.add_text("> ")
226 if additional_commands:
227 self.add_text(additional_commands[0].rstrip("\n"))
228 if additional_commands[0].endswith("\n"):
229 self.send_command_handler(
230 additional_commands[0], additional_commands[1:]
231 )
232 return
233 self.console.SetFocus()
234 self.busy = False
235
236 def clear(self):
237 """Clear the console and reset the input prompt."""
238 self.console.Clear()
239 self.add_text("> ")
240 self.console.SetInsertionPoint(2)
241
242 def connect_handler(self, ip_port):
243 """Handle connecting to a specified IP and port.
244
245 Args:
246 ip_port (str): The IP address and port in the format "ip:port".
247 """
248 ip, port = ip_port.split(":", 1)
249 try:
250 port = int(port)
251 except ValueError:
252 self.add_error_text(lang.getstr("port.invalid", port) + "\n")
253 self.add_text("> ")
254 return
255 if self.conn:
256 self.disconnect()
257 self.add_text(lang.getstr("connecting.to", (ip, port)) + "\n")
258 self.busy = True
259 delayedresult.startWorker(
260 self.check_result,
261 self.connect,
262 cargs=(self.get_app_info, None, False),
263 wargs=(ip, port),
264 )
265
266 def copy_text_handler(self, event):
267 """Handle copying selected text from the console to the clipboard.
268
269 Args:
270 event (wx.Event): The event triggered by the copy action.
271 """
272 # Override native copy to clipboard because reading the text back
273 # from wx.TheClipboard results in wrongly encoded characters under
274 # Mac OS X
275 # TODO: The correct way to fix this would actually be in the pasting
276 # code because pasting text that was copied from other sources still
277 # has the problem with this workaround
278 clipdata = wx.TextDataObject()
279 clipdata.SetText(self.console.GetStringSelection())
280 wx.TheClipboard.Open()
281 wx.TheClipboard.SetData(clipdata)
282 wx.TheClipboard.Close()
283
284 def disconnect(self):
285 """Disconnect from the connected application, if any."""
286 if self.conn:
287 try:
288 peer = self.conn.getpeername()
289 self.conn.shutdown(socket.SHUT_RDWR)
290 except OSError as exception:
291 if exception.errno != errno.ENOTCONN:
292 self.add_text(f"{exception}\n")
293 else:
294 self.add_text(lang.getstr("disconnected.from", peer) + "\n")
295 self.conn.close()
296 del self.conn
297 self.conn = None
298 self.commands = []
299 else:
300 self.add_error_text(lang.getstr("not_connected") + "\n")
301
302 def get_app_info(self):
303 """Retrieve application information from the connected application.
304
305 Returns:
306 OSError: If there is an error retrieving the application information.
307 """
308 commands = ["setresponseformat plain", "getcommands", "getappname"]
309 try:
310 for command in commands:
311 self.conn.send_command(command)
312 response = self.conn.get_single_response()
313 if command == "getcommands":
314 self.commands = response.splitlines()
315 elif command == "getappname":
316 wx.CallAfter(
317 self.add_text,
318 lang.getstr(
319 "connected.to.at", ((response, *self.conn.getpeername()))
320 )
321 + "\n{}\n".format(lang.getstr("scripting-client.cmdhelptext")),
322 )
323 except OSError as exception:
324 return exception
325
326 def get_commands(self):
327 """Retrieve a list of commands available in the scripting client.
328
329 Returns:
330 list: A list of commands available in the scripting client.
331 """
332 return [
333 *self.get_common_commands(),
334 "clear",
335 "connect <ip>:<port>",
336 "disconnect",
337 "echo <string>",
338 "getscriptinghosts",
339 ]
340
341 def get_common_commands(self):
342 """Retrieve a list of common commands available in the scripting client.
343
344 Returns:
345 list: A list of common commands excluding those starting with "echo ".
346 """
347 cmds = SimpleTerminal.get_common_commands(self)
348 return [cmd for cmd in cmds if not cmd.startswith("echo ")]
349
350 def get_last_line(self):
351 """Retrieve the last line of text in the console and its position.
352
353 Returns:
354 tuple: A tuple containing the last line of text, its last position,
355 and the start and end column positions of the current selection.
356 """
357 linecount = self.console.GetNumberOfLines()
358 lastline = self.console.GetLineText(linecount - 1)
359 lastpos = self.console.GetLastPosition()
360 start, end = self.console.GetSelection()
361 startcol, startrow = self.console.PositionToXY(start)
362 endcol, endrow = self.console.PositionToXY(end)
363 if startcol > lastpos or endcol > lastpos:
364 # Under Mac OS X, PositionToXY seems to be broken and returns insane
365 # numbers. Calculate them ourselves. Note they will only be correct
366 # for the last line, but that's all we care about.
367 startcol = len(lastline) - (lastpos - start)
368 endcol = len(lastline) - (lastpos - end)
369 return lastline, lastpos, startcol, endcol
370
371 def get_response(self):
372 """Retrieve the response from the connected application.
373
374 Returns:
375 str: The response from the application, formatted with a leading
376 "< " and each line prefixed with "< ".
377 """
378 try:
379 return b"< " + b"\n< ".join(self.conn.get_single_response().splitlines())
380 except OSError as exception:
381 return exception
382
383 def key_handler(self, event):
384 """Custom key event handler for the console.
385
386 Args:
387 event (wx.KeyEvent): The key event triggered by the user.
388 """
389 # safe_print("KeyCode", event.KeyCode, "UnicodeKey", event.UnicodeKey,
390 # "AltDown:", event.AltDown(),
391 # "CmdDown:", event.CmdDown(),
392 # "ControlDown:", event.ControlDown(),
393 # "MetaDown:", event.MetaDown(),
394 # "ShiftDown:", event.ShiftDown(),
395 # "console.CanUndo:", self.console.CanUndo(),
396 # "console.CanRedo:", self.console.CanRedo())
397 insertionpoint = self.console.GetInsertionPoint()
398 lastline, lastpos, startcol, endcol = self.get_last_line()
399 # safe_print(insertionpoint, lastline, lastpos, startcol, endcol)
400 cmd_or_ctrl = (event.ControlDown() or event.CmdDown()) and not event.AltDown()
401 if cmd_or_ctrl and event.KeyCode == 65:
402 # A
403 self.console.SelectAll()
404 elif cmd_or_ctrl and event.KeyCode in (67, 88):
405 # C
406 self.copy_text_handler(None)
407 elif insertionpoint >= lastpos - len(lastline):
408 if cmd_or_ctrl:
409 if startcol > 1 and event.KeyCode == 86:
410 # V
411 self.paste_text_handler(None)
412 elif event.KeyCode in (89, 90):
413 # Y / Z
414 if event.KeyCode == 89 or (
415 sys.platform != "win32" and event.ShiftDown()
416 ):
417 if self.console.CanRedo():
418 self.console.Redo()
419 else:
420 wx.Bell()
421 elif self.console.CanUndo() and lastline[2:]:
422 self.console.Undo()
423 else:
424 wx.Bell()
425 elif (
426 event.KeyCode != wx.WXK_SHIFT
427 and event.UnicodeKey
428 and event.UnicodeKey != "\0"
429 ):
430 # wxPython 3 "Phoenix" defines UnicodeKey as "\x00" when
431 # control key pressed
432 wx.Bell()
433 elif event.KeyCode in (10, 13, wx.WXK_NUMPAD_ENTER):
434 # Enter, return key
435 self.send_command_handler(lastline[2:])
436 elif event.KeyCode == wx.WXK_BACK:
437 # Backspace
438 if startcol > 1 and endcol > 2:
439 if endcol > startcol:
440 # TextCtrl.WriteText would be optimal, but it doesn't
441 # do anything under wxGTK with wxPython 2.8.12
442 self.add_text("\r" + lastline[:startcol] + lastline[endcol:])
443 self.console.SetInsertionPoint(
444 lastpos - len(lastline) + startcol
445 )
446 else:
447 event.Skip()
448 else:
449 wx.Bell()
450 elif event.KeyCode in (wx.WXK_DELETE, wx.WXK_NUMPAD_DELETE):
451 if startcol > 1 and (endcol < len(lastline) or startcol < endcol):
452 if endcol > startcol:
453 # TextCtrl.WriteText would be optimal, but it doesn't
454 # do anything under wxGTK with wxPython 2.8.12
455 self.add_text("\r" + lastline[:startcol] + lastline[endcol:])
456 self.console.SetInsertionPoint(
457 lastpos - len(lastline) + startcol
458 )
459 else:
460 event.Skip()
461 else:
462 wx.Bell()
463 elif event.KeyCode in (
464 wx.WXK_DOWN,
465 wx.WXK_NUMPAD_DOWN,
466 wx.WXK_NUMPAD_PAGEDOWN,
467 wx.WXK_PAGEDOWN,
468 ):
469 if self.historypos < len(self.history) - 1:
470 self.historypos += 1
471 self.add_text("\r> " + self.history[self.historypos])
472 else:
473 wx.Bell()
474 elif event.KeyCode in (wx.WXK_END, wx.WXK_NUMPAD_END):
475 event.Skip()
476 elif event.KeyCode in (wx.WXK_HOME, wx.WXK_NUMPAD_HOME):
477 self.console.SetInsertionPoint(lastpos - len(lastline) + 2)
478 elif event.KeyCode in (wx.WXK_INSERT, wx.WXK_NUMPAD_INSERT):
479 self.overwrite = not self.overwrite
480 elif event.KeyCode in (wx.WXK_LEFT, wx.WXK_NUMPAD_LEFT):
481 if startcol > 2:
482 event.Skip()
483 else:
484 wx.Bell()
485 elif event.KeyCode in (wx.WXK_RIGHT, wx.WXK_NUMPAD_RIGHT):
486 if endcol < len(lastline):
487 event.Skip()
488 else:
489 wx.Bell()
490 elif event.KeyCode in (
491 wx.WXK_UP,
492 wx.WXK_NUMPAD_UP,
493 wx.WXK_NUMPAD_PAGEUP,
494 wx.WXK_PAGEUP,
495 ):
496 if self.historypos > 0:
497 self.historypos -= 1
498 self.add_text("\r> " + self.history[self.historypos])
499 else:
500 wx.Bell()
501 elif event.KeyCode == wx.WXK_TAB:
502 # Tab completion
503 # Can't use built-in AutoComplete feature because it only
504 # works for single-line TextCtrls
505 commonpart = lastline[2:endcol]
506 candidates = []
507 for command in sorted(set(self.commands + self.get_commands())):
508 command = command.split()[0]
509 if command.startswith(commonpart):
510 candidates.append(command)
511 findcommon = bool(candidates)
512 while findcommon and len(candidates[0]) > len(commonpart):
513 commonpart += candidates[0][len(commonpart)]
514 for candidate in candidates:
515 if candidate.startswith(commonpart):
516 continue
517 commonpart = commonpart[:-1]
518 findcommon = False
519 break
520 if len(candidates) > 1:
521 self.add_text("\n{}\n".format(" ".join(candidates)))
522 self.add_text("\r> " + commonpart + lastline[endcol:])
523 self.console.SetInsertionPoint(
524 self.console.GetLastPosition() - len(lastline[endcol:])
525 )
526 elif event.UnicodeKey or event.KeyCode in NUMPAD_KEYCODES:
527 if startcol > 1:
528 event.Skip()
529 if self.overwrite and startcol == endcol:
530 self.add_text(
531 "\r> " + lastline[2:startcol] + lastline[endcol + 1 :]
532 )
533 self.console.SetInsertionPoint(insertionpoint)
534 else:
535 wx.Bell()
536 self.console.SetInsertionPoint(lastpos)
537 elif event.KeyCode not in (
538 wx.WXK_ALT,
539 wx.WXK_COMMAND,
540 wx.WXK_CONTROL,
541 wx.WXK_SHIFT,
542 ):
543 wx.Bell()
544 self.console.SetInsertionPoint(lastpos)
545
546 def mark_text(self, start, end, color):
547 """Mark a section of text in the console with a specific color.
548
549 Args:
550 start (int): The starting position of the text to mark.
551 end (int): The ending position of the text to mark.
552 color (str): The color to use for marking the text, in hex format.
553 """
554 self.console.SetStyle(start, end, wx.TextAttr(color))
555
556 def paste_text_handler(self, event):
557 """Handle pasting text from the clipboard into the console.
558
559 Args:
560 event (wx.Event): The event triggered by the paste action.
561 """
562 do = wx.TextDataObject()
563 wx.TheClipboard.Open()
564 success = wx.TheClipboard.GetData(do)
565 wx.TheClipboard.Close()
566 if not success:
567 return
568 insertionpoint = self.console.GetInsertionPoint()
569 lastline, lastpos, startcol, endcol = self.get_last_line()
570 cliptext = universal_newlines(do.GetText())
571 lines = cliptext.replace("\n", "\n\0").split("\0")
572 command1 = lastline[2:startcol] + lines[0].rstrip("\n") + lastline[endcol:]
573 self.add_text("\r> " + command1)
574 if "\n" in cliptext:
575 self.send_command_handler(command1, lines[1:])
576 else:
577 self.console.SetInsertionPoint(insertionpoint + len(cliptext))
578
579 def process_data(self, data):
580 """Process the input data received from the connected application.
581
582 Handle commands and returns appropriate responses.
583
584 Args:
585 data (list): The input data split into command and arguments.
586
587 Returns:
588 str: "ok" if the command was processed successfully, "invalid" if
589 the command is not recognized, or a list of responses if
590 applicable.
591 """
592 if data[0] == "echo" and len(data) > 1:
593 linecount = self.console.GetNumberOfLines()
594 lastline = self.console.GetLineText(linecount - 1)
595 if lastline:
596 self.add_text("\n")
597 txt = " ".join(data[1:])
598 print(txt)
599 self.add_text(txt + "\n")
600 if lastline:
601 self.add_text("> ")
602 return "ok"
603 return "invalid"
604
605 def process_data_local(self, data):
606 """Process the input data locally.
607
608 Handle commands and return appropriate responses.
609
610 Args:
611 data (list): The input data split into command and arguments.
612
613 Returns:
614 str: "ok" if the command was processed successfully, "invalid" if
615 the command is not recognized, or a list of responses if applicable.
616 """
617 if data[0] == "clear" and len(data) == 1:
618 self.clear()
619 elif data[0] == "connect" and len(data) == 2 and len(data[1].split(":")) == 2:
620 wx.CallAfter(self.connect_handler, data[1])
621 elif data[0] == "disconnect" and len(data) == 1:
622 self.disconnect()
623 self.add_text("> ")
624 # elif data[0] == "echo" and len(data) > 1:
625 # self.add_text(" ".join(data[1:]) + "\n")
626 # return
627 elif data[0] == "getscriptinghosts" and len(data) == 1:
628 return self.get_scripting_hosts()
629 else:
630 return "invalid"
631 return "ok"
632
633 def send_command(self, command):
634 """Send a command to the connected application.
635
636 Args:
637 command (str): The command to send.
638
639 Returns:
640 None | OSError: None if successful, or an OSError exception if
641 there was an error.
642 """
643 try:
644 self.conn.send_command(command)
645 except OSError as exception:
646 return exception
647 if not wx.GetApp().IsMainLoopRunning():
648 delayedresult.AbortEvent()()
649 return None
650
651 def send_command_handler(self, command, additional_commands=None):
652 """Handle sending a command to the connected application.
653
654 Args:
655 command (str): The command to send.
656 additional_commands (list, optional): Additional commands to process
657 after the initial command. Defaults to None.
658 """
659 self.add_text("\n")
660 command = command.strip()
661 if not command:
662 self.add_text("> ")
663 return
664 data = split_command_line(command)
665 response = self.process_data_local(data)
666 if response == "ok":
667 pass
668 elif isinstance(response, list):
669 self.add_text("\n".join(response))
670 self.add_text("\n> ")
671 elif not self or not self.conn:
672 self.add_error_text(lang.getstr("not_connected") + "\n")
673 self.add_text("> ")
674 else:
675 self.busy = True
676 delayedresult.startWorker(
677 self.check_result,
678 self.send_command,
679 cargs=(self.get_response, additional_commands),
680 wargs=(command,),
681 )
682 self.history.insert(len(self.history) - 1, command)
683 if len(self.history) > 1000:
684 del self.history[0]
685 self.historypos = len(self.history) - 1
686
687
688 def main():
689 """Main function to run the wxPython application."""
690 config.initcfg("scripting-client")
691 lang.init()
692 app = BaseApp(0)
693 app.TopWindow = ScriptingClientFrame()
694 if sys.platform == "darwin":
695 app.TopWindow.init_menubar()
696 app.TopWindow.listen()
697 app.TopWindow.Show()
698 app.MainLoop()
699 writecfg(
700 module="scripting-client", options=("position.scripting", "size.scripting")
701 )
702
703
704 if __name__ == "__main__":
705 main()