-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosm2touch.py
468 lines (350 loc) · 13.5 KB
/
osm2touch.py
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
import os
import platform
import threading
import webview
import json
import platform
import sys
import time
from pathlib import Path
from osm import OSMprocess
from osm import OSMprocessStreet
from osm import OSMutils
cairosvg_available = False
try:
from cairosvg import svg2png
cairosvg_available = True
except:
print ("cairosvg not available")
rpi = False
COM_TIMEOUT = 5 #Communication timeout with device controller (Marlin)
if getattr(sys, "frozen", False):
try: # pyi_splash only available while running in pyinstaller
import pyi_splash
except ImportError:
pass
app_options = {
"lang": "en",
"osmiso639": "fr"
}
class KnownOS:
Windows = 0
Linux = 1
RPI = 2
Unknown = 3
filename = ""
root = None
detected_os = KnownOS.Unknown
def get_parameter_fname ():
paramfname = "osm2touch_parameters.json"
if detected_os == KnownOS.Linux:
home = Path.home ()
dir = Path.joinpath(home, ".osm2touch/")
print (home, dir)
if not os.path.exists(dir):
os.makedirs(dir)
fpath = Path.joinpath(dir, paramfname)
print (fpath)
return fpath
else:
return paramfname
def load_parameters():
try:
fpath = get_parameter_fname()
with open(fpath, "r", encoding="utf-8") as inf:
data = json.load(inf)
for k, v in data.items():
if k in app_options:
app_options[k] = v
except Exception as e:
print(e)
print(app_options)
class Api:
def __init__(self):
self.osmt = OSMprocess.Osmprocess()
self.osms = OSMprocessStreet.OSMprocessStreet()
self._window = None
def fullscreen(self):
"""toggle main window fullscreen"""
webview.windows[0].toggle_fullscreen()
def set_window(self, window):
self._window = window
def quit(self):
print ("quit request")
self._window.destroy()
def gcode_get_parameters(self):
"""Get parameters value"""
js = json.dumps(app_options)
print ("backend get parameters: ", js)
return js
def gcode_set_parameters(self, opt):
"""Set parameters value"""
print("parameters", opt, type(opt))
try:
for k, v in opt.items():
if k in app_options:
app_options[k] = v
except Exception as e:
print(e)
self.save_parameters()
def get_cairosvg_available(self):
return cairosvg_available
# This function creates a confirmation dialog with a given title and message
def confirm_dialog (self, title, message):
# Create a confirmation dialog with the given title and message
return window.create_confirmation_dialog(title, message)
def save_parameters(self):
"""Save parameters in local json file"""
try:
#print("data", app_options)
#print("json", json.dumps(app_options))
fpath = get_parameter_fname()
with open(fpath, "w", encoding="utf-8") as of:
json.dump(app_options, of)
except Exception as e:
print(e)
def saveas_svg_aspngfile (self, svgdata, dialogtitle, filterstring):
if cairosvg_available != True:
return
filename = ''
fname = window.create_file_dialog(
webview.SAVE_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " (*.png)", filterstring[1] + " (*.*)"),
)
if fname:
if detected_os == KnownOS.Windows:
filename = fname
else:
filename = fname[0]
else:
return
svg2png(bytestring=svgdata,write_to=filename)
def saveas_svgfile(self, data, dialogtitle, filterstring):
global filename
fname = window.create_file_dialog(
webview.SAVE_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " (*.svg)", filterstring[1] + " (*.*)"),
)
if fname:
if detected_os == KnownOS.Windows:
filename = fname
else:
filename = fname[0]
else:
return
with open(filename, "w", encoding="utf8") as inf:
inf.writelines(data)
def saveas_file(self, data, dialogtitle, filterstring):
global filename
fname = window.create_file_dialog(
webview.SAVE_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " (*.txt)", filterstring[1] + " (*.*)"),
)
if fname:
if detected_os == KnownOS.Windows:
filename = fname
else:
filename = fname[0]
else:
return
with open(filename, "w", encoding="utf8") as inf:
inf.writelines(data)
def save_file(self, data, dialogtitle, filterstring):
global filename
if filename == "":
self.saveas_file (data, dialogtitle, filterstring)
return
with open(filename, "w", encoding="utf8") as inf:
inf.writelines(data)
def download_file(self, data, dialogtitle, filterstring, filter=["(*.txt)", "(*.*)"]):
if len(filterstring) < 2 or len(filter) < 2:
print("incorrect file filter")
return
fname = window.create_file_dialog(
webview.SAVE_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " " + filter[0], filterstring[1] + " " +filter[1]),
)
if fname:
if detected_os == KnownOS.Windows:
ftowrite = fname
else:
ftowrite = fname[0]
else:
return
with open(ftowrite, "w", encoding="utf8") as inf:
inf.writelines(data)
def read_file (self, path):
js = {"data": "", "error": ""}
with open(path, "rt", encoding="utf8") as inf:
js["data"] = inf.read()
js["fname"] = os.path.basename(path)
return json.dumps(js)
def import_file(self, dialogtitle, filterstring, filter=["(*.brp)", "(*.*)"]):
js = {"data": "", "error": ""}
# check file filter
if len(filterstring) < 2 or len(filter) < 2:
js["error"] = "incorrect file filter"
return json.dumps(js)
# open common dialog
listfiles = window.create_file_dialog(
webview.OPEN_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " " + filter[0], filterstring[1] + " " +filter[1]),
)
if not listfiles:
return json.dumps(js)
if len(listfiles) != 1:
return json.dumps(js)
fname = listfiles[0]
if fname == "" or fname == None:
return json.dumps(js)
with open(fname, "rt", encoding="utf8") as inf:
js["data"] = inf.read()
js["fname"] = os.path.basename(fname)
return json.dumps(js)
def load_file(self, dialogtitle, filterstring, filter=["(*.brp)", "(*.*)"]):
global filename
js = {"data": "", "error": ""}
# check file filter
if len(filterstring) < 2 or len(filter) < 2:
js["error"] = "incorrect file filter"
return json.dumps(js)
# open common dialog
listfiles = window.create_file_dialog(
webview.OPEN_DIALOG,
allow_multiple=False,
file_types=(filterstring[0] + " " + filter[0], filterstring[1] + " " +filter[1]),
)
if not listfiles:
return json.dumps(js)
if len(listfiles) != 1:
return json.dumps(js)
if listfiles[0]:
fname = listfiles[0]
else:
return json.dumps(js)
with open(fname, "rt", encoding="utf8") as inf:
js["data"] = inf.read()
filename = fname
return json.dumps(js)
def GetISO639_country_code (self):
list = OSMutils.omsutils_get_iso639_code ()
return list
def ReadTransportData (self, city, transport_type, iso639_city_code, place_id):
ret = self.osmt.ReadTransportData (city, transport_type, iso639_city_code, place_id)
print ("ReadTransportData", ret)
return ret
def GetTransportLines (self):
#ret = self.osmt.GetTransportLineList ()
ret = self.osmt.GetTransportDataLineList ()
print ("ret", ret, type(ret))
resstr = json.dumps (ret, ensure_ascii=False)
print ("GetTransportLineList", resstr)
return resstr
def GetTransportDataSvg (self, linelist, drawstation, linestrategy, polygon):
print ("GetTransportSVG", linelist, drawstation, int(linestrategy), type(linestrategy))
svg = self.osmt.GetTransportDataSvg (linelist, drawstation, int(linestrategy), polygon)
print ("GetTransportSVG svg size", len(svg))
return svg
def GetTransportData (self, linelist, drawstation, linestrategy, polygon):
linearray = json.loads (linelist)
#print ("json decoded", linearray )
svg = self.GetTransportDataSvg (linearray, drawstation, linestrategy, polygon)
liststation = self.osmt.GetTransportDataStations (linearray)
str = json.dumps({"svg": svg, "stations": liststation}, ensure_ascii=False)
return str
def GetTransportSVGbase64 (self):
svg = self.osmt.get_svg ()
return svg
def ReadStreetMapData (self, latitude, longitude, radius, building, footpath, polygon, includeWater, cliping):
street_data = self.osms.ReadStreetMapData (latitude, longitude, radius)
print ("building", building, "footpath", footpath, "polygon", polygon)
svg = self.osms.GetStreetMapSVG (street_data, latitude, longitude, building, footpath, polygon,includeWater, cliping)
print ("ReadStreetMapData svg size", len(svg))
return svg
def get_entrypoint():
def exists(path):
print(os.path.join(os.path.dirname(__file__), path))
return os.path.exists(os.path.join(os.path.dirname(__file__), path))
if exists("./build/index.html"): # unfrozen development
return "./build/index.html"
raise Exception("No index.html found")
def delete_splash(window):
print ("delete splash **************************************************")
try:
if (platform.machine () == 'aarch64'):
time.sleep(10)
print ("################################# resize the window")
window.resize (512,512)
window.maximize()
except:
pass
try:
if getattr(sys, "frozen", True):
pyi_splash.close()
except:
pass
# print ("started", time())
entry = get_entrypoint()
if __name__ == "__main__":
app = "OpenStreetTouch"
api = Api()
debugihm = False
# redirect stdout to file for debug purpose
#f = open("output.log", 'w')
f = open(os.devnull, 'w', encoding='utf-8')
sys.stdout = f
#print(sys.argv)
dir, script = os.path.splitext(sys.argv[0])
#if len(sys.argv) > 1 and script == ".py":
if len(sys.argv) > 1:
if sys.argv[1] == "--debug":
debugihm = True
# display html start file
print("start html=", entry)
# load parameteres
load_parameters()
# start gui
if platform.machine() == 'aarch64':
detected_os = KnownOS.RPI
if platform.system() == "Windows":
detected_os = KnownOS.Windows
elif platform.system() == "Linux":
detected_os = KnownOS.Linux
if detected_os == KnownOS.RPI:
window = webview.create_window(
app, entry, js_api=api, focus=True,
)
else:
window = webview.create_window(
app, entry, js_api=api, focus=True, maximized=True,
)
api.set_window (window)
if detected_os == KnownOS.Windows:
print ("starting Windows GUI")
webview.start(delete_splash, window, http_server=False, debug=debugihm)
elif (detected_os == KnownOS.Linux):
#set QT_QPA_PLATFORM on UBUNTU
if getattr(sys, 'frozen', False):
if ('QT_QPA_PLATFORM' in os.environ):
print ("QT_QPA_PLATFORM=", os.environ['QT_QPA_PLATFORM'])
print ("starting Linux GUI QT with configured QT_QPA_PLATFORM")
webview.start(delete_splash, gui="qt", http_server=False, debug=False)
else:
print ("QT_QPA_PLATFORM=<empty>")
print ("try to resolve with XDG_SESSION_TYPE")
plugin = 'xcb'
if ('XDG_SESSION_TYPE' in os.environ):
if (os.environ['XDG_SESSION_TYPE'] == 'wayland'):
plugin = 'wayland'
# try wayland and xcb to start QT
print ("setting QT_QPA_PLATFORM to :", plugin)
os.environ['QT_QPA_PLATFORM'] = plugin
webview.start(delete_splash, window, gui="qt", http_server=False, debug=False)
else :
print ("starting GUI GTK dev environment, debug don't work in qt")
webview.start(delete_splash, window, gui="gtk", http_server=False, debug=debugihm)