forked from adywizard/car-locator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1468 lines (1198 loc) · 47 KB
/
main.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
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
"""Find my car"""
__author__ = 'Ady Wizard'
from functools import partial
from random import choice
from datetime import datetime, date
import os
import glob
import json
from kivymd.color_definitions import colors
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.app import MDApp
from kivymd.uix.card import MDCardSwipe
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import MDList, OneLineIconListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.button import MDFlatButton
from kivymd.uix.list import OneLineAvatarIconListItem
from kivy.properties import StringProperty, ListProperty,\
ObjectProperty, NumericProperty, ColorProperty
from kivy.uix.screenmanager import (
Screen, SlideTransition,
RiseInTransition # ,FallOutTransition
)
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.utils import platform
from kivy.core.window import Window
from kivy.clock import mainthread
from plyer import gps
from kivy_garden.mapview import MapMarker
from kivy.logger import Logger
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.graphics import (
RenderContext, Fbo, Color,
ClearColor, ClearBuffers, Rectangle
)
from kivy.uix.floatlayout import FloatLayout
from kivy.metrics import dp
from time_picker.picker import CustomTimePicker
from constants.texts import first_warn_text, background_text
from constants.colors import BUBBLE_COLORS
from constants.urls import URL, MAIL
from opengl_shader.bubbleshader import shader_watter_bubble
from kivy_lang.kivy_lang import KV
if platform == 'android':
from jnius import autoclass, cast, JavaException
from android.runnable import run_on_ui_thread
from android import activity
from android.permissions import request_permissions, Permission
from blue.blue import BroadcastReceiver
from android_notification.notification import notify, cancel_notification
from alarm_manager.alarm import ParkAlarmManager
from android_toast.toast import android_toast
from android_vibrator.vibrator import AndroidVibrator
Intent = autoclass('android.content.Intent')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
Uri = autoclass('android.net.Uri')
Context = autoclass('android.content.Context')
String = autoclass('java.lang.String')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
mActivity = PythonActivity.mActivity
WindowManager = autoclass('android.view.WindowManager')
AColor = autoclass("android.graphics.Color")
LayoutParams = autoclass('android.view.WindowManager$LayoutParams')
Settings = autoclass('android.provider.Settings')
LocationManager = autoclass('android.location.LocationManager')
Calendar = autoclass('java.util.Calendar')
SimpleDateFormat = autoclass('java.text.SimpleDateFormat')
View = autoclass('android.view.View')
String = autoclass('java.lang.String')
Boolean = autoclass('java.lang.Boolean')
ActivityCompat = autoclass('androidx.core.app.ActivityCompat')
Manifest = autoclass('android.Manifest$permission')
PackageManager = autoclass('android.content.pm.PackageManager')
ContextCompat = autoclass('androidx.core.content.ContextCompat')
NotificationManager = autoclass('android.app.NotificationManager')
BuildVersion = autoclass('android.os.Build$VERSION')
BuildVersion_CODES = autoclass('android.os.Build$VERSION_CODES')
PowerManager = autoclass('android.os.PowerManager')
Configuration = autoclass('android.content.res.Configuration')
else:
import webbrowser
def run_on_ui_thread(*args, **kwargs):
return
class WarnDialogContent(BoxLayout):
txt = ObjectProperty()
class ContentTimeError(FloatLayout):
pass
class ContentLocationReady(FloatLayout):
pass
class LayoutWidget(FloatLayout):
angle = NumericProperty()
color = ColorProperty([0, 0, 0, 0])
x_scale = NumericProperty(1)
y_scale = NumericProperty(1)
z_scale = NumericProperty(1)
class SemiCircle(FloatLayout):
color = ColorProperty([1, 1, 1, 1])
angle_start = NumericProperty()
angle_end = NumericProperty()
class ShaderWidget(FloatLayout):
mouse_pos = ListProperty([100, 100])
fs = StringProperty(None)
texture = ObjectProperty(None)
def __init__(self, **kwargs):
Window.bind(mouse_pos=self.get_mouse_pos)
self.canvas = RenderContext(use_parent_projection=True,
use_parent_modelview=True,
use_parent_frag_modelview=True)
with self.canvas:
self.fbo = Fbo(size=self.size)
self.fbo_color = Color(1, 1, 1, 1)
self.fbo_rect = Rectangle(size=self.size, pos=self.pos)
with self.fbo:
ClearColor(0, 0, 0, 0)
ClearBuffers()
super(ShaderWidget, self).__init__(**kwargs)
self.fs = shader_watter_bubble
Clock.schedule_interval(self.update_glsl, 0)
def get_mouse_pos(self, w, pos):
self.canvas['mouse'] = pos
self.mouse_pos = pos
def update_glsl(self, *largs):
self.canvas['time'] = Clock.get_boottime()
self.canvas['resolution'] = [float(v) for v in self.size]
def on_fs(self, instance, value):
shader = self.canvas.shader
old_value = shader.fs
shader.fs = value
if not shader.success:
shader.fs = old_value
raise Exception('compilation failed')
def add_widget(self, *args, **kwargs):
c = self.canvas
self.canvas = self.fbo
super(ShaderWidget, self).add_widget(*args, **kwargs)
self.canvas = c
def remove_widget(self, *args, **kwargs):
c = self.canvas
self.canvas = self.fbo
super(ShaderWidget, self).remove_widget(*args, **kwargs)
self.canvas = c
def on_size(self, instance, value):
self.fbo.size = value
self.texture = self.fbo.texture
self.fbo_rect.size = value
def on_pos(self, instance, value):
self.fbo_rect.pos = value
def on_texture(self, instance, value):
self.fbo_rect.texture = value
class PltContent(MDFloatLayout):
pass
class ItemSettings(MDFloatLayout):
icon = StringProperty()
text_color = StringProperty('Primary')
color = ListProperty([1, 1, 1, 1])
text = StringProperty()
class ChronologyScreen(Screen):
ellipse_top = ListProperty([0, 0])
ellipse_bottom = ListProperty([0, 0])
ellipse_middle_bottom = ListProperty([0, 0])
ellipse_middle_top = ListProperty([0, 0])
def on_enter(self):
self.animate()
def animate(self):
a = Animation(
ellipse_top=[dp(300), dp(300)], d=.4, t='in_out_elastic'
)
a += Animation(
ellipse_bottom=[dp(250), dp(250)], d=.4, t='in_out_elastic'
)
a += Animation(
ellipse_middle_top=[dp(25), dp(25)], d=.4, t='in_out_elastic'
)
a += Animation(
ellipse_middle_bottom=[dp(50), dp(50)], d=.4, t='in_out_elastic'
)
a.start(self)
class SettingsScreen(Screen):
def jump(self):
app.root.ids.sm.transition.direction = 'up'
app.root.ids.sm.current = 'scr 1'
class ColorMark(MapMarker):
pass
class RootWidget(Screen):
mapview = ObjectProperty()
alpha = ListProperty([1])
class SwipeToDeleteItem(MDCardSwipe):
text = StringProperty()
secondary_text = StringProperty()
tertiary_text = StringProperty()
def set_location(self, location):
loc = location.split(' ')
lo = float(loc[1])
la = float(loc[3])
app.loca.clear()
app.loca = [lo, la]
app.root.ids.mapview.center_on(lo, la)
app.add_mark(lo, la)
app.root.ids.sm.current = 'scr 2'
class ItemConfirm(OneLineAvatarIconListItem):
map_type = StringProperty()
def set_icon(self, instance_check):
instance_check.active = True
check_list = instance_check.get_widgets(instance_check.group)
for check in check_list:
if check != instance_check:
check.active = False
class ItemColor(OneLineAvatarIconListItem):
def set_icon(self, instance_check):
instance_check.active = True
check_list = instance_check.get_widgets(instance_check.group)
for check in check_list:
if check != instance_check:
check.active = False
class Cancel(MDFlatButton):
pass
class Accept(MDFlatButton):
pass
class Ok(MDFlatButton):
pass
class ContentNavigationDrawer(MDBoxLayout):
pass
class ItemDrawer(OneLineIconListItem):
icon = StringProperty()
def set_name(self):
if self.text == 'Drawer to right':
self.text = 'Drawer to left'
elif self.text == 'Drawer to left':
self.text = 'Drawer to right'
class DrawerList(ThemableBehavior, MDList):
type_way = ''
def set_color_item(self, instance_item):
if instance_item == 'theme-light-dark':
if app.theme_cls.theme_style == 'Dark':
app.root.alpha = [1]
app.theme_cls.theme_style = 'Light'
app.root.ids.r.color = [1, 1, 1, 1]
elif app.theme_cls.theme_style == 'Light':
app.root.alpha = [1]
app.theme_cls.theme_style = 'Dark'
app.root.ids.content_drawer.md_bg_color = [1, 1, 1, 1]
app.root.ids.r.color = [0, 0, 0, 1]
app.save_theme()
class CarPos(MDApp):
gps_location = StringProperty()
gps_status = StringProperty()
loca = ListProperty()
permit = False
mark = None
dialog = None
map_dialog = None
plate_dialog = None
a_11_background_permit = None
automatic_ready_dialog = None
time_picker = None
time_dialog_warn = None
lat_lon = []
accur = []
saved = False
gps_is_on = False
theme_dialog = None
mark_img = StringProperty()
car_image = StringProperty()
anchor = StringProperty('left')
w = None
h = None
plate = StringProperty('')
green = False
w_count = 0
upper_left = False
lower_right = False
transition = None
br = None
paired_car = ""
is_car_paired = False
is_first_time = None
is_removing = False
is_gathering = False
alarm_time = ObjectProperty(allownone=True)
vibrator = None
activity_alarm = False
@run_on_ui_thread
def regain_focus(self):
mActivity.onWindowFocusChanged(False)
mActivity.onWindowFocusChanged(True)
# FIX for SDLActivity window loses focus
def button_animation(self, *_):
if platform != 'android':
Clock.schedule_once(self.button_animation_cancel, 5)
ang = 8 if self.root.ids.sl.angle == -2 else -2
a = Animation(angle=ang, d=.7, t='out_bounce')
a.bind(on_complete=self.button_animation)
a.start(self.root.ids.sl)
def button_animation_cancel(self, *_):
Animation.cancel_all(self.root.ids.sl)
self.root.ids.sl.disabled = False
self.root.ids.sl.angle == -2
def on_alarm_time(self, *_):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
time = datetime.strptime(current_time, '%H:%M:%S').time()
t = datetime.combine(
date.today(), self.alarm_time
) - datetime.combine(date.today(), time)
if t.seconds < 60 or t.seconds > 43200:
self.open_animate_dialog(self.time_dialog_warn, None)
return
alarm = ParkAlarmManager()
alarm.start(t.seconds)
if not self.activity_alarm:
activity.bind(on_new_intent=self.on_alarm_intent)
self.activity_alarm = True
def center_mapview(self, mapview):
mapview.center_on(app.loca[0], app.loca[1]) \
if app.loca[0] != 0 and app.loca[1] != 0 \
else mapview.center_on(52.5065133, 13.1445545)
def on_alarm_intent(self, intent):
start_alarm = intent.getBooleanExtra("startAlarm", False)
if start_alarm:
self.show_alarm_screen(None)
if self.activity_alarm:
activity.unbind(on_new_intent=self.on_alarm_intent)
self.activity_alarm = False
def on_new_intent(self, intent):
cancel = intent.getStringExtra("cancel")
if cancel == "cancel":
self.stop_service(0, 0)
self.start(1000, 0)
return
got_location = intent.getStringExtra("gotLocation")
lat = intent.getStringExtra("lat")
lon = intent.getStringExtra("lon")
start = intent.getStringExtra("start")
if start == "start":
self.start_service(self.paired_car)
self.turn_on_gps('start')
cancel_notification()
return
if lat or lon:
lat = float(lat)
lon = float(lon)
if got_location == "true":
self.stop_service(lat, lon)
def on_receive(self, context, intent):
name = ''
action = intent.getAction()
parcable = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
device = cast(BluetoothDevice, parcable)
name = device.getName()
if action == BluetoothDevice.ACTION_ACL_CONNECTED:
if name == self.paired_car and not self.is_car_paired:
# android_toast(f'connected to {name} Starting service', True)
activity.bind(on_new_intent=self.on_new_intent)
# self.start_service(name)
notify(
context,
'CAR_LOCATOR_HEADS_UP',
'CAR CONNECTED PRESS TO START LISTEN',
'Location service',
'Car locator',
'Car locator service',
flag='update',
n_type='head',
autocancel=False
)
def unregister_broadcast_receiver(self):
try:
if self.br and platform == 'android':
self.br.stop()
self.br = None
except JavaException as e:
Logger.error(str(e))
@mainthread
def stop_service(self, lat, lon):
mActivity.stop_service()
activity.unbind(on_new_intent=self.on_new_intent)
if lat == 0 and lon == 0:
return
now = self.get_datetime()
with open('locations/loc.json', 'r+') as f:
loc = json.load(f)
loc["datetime"].append(now)
number_of_locations = len(loc['loc'])
if number_of_locations >= 20:
loc['loc'].pop(0)
loc['loc'].append([lat, lon])
f.seek(0)
json.dump(loc, f)
self.root.ids.md_list.add_widget(
SwipeToDeleteItem(
text="Automatic Location",
secondary_text=now,
tertiary_text=f"longitude {lat} latitude {lon}"
)
)
self.open_animate_dialog(self.automatic_ready_dialog, None)
@mainthread
def start_service(self, device):
mActivity.start_service(
'waiting for disconnection',
'location service',
device
)
def register_broadcats_receiver(self):
if not self.br and platform == 'android':
''' 'SCAN_RESULTS_AVAILABLE_ACTION',
'ACTION_STATE_CHANGED',
'ACTION_ACL_CONNECTED',
'ACTION_ACL_DISCONNECTED',
'ACTION_BOND_STATE_CHANGED',
'ACTION_ACL_DISCONNECT_REQUESTED' '''
self.br = BroadcastReceiver(
self.on_receive, actions=[
'ACTION_ACL_CONNECTED',
'ACTION_ACL_DISCONNECTED'
])
self.br.start()
def first_start(self, *_):
self.root.ids.sm.transition = RiseInTransition()
# FallOutTransition()\
# if self.theme_cls.theme_style == 'Dark' else RiseInTransition()
self.root.ids.sm.current = 'scr 1'
self.root.ids.sm.transition = SlideTransition()
self.root.ids.sm.transition.direction = 'up'
def get_background_permission_option_label(self):
'''this is yet to be implemented with newer API'''
PackageManager.getBackgroundPermissionOptionLabel()
def check_background(self, *_):
if self.permit and BuildVersion.SDK_INT >= 29:
if ContextCompat.checkSelfPermission(
mActivity.getApplicationContext(),
Manifest.ACCESS_BACKGROUND_LOCATION
) == PackageManager.PERMISSION_GRANTED:
return True
if ContextCompat.checkSelfPermission(
mActivity.getApplicationContext(),
Manifest.ACCESS_BACKGROUND_LOCATION
) != PackageManager.PERMISSION_GRANTED:
ActivityCompat.requestPermissions(
mActivity, [Manifest.ACCESS_BACKGROUND_LOCATION], 1)
if ContextCompat.checkSelfPermission(
mActivity.getApplicationContext(),
Manifest.ACCESS_BACKGROUND_LOCATION
) == PackageManager.PERMISSION_DENIED:
if ActivityCompat.shouldShowRequestPermissionRationale(
mActivity,
Manifest.ACCESS_BACKGROUND_LOCATION
):
Clock.schedule_once(
partial(
self.open_animate_dialog,
self.a_11_background_permit
), 0)
return True
def explain_need_for_backgraund(self, *_):
if self.is_firs_time and platform == 'android':
Clock.schedule_once(partial(
self.open_animate_dialog, self.explain_dialog), 0)
def request_android_permissions(self):
def callback(permissions, results):
if all([res for res in results]):
self.permit = True
else:
android_toast("Permessions denied", True)
self.permit = False
android_toast("This app can't work without GPS", True)
return self.permit
request_permissions([Permission.ACCESS_COARSE_LOCATION,
Permission.ACCESS_FINE_LOCATION], callback)
def build(self):
Window.bind(on_keyboard=self.back_key_handler)
Builder.load_string(KV)
self.root = RootWidget()
def set_plate_number(self):
if self.plate_dialog.content_cls.ids.txt_field.text:
self.plate = self.plate_dialog.content_cls.ids.txt_field.text
# Clock.schedule_once(self.save_theme, .05)
def handle_screens(self):
if self.root.ids.sm.current == 'scr 2':
self.root.ids.sm.current = 'scr 1'
elif self.root.ids.sm.current == 'scr 3'\
or self.root.ids.sm.current == 'scr 4':
self.root.ids.sm.current = 'scr 1'
elif self.root.ids.sm.current == 'blue':
self.root.ids.sm.current = 'scr 1'
elif self.root.ids.sm.current == 'scr 1' and platform == 'android':
mActivity.moveTaskToBack(True)
self.on_pause()
self.stop()
def back_key_handler(self, window, keycode1, keycode2, text, modifiers):
if keycode1 in [27, 1001]:
self.handle_screens()
return True
def add_mark(self, lat, lon):
if not self.mark:
self.mark = ColorMark(lat=lat, lon=lon)
self.root.mapview.add_widget(self.mark)
else:
self.mark.lat = lat
self.mark.lon = lon
def start(self, minTime, minDistance):
if platform == 'android' and self.permit and not self.is_gathering:
self.is_gathering = True
self.turn_on_gps('start')
gps.start(minTime, minDistance)
self.show_banner()
elif platform == 'android' and not self.permit:
self.request_android_permissions()
def gps_stop(self):
if platform == 'android':
gps.stop()
def open_gps_settings(self, *_):
self.turn_on_gps('start')
def is_location_enabled(self, *args):
if platform != 'android':
return
context = cast(
'android.content.Context',
mActivity.getApplicationContext())
locationManager = cast(
'android.location.LocationManager',
context.getSystemService(Context.LOCATION_SERVICE))
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
@mainthread
def turn_on_gps(self, caller=''):
if platform == 'android':
if self.is_location_enabled():
if not caller:
android_toast('GPS already on', True)
else:
Clock.schedule_once(
partial(self.open_animate_dialog, self.dialog), .3)
Clock.schedule_once(self.safety_check, 15)
@mainthread
def enable(self, _):
gpsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
mActivity.startActivity(gpsIntent)
def get_datetime(self):
cal = Calendar.getInstance()
y, m, d, h, mi = (
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE)
)
if h < 10:
h = f"0{h}"
if mi < 10:
mi = f"0{mi}"
if d < 10:
d = f"0{d}"
if m < 10:
m = f"0{m}"
now = f"{d}/{m}/{y} {h}:{mi}"
return now
def clear_history(self):
now = self.get_datetime()
loc = {'loc': [[0, 0]], 'datetime': [now]}
with open('locations/loc.json', 'w') as f:
json.dump(loc, f)
self.loca = [0, 0]
self.remove_all_items()
def safety_check(self, *_):
if not self.is_location_enabled():
self.saved = False
self.is_gathering = False
self.hide_banner()
Animation.cancel_all(self.root.ids.sl)
self.root.ids.sl.disabled = False
self.root.ids.sl.angle == -2
return
def save_current_loc(self, *args):
if not self.is_location_enabled():
self.saved = False
self.is_gathering = False
Animation.cancel_all(self.root.ids.sl)
self.root.ids.sl.disabled = False
self.root.ids.sl.angle == -2
return
idx = self.accur.index(min(self.accur))
self.loca = self.lat_lon[idx]
now = self.get_datetime()
number_of_locations = 0
with open('locations/loc.json', 'r+') as f:
loc = json.load(f)
loc["datetime"].append(now)
number_of_locations = len(loc['loc'])
if number_of_locations < 20:
loc['loc'].append(self.loca)
else:
loc['loc'].pop(0)
loc['loc'].append(self.loca)
f.seek(0)
json.dump(loc, f)
if number_of_locations >= 20:
w = self.root.ids.md_list.children[0]
self.root.ids.md_list.remove_widget(w)
t_text = f"longitude {self.loca[0]} latitude {self.loca[1]}"
self.root.ids.md_list.add_widget(
SwipeToDeleteItem(
text="Location",
secondary_text=now,
tertiary_text=t_text
)
)
Clock.schedule_once(self.allow_scanning, 2.5)
def allow_scanning(self, _):
self.saved = False
self.accur.clear()
self.lat_lon.clear()
Animation.cancel_all(self.root.ids.sl)
self.root.ids.sl.disabled = False
self.root.ids.sl.angle == -2
def show_banner(self):
self.root.ids.spinner.active = True
self.root.ids.banner.opacity = 1
self.root.ids.b_lbl.opacity = 1
a = Animation(
y=(
self.root.height
- self.root.ids.toolbar.height
- self.root.ids.banner.height
),
d=.25, t='in_out_back'
)
a.start(self.root.ids.banner)
def hide_banner(self):
if self.root.ids.banner.y == self.root.height:
return
a = Animation(y=self.root.height, d=.5, t='out_back')
a.bind(on_complete=self.stop_and_save)
a.start(self.root.ids.banner)
@mainthread
def on_location(self, **kwargs):
loc = []
if len(self.lat_lon) <= 5:
for k, v in kwargs.items():
if k == 'lat' or k == 'lon':
loc.append(v)
elif k == 'accuracy':
self.accur.append(v)
self.lat_lon.append(loc)
else:
self.hide_banner()
def stop_and_save(self, *_):
self.root.ids.spinner.active = False
self.is_gathering = False
self.root.ids.b_lbl.opacity = 0
self.root.ids.banner.opacity = 0
self.gps_stop()
if not self.saved and self.is_location_enabled():
android_toast("Current location saved", True)
self.saved = True
Clock.schedule_once(self.save_current_loc, 0)
# self.save_current_loc()
def remove_item(self, instance):
self.root.ids.md_list.remove_widget(instance)
def animate_remove_locations(self, *args):
if args:
self.root.ids.md_list.remove_widget(args[1])
if self.root.ids.md_list.children:
a = Animation(
x=-self.root.width, opacity=.2, d=.45, t='in_elastic'
)
a.bind(on_complete=self.animate_remove_locations)
a.start(
self.root.ids.md_list.children[0]
)
else:
self.is_removing = False
self.root.ids.sv._trigger_update_from_scroll()
def remove_all_items(self):
if not self.is_removing:
self.is_removing = True
if self.root.ids.md_list.children:
self.animate_remove_locations()
# self.root.ids.md_list.clear_widgets()
@mainthread
def on_status(self, stype, status):
self.gps_status = f'type={stype}\n{status}'
@run_on_ui_thread
def clear_statusbar(self):
window = mActivity.getWindow()
window.setFlags(
LayoutParams.FLAG_LAYOUT_NO_LIMITS,
LayoutParams.FLAG_LAYOUT_NO_LIMITS)
def normal_statusbar(self):
self.set_decorations()
@run_on_ui_thread
def statusbar(self, color_s, color_n):
window = mActivity.getWindow()
window.clearFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS)
window.clearFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.setStatusBarColor(AColor.parseColor(color_s))
window.setNavigationBarColor(AColor.parseColor(color_n))
if self.green:
window.getDecorView().setSystemUiVisibility(
LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR |
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
else:
window.getDecorView().setSystemUiVisibility(0)
@mainthread
def show_alarm_screen(self, dt):
self.root.ids.sm.current = 'alarm_screen'
self.vibrator = AndroidVibrator()
self.vibrator.vibrate()
def get_intent(self):
if platform != 'android':
return
intent = mActivity.getIntent()
start = intent.getBooleanExtra("startAlarm", False)
if start:
Clock.schedule_once(self.show_alarm_screen, 2)
def is_dark_theme_on(self):
return (
mActivity.getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK
) == Configuration.UI_MODE_NIGHT_YES
def on_start(self):
self.dark_on = self.is_dark_theme_on()
self.set_theme()
self.create_content_drawer()
self.create_dialogs()
self.get_last_location()
self.create_history()
self.configure_gps()
# self.set_decorations()
self.register_broadcats_receiver()
Clock.schedule_once(self.animate_colors, 3)
Clock.schedule_once(self.animate_lower_pos, 3)
# encreased to 3 seconds because of some older devices
# need more time for loading
Clock.schedule_once(self.first_start, 2.75)
self.set_decorations()
self.get_intent()
def on_pause(self, *_):
self.save_theme()
files = glob.glob('/cache/*.png')
for f in files:
try:
os.remove(f)
except OSError as e:
Logger.info('Chache not removed: ' + str(e))
self.unregister_broadcast_receiver()
if self.activity_alarm:
activity.unbind(on_new_intent=self.on_alarm_intent)
self.activity_alarm = False
return True
def on_resume(self):
self.register_broadcats_receiver()
self.get_intent()
Clock.schedule_once(self.get_last_location, .1)
def on_stop(self, *_):
try:
gps.stop()
except Exception:
Logger.info('On_pause: %s', exc_info=1)
files = glob.glob('/cache/*.png')
for f in files:
try:
os.remove(f)
except OSError as e:
Logger.info('Chache not removed: ' + str(e))
def select_intent(self, icon, lon=None, lat=None, mode=None):
if platform in ('win', 'linux', 'macos', 'linux2') \
and icon == 'walk':
url = \
f"{URL}52.506761,13.2843075,11z"
webbrowser.open(url)
return
elif platform == 'android' and\
icon != 'palette' and\
icon != 'set-left-right':
if icon == 'mail':
Clock.schedule_once(self.contact_developer, .5)
return
elif icon == 'walk':
self.open_navigation(lon, lat, mode)
Clock.schedule_once(partial(
self.open_navigation, lon, lat, mode), 0.5)
return True
elif icon == 'share-variant':
Clock.schedule_once(self.helper, .5)
return