Debian Codegraph @

texmf-dist/doc/latex/figput/javascript/server.py

raw
1 """
2 Use this to serve the document as it is being edited. It does several things
3 that no normal server does. It modifies the one and only HTML file before it
4 is passed to the client so that the correct document is opened. It will serve
5 files from directories outside the server directory. This way, the user can
6 keep his latex files in one place and this framework stuff in a different
7 directory. Also, the client can send .tikz files to the server and they
8 will be saved in the latex directory. Some of this (maybe all?) could be done
9 by taking an off-the-shelf server and tweaking it, but I want to keep things
10 simple, both for me and for the user. Another non-standard thing is that it
11 handles "WHERE" requests from the browswer; these are used so that that
12 documents can be loaded to open so that the are scrolled to a certain position.
13
14 To invoke this, say
15
16 python server.py directory/nameof.pdf port_num
17
18 where directory/nameof.pdf is the pdf file we want to load. If the server
19 stuff is in top_level/something/figput_guts/ and the latex stuff is in
20 top_level/elsewhere/latex/ then, after cd-ing to
21 top_level/something/figput_guts/ you need to say
22
23 python server.py ../../elsewhere/latex/thefile.pdf 8080
24
25 where the 8080 is optional, and will default to 8000. Allowing for an
26 optional port number permits the user to work on several documents at once.
27
28 BUG: It is tempting to write the entire thing in a language where
29 I can compile it to something that uses no outside resources. Asking
30 the user to install external stuff is not ideal, even if it's only
31 Python. I suspect that this could be done most easily in Rust, although
32 C/C++ would work, or most anything that compiles to an executable. It
33 just needs to be easily compiled for mac/linux/windows without any
34 contortions.
35
36 """
37
38 import sys
39 import os
40 import shutil
41 from http.server import BaseHTTPRequestHandler, HTTPServer
42
43
44 # By default, documents open at the top of the first page, but this
45 # can be used (see do_WHERE()) to change that.
46 verticalScrollPos = 0
47
48
49 # BaseHTTPRequestHandler routes requests based on the text that appears in the
50 # request. So "POST" is routed to do_POST(), "GET" is routed to doGET(), and
51 # it would be trivial to add my own request type: "WACKY" would automatically
52 # be routed to do_WACKY(). That's exactly wheat is done below for the WHERE
53 # request.
54
55 class MyServer(BaseHTTPRequestHandler):
56
57 def send_head(self):
58 # Open and return the relevant file, or return None.
59
60 # For whatever reason, the path that comes in always starts with a '/',
61 # probably to emphasize that it's relative to the "root" of the server.
62 # I break that concept.
63 #
64 # It is tempting to have the client reqest "draw_whatever" instead
65 # of "draw_whatever.js" or "draw_whatever.fjs" I could then look for
66 # both types here, saving a bit of effort on the js end. However, no
67 # normal server does this, so I would still need to maintain a version
68 # of the js that does ask for both types for use in a typical production
69 # situation.
70 path = self.path[1:]
71 f = None
72 if (self.path == '/'):
73 # Request for the one and only html file, corresponding to localhost:8000
74 path = os.path.join(path,"figput.html")
75 else:
76 if (not os.path.exists(path)):
77 # Try the latex directory. Strip off leading '/' and pre=pend latex path.
78 path = self.path[1:]
79 path = os.path.join(args.latex_dir,path)
80
81 try:
82 f = open(path, 'rb')
83 except OSError:
84 self.send_error(404, "File not found")
85 return None
86
87 # The MIME type of the file *could* be ignored since "text/html" always
88 # seems to work, but it does generate distracting error messages in the
89 # broswer.
90 ctype = ""
91 base, ext = os.path.splitext(path)
92 if (ext == ".js"):
93 ctype = "text/javascript"
94 elif (ext == ".fjs"):
95 ctype = "text/javascript"
96 elif (ext == ".html"):
97 ctype = "text/html"
98 else:
99 ctype = "text/plain"
100
101 self.send_response(200)
102 self.send_header("Content-type", ctype)
103 self.end_headers()
104 return f
105
106 def do_HEAD(self):
107 # Probably never called in my situation, although everything this
108 # does must also be done for GET, so no harm in handling it.
109 f = self.send_head()
110 if f:
111 f.close()
112
113 def do_GET(self):
114 f = self.send_head()
115 if f:
116 try:
117 if (self.path == '/'):
118 # Special case of the root html file; replace 'unknown'.
119 buf = f.read()
120 buf = buf.replace(b'unknown1',bytes(args.project_name,'utf-8') )
121 buf = buf.replace(b'unknowny',bytes(str(verticalScrollPos),'utf-8') )
122 self.wfile.write(buf)
123 else:
124 shutil.copyfileobj(f, self.wfile)
125 finally:
126 f.close()
127
128 def do_POST(self):
129 # self.path will be '/whatever.tikz'. Strip off the leading '/' and
130 # pre-pend the latex directory. This is where the content is saved.
131 dpath = self.path[1:]
132 dpath = os.path.join(args.latex_dir,dpath)
133 text_output_file = open(dpath,"w")
134
135 # Get the length of the incoming payload and read it all.
136 postLength = int(self.headers.get('content-length'))
137 testmsg = self.rfile.read(postLength)
138
139 # This is semi-pointless, but testmsg is a series of bytes, and
140 # write() below is looking for a string.
141 newmsg = testmsg.decode("ASCII",'ignore')
142
143 ignore = text_output_file.write(newmsg)
144
145 text_output_file.flush()
146 text_output_file.close()
147 self.send_response(200, "File saved")
148 self.flush_headers()
149
150 def do_WHERE(self):
151 # This is a trick to allow the browser to maintain the postion within the
152 # document when it is reloaded. It passes the current scroll position, which
153 # is then fed back to it when the document is reloaded.
154 #
155 # self.path is ignored. The client will send 'bogus' or the like.
156 # We want the contents of the message. Start off very much as for POST.
157 print("Got " +self.path);
158 postLength = int(self.headers.get('content-length'))
159 testmsg = self.rfile.read(postLength)
160 newmsg = testmsg.decode("ASCII",'ignore')
161
162 # newmsg is the postion within the document, as a string.
163 global verticalScrollPos
164 verticalScrollPos = float(newmsg)
165
166
167 def testWhetherPDF(fpath):
168
169 if (not os.path.exists(fpath)):
170 print("No such file!")
171 sys.exit(0)
172
173 ftype = os.path.splitext(os.path.basename(fpath))[-1]
174 if (ftype.lower() != ".pdf"):
175 print("Not a PDF file!")
176 sys.exit(0);
177
178
179 import argparse
180
181 parser = argparse.ArgumentParser()
182 parser.add_argument('file_path',help='specify path to pdf generated by LaTeX')
183 parser.add_argument('port', action='store', default=8000, type=int,
184 nargs='?',
185 help='specify alternate port (default: 8000)')
186 args = parser.parse_args()
187
188 testWhetherPDF(args.file_path)
189
190 # Parse out the directory leading to the PDF. It's used to search for js files.
191 # BEWARE: This is used above, as a global variable.
192 args.latex_dir = os.path.dirname(os.path.abspath(args.file_path))
193
194 # Do the same thing to get the name of the pdf file, without the '.pdf'.
195 # This is ultimately passed to the FigPut code so that it knows which file to
196 # open as the .pdf and as the .aux.
197 args.project_name = os.path.splitext(os.path.basename(args.file_path))[0]
198
199 theServer = HTTPServer(("localhost", args.port), MyServer)
200 print(f"Server started for http://localhost:{args.port}")
201
202 try:
203 theServer.serve_forever()
204 except KeyboardInterrupt:
205 pass
206
207 theServer.server_close()
208 print("Http server stopped.")
209