-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1884 lines (1635 loc) · 63.2 KB
/
Copy pathmain.py
File metadata and controls
executable file
·1884 lines (1635 loc) · 63.2 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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Basic app for celestial navigation.
Based on Kivy, and runnable on Android.
See APPDOC.md for more info.
See buildozer.spec and build.sh for deployment information.
© August Linnman, 2025, email: august@linnman.net
MIT License (see LICENSE file)
'''
# pylint: disable=C0413
# pylint: disable=C0411
import os
os.environ['SDL_ANDROID_BLOCK_ON_PAUSE'] = '0'
from multiprocessing import freeze_support
from queue import Queue, Empty
import threading
import gc
from types import NoneType
from typing import Literal
import importlib
import socket
import time
from starfix import LatLonGeodetic, SightCollection, Sight, \
get_representation, IntersectError, get_folium_load_error, show_or_display_file, \
is_windows, kill_http_server, parse_angle_string, debug_logger, DebugLogger
import json
import kivy
kivy.require('2.0.0')
from kivy.core.audio import SoundLoader
# Sound has to be loaded now directly
# This seems to be due to a Kivy bug. Delaying sound loading leads to UI crashes.
click_sound = SoundLoader.load('./sounds/mouse-click.mp3')
error_sound = SoundLoader.load('./sounds/error.mp3')
kivy.config.Config.set('graphics', 'resizable', False)
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown
from kivy.uix.checkbox import CheckBox
from kivy.uix.scrollview import ScrollView
from kivy.uix.popup import Popup
from kivy.metrics import dp, sp
from kivy.clock import Clock
from kivy.storage.jsonstore import JsonStore
from kivy.lang import Builder
from kivy.app import App
from kivy.core.clipboard import Clipboard # Import the Clipboard module
from kivy.core.window import Window
from kivy.utils import platform
from functools import partial
from plotserver import NMEAServer
# pylint: disable=W0702
try:
# Activate android libraries, needed for correct webbrowser functionality
importlib.import_module("android")
# pylint: disable=W0702
except:
pass
Window.softinput_mode = 'below_target'
# pylint: enable=C0413
# pylint: enable=C0411
def str2bool(v):
''' Simple conversion from bool to string '''
return v.lower() in ("yes", "true", "t", "1")
Window.clearcolor = (0.4, 0.4, 0.4, 1.0)
DEBUG_FONT_HANDLING = False
# TODO Review.
# Flags using for selection of different functionality.
DO_PAUSE_HANDLING = True
DO_MINIMALIST_PAUSE_HANDLING = True
DO_FULL_PAUSE_HANDLING = False
DISABLE_IP_CLOCKS = False
ADD_EXIT_BUTTON = True
DO_HTTP_SERVER_RESTART = False
DRAW_AZIMUTHS_ON_MAP = False
DebugLogger.enable (do_enable=False, to_stdout=False)
class ResourceMonitor:
"""Monitor system resources to identify leaks"""
@staticmethod
def log_resources():
"""Log current resource usage"""
# Thread count
thread_count = threading.active_count()
thread_names = [t.name for t in threading.enumerate()]
# File descriptors (Android)
try:
fd_count = len(os.listdir('/proc/self/fd'))
except:
fd_count = "N/A"
# Object count
obj_count = len(gc.get_objects())
# Clock callbacks (Kivy) - SAFE VERSION
try:
# Try different possible internal attributes
if hasattr(Clock, '_events'):
#pylint: disable=W0212
scheduled_count = len(Clock._events)
#pylint: enable=W0212
elif hasattr(Clock, 'events'):
scheduled_count = len(Clock.events)
else:
scheduled_count = "N/A"
#pylint: disable=W0718
except Exception:
#pylint: enable=W0718
scheduled_count = "N/A"
debug_logger.info("=== RESOURCE SNAPSHOT ===")
debug_logger.info(f"Threads: {thread_count} - {thread_names}")
debug_logger.info(f"File descriptors: {fd_count}")
debug_logger.info(f"Python objects: {obj_count}")
debug_logger.info(f"Scheduled events: {scheduled_count}")
debug_logger.info("========================")
# Alert if suspicious
if thread_count > 20:
debug_logger.error(f"⚠️ HIGH THREAD COUNT: {thread_count}")
if isinstance(fd_count, int) and fd_count > 100:
debug_logger.error(f"⚠️ HIGH FD COUNT: {fd_count}")
# Font scale configuration class
class FontAwareConfig:
"""Configuration class that adapts to system font scaling"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(FontAwareConfig, cls).__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
self.font_scale = self.detect_font_scale()
self.config = self.load_adaptive_config()
self._initialized = True
# Show warning if font scale is very large
if DEBUG_FONT_HANDLING:
if self.font_scale > 1.3:
Clock.schedule_once(self.show_font_scale_warning, 1.0)
def detect_font_scale(self):
"""Detect system font scale"""
if platform == 'android':
try:
# pylint: disable=E0401
# pylint: disable=C0415
from android import mActivity # type: ignore
# pylint: disable=W0611
from jnius import autoclass # type: ignore
# pylint: enable=W0611
# pylint: enable=E0401
# pylint: enable=C0415
context = mActivity
resources = context.getResources()
configuration = resources.getConfiguration()
font_scale = configuration.fontScale
print(f"Detected system font scale: {font_scale}")
return font_scale
# pylint: disable=W0718
except Exception as e:
# pylint: enable=W0718
print(f"Could not detect font scale: {e}")
return 1.0
def load_adaptive_config(self):
"""Load configuration based on font scale"""
base_config = {
'base_element_height': 35,
'base_spacing': 5,
'base_padding': 5,
'max_font_scale': 1.4, # Prevent complete UI breakdown
'font_size_reduction': 0.85 # Reduce font size for very large scales
}
# Calculate effective scale (capped to prevent UI breaking)
effective_scale = min(self.font_scale, base_config['max_font_scale'])
# Apply font size reduction for very large scales
font_reduction = 1.0
if self.font_scale > 1.25:
font_reduction = base_config['font_size_reduction']
adapted_config = {
'element_height': int(base_config['base_element_height'] * effective_scale),
'spacing': int(base_config['base_spacing'] * effective_scale),
'padding': int(base_config['base_padding'] * effective_scale),
'font_scale_factor': font_reduction,
'use_scroll': self.font_scale > 1.15, # Force scroll for large fonts
'effective_scale': effective_scale
}
return adapted_config
def get_element_height(self):
"""Get adaptive element height"""
return dp(self.config['element_height'])
def get_spacing(self):
"""Get adaptive spacing"""
return dp(self.config['spacing'])
def get_padding(self):
"""Get adaptive padding"""
return dp(self.config['padding'])
def get_font_size_factor(self):
"""Get font size reduction factor"""
return self.config['font_scale_factor']
def should_use_scroll(self):
"""Whether to force scrolling for this font scale"""
return self.config['use_scroll']
def show_font_scale_warning(self): #, dt):
"""Show warning for very large font scales"""
if hasattr(CelesteApp, 'message_popup'):
CelesteApp.message_popup(
f"[b]Large Font Scale Detected[/b]\n\n"
f"Your system font size is set to {self.font_scale:.1f}x normal size.\n"
f"The app layout has been optimized for better readability.\n\n"
f"If you experience any layout issues, consider reducing\n"
f"your system font size in Android Settings.",
"FONT_SCALE_WARNING"
)
# Initialize global font config
font_config = FontAwareConfig()
# Set default color and sizes of the form with font awareness
USE_KV = True
if USE_KV:
# Generate adaptive KV string based on font scale
def generate_adaptive_kv():
''' Generated adaptive KV string '''
# pylint: disable=W0612
element_height = font_config.get_element_height()
# pylint: enable=W0612
spacing = font_config.get_spacing()
padding = font_config.get_padding()
font_factor = font_config.get_font_size_factor()
return f"""
<FormSection@GridLayout>:
cols: 2
spacing: {spacing}
padding: {padding}
canvas.before:
Color:
rgba: 0.35, 0.35, 0.35, 1
Rectangle:
pos: self.pos
size: self.size
<MyLabel>:
size_hint_x: 0.4
halign: 'right'
valign: 'middle'
padding: dp(1)
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
<MyTextInput>:
size_hint_x: 0.8
valign: 'middle'
multiline: False
font_size: sp(14 * {font_factor})
<LimbDropDown>:
size_hint_x: 0.8
font_size: sp(14 * {font_factor})
<MyCheckbox@CheckBox>:
size_hint_x: 0.8
<SightInputSection@GridLayout>:
cols: 2
size_hint_y: None
size_hint_x: 0.8
spacing: {spacing}
padding: {padding}
canvas.before:
Color:
rgba: 0.25, 0.25, 0.25, 1
Rectangle:
pos: self.pos
size: self.size
Label:
text: '[b]Use this sight:[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyCheckbox:
id: use_checkbox
size_hint_x: 0.8
Label:
text: '[b]Name :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: object_name
size_hint_x: 0.8
multiline: False
Label:
text: '[b]Altitude (Hs) :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: altitude
size_hint_x: 0.8
multiline: False
Label:
text: '[b]Artificial Horizon :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyCheckbox:
id: artificial_horizon
size_hint_x: 0.8
Label:
text: '[b]Date :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: set_time_date
size_hint_x: 0.8
multiline: False
Label:
text: '[b]Time :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: set_time
size_hint_x: 0.8
multiline: False
Label:
text: '[b]Timezone :[/b]'
markup: True
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: set_time_tz
size_hint_x: 0.8
multiline: False
Label:
text: 'Index Error (am) :'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: index_error
size_hint_x: 0.8
multiline: False
Label:
text: 'Limb correction :'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
LimbDropDown:
id: limb_correction
size_hint_x: 0.8
Label:
text: 'Elevation (m) :'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: observer_height
size_hint_x: 0.8
multiline: False
Label:
text: 'Temperature (°C):'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: temperature
size_hint_x: 0.8
multiline: False
Label:
text: 'Gradient (°C/m):'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: temperature_gradient
size_hint_x: 0.8
multiline: False
Label:
text: 'Pressure (kPa):'
halign: 'right'
valign: 'middle'
text_size: self.width, None
size_hint_x : 0.45
font_size: sp(14 * {font_factor})
MyTextInput:
id: pressure
size_hint_x: 0.8
multiline: False
"""
Builder.load_string(generate_adaptive_kv())
FILE_NAME = None
NUM_DICT = None
# [Keep all the existing functions unchanged: get_starfixes, get_local_ip, etc.]
# SIGHT REDUCTION.
def get_starfixes(drp_pos: LatLonGeodetic) -> SightCollection:
''' Returns a list of used star fixes (SightCollection) '''
assert isinstance(NUM_DICT, dict)
Sight.set_estimated_position(drp_pos)
retval = []
assert isinstance(NUM_DICT, dict)
def str2float_or_default (val : str, default : float | int) -> float | int:
if len(val) == 0:
retval = default
else:
retval = float(val)
return retval
for i in range(3):
if str2bool(NUM_DICT["Use"+str(i+1)]):
time_string = NUM_DICT["Date"+str(i+1)]+" "+\
NUM_DICT["Time"+str(i+1)]+\
NUM_DICT["TimeZone"+str(i+1)]
assert isinstance (time_string, str)
time_string = time_string.strip().upper()
retval.append(
Sight(object_name=NUM_DICT["ObjectName"+str(i+1)],
measured_alt=NUM_DICT["Altitude"+str(i+1)],
set_time=time_string,
index_error_minutes=str2float_or_default(
NUM_DICT["IndexError"+str(i+1)],0),
limb_correction=int(
NUM_DICT["LimbCorrection"+str(i+1)]),
artificial_horizon=str2bool(
NUM_DICT["ArtificialHorizon"+str(i+1)]),
observer_height=str2float_or_default(
NUM_DICT["ObserverHeight"+str(i+1)],0),
temperature=str2float_or_default(
NUM_DICT["Temperature"+str(i+1)],10),
dt_dh=str2float_or_default(
NUM_DICT["TemperatureGradient"+str(i+1)],-0.01),
pressure=str2float_or_default(NUM_DICT["Pressure"+str(i+1)],101)
))
return SightCollection(retval)
def get_local_ip():
"""Get local IP without internet connectivity - won't hang"""
test_socket = None
try:
test_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_socket.settimeout(1.0) # ← CRITICAL FIX!
test_socket.connect(('192.168.1.1', 80))
local_ip = test_socket.getsockname()[0]
test_socket.close()
return local_ip
# pylint:disable=W0702
except:
return "127.0.0.1"
# pylint:enable=W0702
finally:
if test_socket is not None:
try:
test_socket.close()
# pylint:disable=W0702
except:
pass
# pylint:enable=W0702
COMM_QUEUE = None
KILL_QUEUE = None
def run_plotserver():
''' Running the plot server worker
This thread starts the NMEA server, listens for position updates
and also STOP commands for killing the NMEA server.
'''
# pylint: disable=W0603
global COMM_QUEUE
# pylint: enable=W0603
server = NMEAServer(host='0.0.0.0', port=10110)
server_thread = None
try:
# Start NMEA server in a separate thread
server_thread = threading.Thread(target=server.start, daemon=True)
server_thread.start()
while True:
#pylint: disable=E0601
assert isinstance (COMM_QUEUE, Queue)
#pylint: enable=E0601
try:
check_string = COMM_QUEUE.get (timeout=1.0)
except Empty:
continue
assert isinstance (check_string, str)
if check_string == "STOP":
# The plot server will now terminate
break
strs = check_string.split (";")
lat = float (strs[0])
lon = float (strs[1])
server.update_position (lat, lon)
finally:
server.stop()
if server_thread is not None:
server_thread.join (timeout=1.0)
if server_thread.is_alive ():
debug_logger.error ("Failed to stop plot server thread")
COMM_QUEUE = None
def run_killserver ():
''' Running a separate "kill" server responsible for removing the NMEA server
This is needed to avoid Androids aggressive thread management which seems
to cause hangups if the NMEA server is allowed to live for a longer time.
'''
timestamp = 0
has_waited = False
while True:
try:
# pylint: disable=W0603
global KILL_QUEUE
# pylint: enable=W0603
assert KILL_QUEUE is not None
do_wait = False
# Here we wait for the kill signal
timestamp = KILL_QUEUE.get (block=False)
# We got a kill signal, with a timestamp
if not KILL_QUEUE.empty:
pass
# There is more data on the kill queue. Ignore this post.
else:
# No more data on the kill queue. Now we should wait
do_wait = True
if do_wait:
# Calculate the real time difference, and add 20 seconds
wait_time = timestamp - time.time() + 20
if wait_time < 0:
wait_time = 0
# If we have a positive net waiting time, then waut
if wait_time > 0:
time.sleep (wait_time)
else:
pass
# We cot an overdue kill request
# Now remember we have waited
has_waited = True
except Empty:
# We have an empty kill queue. See if it is time to actually kill the plot server.
if has_waited:
# Time to kill
global COMM_QUEUE
if COMM_QUEUE is not None:
# Sending kill command
COMM_QUEUE.put ("STOP")
# Graceful wait for 1 sec
time.sleep (1)
# Clean up
COMM_QUEUE = None
KILL_QUEUE = None
# We are done
return
else:
pass
def start_plotserver ():
''' Start the plot server'''
# pylint: disable=W0603
global COMM_QUEUE, KILL_QUEUE
# pylint: enable=W0603
if COMM_QUEUE is None:
COMM_QUEUE = Queue ()
plot_process = threading.Thread (target = run_plotserver, args = (), daemon=True)
plot_process.start ()
if KILL_QUEUE is None:
KILL_QUEUE = Queue ()
kill_process = threading.Thread (target=run_killserver, args = (), daemon=True)
kill_process.start ()
try:
while True:
KILL_QUEUE.get(False)
except Empty:
pass
# KILL_QUEUE.put (20)
KILL_QUEUE.put (time.time())
def kill_plotserver ():
''' Kill the plot server'''
if COMM_QUEUE is not None:
COMM_QUEUE.put ("STOP")
def update_plot_position (lat : float, lon : float):
''' Update the plot server with new coordinates '''
if COMM_QUEUE is not None:
COMM_QUEUE.put (str(lat)+";"+str(lon))
def sight_reduction() -> \
tuple[str, bool, LatLonGeodetic | NoneType, SightCollection | Sight | NoneType]:
''' Perform a sight reduction given data entered above '''
assert isinstance(NUM_DICT, dict)
real_lat = parse_angle_string (NUM_DICT["DrpLat"])
real_lon = parse_angle_string (NUM_DICT["DrpLon"])
the_pos = LatLonGeodetic(lat=float(real_lat),
lon=float(real_lon))
intersections = None
collection = None
try:
the_limit = float(NUM_DICT["DrpQuality"]) * 1.852 # Convert from nm to km
intersections, _, _, collection, calculated_diff =\
SightCollection.get_intersections_conv(return_geodetic=True,
estimated_position=the_pos,
get_starfixes=get_starfixes,
assume_good_estimated_position=True,
limit=the_limit)
assert isinstance (intersections, LatLonGeodetic)
assert isinstance (collection, SightCollection)
repr_string = get_representation(intersections, 1)
km_per_nautical_mile = 1.852
if calculated_diff > 0:
diff_string = " ±" + str(round(calculated_diff/km_per_nautical_mile,1)) + " nm"
else:
diff_string = ""
start_plotserver ()
update_plot_position (intersections.get_lat(), intersections.get_lon())
return repr_string + diff_string, True, intersections, collection
except IntersectError as ve:
coll_object = None
if isinstance (ve.coll_object, SightCollection) or\
isinstance (ve.coll_object, Sight):
coll_object = ve.coll_object
return "Failed sight reduction. " + str (ve), False, None, coll_object
return "Failed sight reduction. " + str (ve), False, None, None
except KeyError as ve:
return "Invalid parameters." + str (ve), False, None, None
except ValueError as ve:
return str(ve), False, None, None
# Modified widget classes with font awareness
class AppButton (Button):
''' Common base class for buttons '''
def __init__(self, active : bool, **kwargs):
# Apply font scaling
if 'font_size' not in kwargs:
kwargs['font_size'] = sp(16 * font_config.get_font_size_factor())
super().__init__(**kwargs)
self.set_active (active)
def set_active (self, active : bool):
''' Toggles the active state of the button '''
if active:
self.background_color = (1.0, 0.10, 0.10, 1)
else:
self.background_color = (0.9, 0.9, 0.9, 1)
class ExecButton (AppButton):
''' This is the button starting the sight reduction '''
def __init__(self, form, **kwargs):
super().__init__(active = True, **kwargs)
self.form = form
self.text = "Perform sight reduction!"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(instance):
''' This is the button callback function '''
assert isinstance(instance, ExecButton)
the_form = instance.form
assert isinstance(the_form, InputForm)
the_form.extract_from_widgets()
sr, result, intersections, coll = sight_reduction()
if result:
# Successful sight reduction
CelesteApp.play_click_sound ()
assert isinstance (coll, SightCollection)
assert isinstance (intersections, tuple) or\
isinstance (intersections, LatLonGeodetic) or\
intersections is None
# Save collection and intersections (to be used in map presentation)
the_form.set_active_intersections(intersections, coll)
the_form.extract_from_widgets()
dump_dict(copy_to_clipboard=False)
the_form.results.text = "Your location = " + sr
CelesteApp.message_popup ("You have made a successful sight reduction!\n"
"Use the \"Show Map!\" button to see the result!",\
CelesteApp.MSG_ID_SIGHT_REDUCTION_SUCCESS)
the_form.set_position (sr)
else:
# Failed sight reduction
CelesteApp.play_error_sound ()
if coll is not None:
# Save the collection (without intersections) on error
the_form.set_active_intersections (None, coll)
CelesteApp.message_popup ("You have made a failed sight reduction!\n"
"The circles of equal altitude don't intersect properly\n"
"Use the \"Show Map!\" button for troubleshooting!",\
CelesteApp.MSG_ID_SIGHT_REDUCTION_FAILURE)
else:
CelesteApp.message_popup ("You have made a failed sight reduction!\n"
"See the message in the field above for more"+\
"information!\n",\
CelesteApp.MSG_ID_SIGHT_REDUCTION_FAILURE)
CelesteApp.reset_messages()
the_form.results.text = sr
class ShowMapButton (AppButton):
''' This button is used to show the active map '''
# shutdown_event = None # Class variable to track scheduled shutdown TODO Review
def __init__(self, form, **kwargs):
super().__init__(active = False, **kwargs)
self.form = form
self.text = "No map data (yet)"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
def callback(self, instance):
''' This is a function for showing a map '''
assert isinstance(instance, ShowMapButton)
the_form = instance.form
assert isinstance(the_form, InputForm)
i, c = the_form.get_active_intersections ()
if c is not None:
the_map = None
try:
if isinstance (c, SightCollection):
the_map = c.render_folium (i, draw_azimuths=DRAW_AZIMUTHS_ON_MAP)
elif isinstance (c, Sight):
the_map = c.render_folium_new_map ()
CelesteApp.play_click_sound()
assert the_map is not None
file_name = "./map.html"
the_map.save (file_name)
show_or_display_file (file_name, protocol="http",
kill_existing_server=DO_HTTP_SERVER_RESTART)
# pylint: disable=W0702
except:
CelesteApp.play_error_sound()
if the_map is None:
instance.text = get_folium_load_error()
else:
instance.text = "Error in map generation."
# pylint: enable=W0702
class PasteConfigButton (AppButton):
''' This button reads the JSON configuration from clipboard and repopulates all widgets '''
def __init__(self, form, **kwargs):
super().__init__(active = True, **kwargs)
self.form = form
self.text = "Paste Data"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(instance):
''' Responds to button click and repopulates the configuration '''
assert isinstance (instance, PasteConfigButton)
config_string = Clipboard.paste ()
assert isinstance (NUM_DICT, dict)
format_ok = _initialize_from_string (config_string, NUM_DICT)
if format_ok:
assert isinstance (instance.form, InputForm)
CelesteApp.play_click_sound ()
instance.form.populate_widgets ()
else:
CelesteApp.play_error_sound ()
#if DebugLogger.enable_debug:
# appx = App.get_running_app ()
# assert isinstance (appx, CelesteApp)
# appx.stress_test_lifecycle ()
class CopyPosButton (AppButton):
''' This button copies the last position (latlon) to the clipboard'''
def __init__(self, form, **kwargs):
super().__init__(active = False, **kwargs)
self.form = form
self.text = "Copy Position"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(instance):
''' Responds to button click and copies position to clipboard '''
assert isinstance(instance, CopyPosButton)
the_form = instance.form
assert isinstance (the_form, InputForm)
p = the_form.get_position ()
if p is not None:
CelesteApp.play_click_sound ()
Clipboard.copy (p)
class CopyConfigButton (AppButton):
""" This button copies the config to the clipboard """
def __init__(self, form, **kwargs):
super().__init__(active = True, **kwargs)
self.form = form
self.text = "Copy Data"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(instance):
''' Responds to button click and copies config to clipboard '''
assert isinstance (instance, CopyConfigButton)
dump_dict(copy_to_clipboard=True)
CelesteApp.play_click_sound ()
class OnlineHelpButton (AppButton):
''' A button for showing online help '''
def __init__(self, **kwargs):
super().__init__(active = True, **kwargs)
self.text = "Show Help!"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(_):
''' This is a function for showing online help '''
CelesteApp.play_click_sound ()
file_name = "./APPDOC.html"
show_or_display_file (file_name, protocol="http",
kill_existing_server=DO_HTTP_SERVER_RESTART)
class ConfirmExitPopup(Popup):
"""Confirmation dialog for app exit"""
def __init__(self, **kwargs):
# Apply font scaling
if 'title_size' not in kwargs:
kwargs['title_size'] = sp(16 * font_config.get_font_size_factor())
super().__init__(
title='Confirm Exit',
size_hint=(0.8, 0.4),
auto_dismiss=False,
**kwargs
)
# Create layout
layout = BoxLayout(
orientation='vertical',
padding=font_config.get_padding(),
spacing=font_config.get_spacing()
)
# Message label
message = Label(
text='Are you sure you want to exit?',
size_hint_y=0.6,
font_size=sp(14 * font_config.get_font_size_factor())
)
layout.add_widget(message)
# Button container
button_box = BoxLayout(
orientation='horizontal',
size_hint_y=0.4,
spacing=font_config.get_spacing()
)
# Yes button
yes_btn = Button(
text='Yes',
font_size=sp(14 * font_config.get_font_size_factor()),
background_color=(1.0, 0.3, 0.3, 1)
)
#pylint: disable=E1101
yes_btn.bind(on_press=self.confirm_exit)
#pylint: enable=E1101
# No button
no_btn = Button(
text='No',
font_size=sp(14 * font_config.get_font_size_factor()),
background_color=(0.3, 1.0, 0.3, 1)
)
#pylint: disable=E1101
no_btn.bind(on_press=self.dismiss)
#pylint: enable=E1101
button_box.add_widget(yes_btn)
button_box.add_widget(no_btn)
layout.add_widget(button_box)
self.content = layout
def confirm_exit(self, _):
"""Actually exit the app"""
debug_logger.info("Exit confirmed by user")
self.dismiss()
# Kill services
#debug_logger.info("Stopping HTTP server")
#kill_http_server()
debug_logger.info("Forcing exit")
os._exit(0)
class ExitButton (AppButton):
''' Button for exiting the app '''
def __init__(self, **kwargs):
super().__init__(active = True, **kwargs)
self.text = "Exit"
# pylint: disable=E1101
self.bind(on_press=self.callback)
# pylint: enable=E1101
@staticmethod
def callback(_):
''' Called when pressing the exit button '''
debug_logger.info("Exit button pressed - showing confirmation")
CelesteApp.play_click_sound()
popup = ConfirmExitPopup()
popup.open()
class FormRow (BoxLayout):