Debian Codegraph @

DisplayCAL/webwin.py

raw
1 """Re-implementation of Argyll's webwin in pure python."""
2
3 import http.server
4 from urllib.parse import unquote
5
6 from DisplayCAL.meta import NAME as APPNAME
7 from DisplayCAL.meta import VERSION_STRING as APPVERSION
8
9 WEBDISP_HTML = rf"""<!DOCTYPE html>
10 <html>
11 <head>
12 <title>{APPNAME} Web Display</title>
13 <script src="webdisp.js"></script>
14 <style>
15 html, body {{
16 background: #000;
17 margin: 0;
18 padding: 0;
19 overflow: hidden;
20 height: 100%%;
21 }}
22 #pattern {{
23 position: absolute;
24 left: 45%%;
25 top: 45%%;
26 width: 10%%;
27 height: 10%%;
28 }}
29 </style>
30 </head>
31 <body>
32 <div id="pattern"></div>
33 </body>
34 </html>
35 """
36
37 WEBDISP_JS = r"""if (typeof XMLHttpRequest == "undefined") {
38 XMLHttpRequest = function () {
39 try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
40 catch (e) {}
41 try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
42 catch (e) {}
43 try { return new ActiveXObject("Microsoft.XMLHTTP"); }
44 catch (e) {}
45 throw new Error("This browser does not support XMLHttpRequest.");
46 };
47 }
48
49 var cpat = ["#000"];
50 var oXHR;
51 var pat;
52 var retryDelayMs = 100;
53
54 function scheduleNextRequest(delayMs) {
55 setTimeout(XHR_request, delayMs);
56 }
57
58 function XHR_request() {
59 try {
60 oXHR.open(
61 "GET",
62 "/ajax/messages?"
63 + encodeURIComponent(cpat.join("|") + "|" + Math.random()),
64 true
65 );
66 oXHR.onreadystatechange = XHR_response;
67 oXHR.send();
68 } catch (e) {
69 scheduleNextRequest(retryDelayMs);
70 }
71 }
72
73 function XHR_response() {
74 if (oXHR.readyState != 4)
75 return;
76
77 if (oXHR.status != 200) {
78 scheduleNextRequest(retryDelayMs);
79 return;
80 }
81 var rt = oXHR.responseText;
82 if (rt.charAt(0) == '\r' && rt.charAt(1) == '\n')
83 rt = rt.slice(2);
84 rt = rt.split("|")
85 if (rt[0] && cpat != rt) {
86 cpat = rt;
87 pat.style.background = rt[1] ? rt[0] : "transparent"; // Older dispwin compat
88 document.body.style.background = (rt[1] || rt[0]); // Older dispwin compat
89 if (rt.length == 6) {
90 pat.style.left = (rt[2] * 100) + "%";
91 pat.style.top = (rt[3] * 100) + "%";
92 pat.style.width = (rt[4] * 100) + "%";
93 pat.style.height = (rt[5] * 100) + "%";
94 }
95 }
96 scheduleNextRequest(50);
97 }
98
99 window.onload = function() {
100 pat = document.getElementById("pattern");
101
102 oXHR = new XMLHttpRequest();
103 XHR_request();
104 };
105 """
106
107
108 class WebWinHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
109 """Simple HTTP request handler with GET and HEAD commands."""
110
111 server_version = f"{APPNAME}-WebWinHTTP/{APPVERSION}"
112
113 def do_GET(self):
114 """Serve a GET request."""
115 s = self.send_head()
116 if s:
117 self.wfile.write(s.encode())
118
119 def do_HEAD(self):
120 """Serve a HEAD request."""
121 self.send_head()
122
123 def log_message(self, format, *args): # noqa: A002
124 """Override to disable logging.
125
126 Args:
127 format (str): The format string for the log message.
128 *args: Arguments to be formatted into the log message.
129 """
130
131 def send_head(self):
132 """Common code for GET and HEAD commands.
133
134 This sends the response code and MIME headers.
135
136 Return value is either a string (which has to be written
137 to the outputfile by the caller unless the command was HEAD), or
138 None, in which case the caller has nothing further to do.
139
140 """
141 if self.path == "/":
142 s = WEBDISP_HTML
143 ctype = "text/html; charset=UTF-8"
144 elif self.path == "/webdisp.js":
145 s = WEBDISP_JS
146 ctype = "application/javascript"
147 elif self.path.startswith("/ajax/messages?"):
148 curpat = "|".join(unquote(self.path.split("?").pop()).split("|")[:6])
149 s = self.server.patterngenerator.wait_for_pattern_change(curpat)
150 ctype = "text/plain; charset=UTF-8"
151 else:
152 self.send_error(404)
153 return None
154 if self.server.patterngenerator.listening:
155 try:
156 self.send_response(200)
157 self.send_header("Cache-Control", "no-cache")
158 self.send_header("Content-Type", ctype)
159 self.end_headers()
160 return s
161 except BaseException:
162 pass
163 return None