-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
259 lines (227 loc) · 7.98 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
# -*- coding: utf-8 -*-
__version__ = "1.0"
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.core.window import Window
from kivy.properties import StringProperty, ObjectProperty
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.list import OneLineIconListItem
from kivymd.uix.snackbar import Snackbar
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.card import MDCardSwipe
from kivy.clock import Clock
from kivy.uix.camera import Camera
import os
import re
import webbrowser
from datetime import datetime
from language import Language
from platformhandler import platform_handler
import database
os.environ["KIVY_ORIENTATION"] = "Portrait"
Window.softinput_mode = "below_target"
class IconListItem(OneLineIconListItem):
icon = StringProperty()
class SwipeToDeleteItem(MDCardSwipe):
text = StringProperty()
class CamImage(Camera):
pass
class ContentNavigationDrawer(MDBoxLayout):
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
camImage = ObjectProperty()
toolbar = ObjectProperty()
class ExternalMemoryApp(MDApp): # <- main class
dialog = None
currentRating = 2
dbname = "ExternalMemory.app.db"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.platform = platform_handler()
self.database = database.DataBase(os.path.join( self.platform.app_dir, self.dbname))
lang = self.database.read(["VALUE"], "SETTING", {"KEY": "lang"})
self.text = Language(lang[0][0] if lang else None)
self.screen = Builder.load_file("layout.kv")
if self.platform.window_size:
Window.size = self.platform.window_size
def on_pause(self):
self.screen.ids["camImage"].play = False
return True
def on_resume(self):
self.screen.ids["camImage"].play = True
return True
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.device_orientation = "portrait"
self.icon = r'assets/app_icon.png'
dropdown_options = self.dropdown_options()
self.settingLanguageDropdown = self.dropdown_generator(dropdown_options["languageSetting"])
self.platform.imgframe = self.screen.ids["camImage"]
self.platform.stringdestination = self.screen.ids["productCode"]
self.platform.prefill_inputs = self.prefill_inputs
self.platform.adjustCamera()
Clock.schedule_interval(self.platform.imageProcessing, 1.0 / 10)
return self.screen
def dropdown_options(self):
return {
"languageSetting":{
"options": [{"icon": "translate", "option": lang} for lang in self.text.available()],
"fields": ["settingLanguageSelection"],
"context": "settingLanguageDropdown"
},
}
def dropdown_generator(self, parameter):
items = [
{
"text": self.text.get(i["content"]) if "content" in i else i["option"],
"content": i.get("content"),
"height": dp(64),
"viewclass": "IconListItem" if "icon" in i else None,
"icon": i.get("icon")
} for i in parameter["options"]
]
return {
field: MDDropdownMenu(
caller = self.screen.ids[field],
items = [dict(i,
**{"on_release": lambda x = (field, i["text"], parameter["context"]): self.select_dropdown_item(x[0], x[1], x[2])}
) for i in items],
position = "center",
width_mult = 4
) for field in parameter["fields"]
}
def select_dropdown_item(self, field, text, context):
self.screen.ids[field].text = text
con_text = getattr(self, context)
con_text[field].dismiss()
def notif(self, msg, display_delayed = 0):
def sb(this):
Snackbar(
text = msg
).open()
Clock.schedule_once(sb, display_delayed)
def cancel_confirm_dialog(self, decision, cancel, confirm):
if not self.dialog:
self.dialog = MDDialog(
text = decision,
buttons = [
MDFlatButton(
text = cancel,
on_release = self.cancel_confirm_dialog_handler
),
MDFlatButton(
text = confirm,
on_release = self.cancel_confirm_dialog_handler
),
],
)
self.dialog.open()
def cancel_confirm_dialog_handler(self, *btnObj):
self.dialog.dismiss()
self.dialog = None
if btnObj[0].text == self.text.get("settingConfirmClearLocal"):
self.database.clear(["DATA"])
self.screen.ids["libraryLocal"].text = ""
if btnObj[0].text == self.text.get("settingConfirmExportLocal"):
success = self.platform.file.copy_to_shared(
os.path.join(self.platform.app_dir, self.dbname),
collection = None,
filepath = self.platform.export_path(self.dbname))
self.notif(f"{success}")
if btnObj[0].text == self.text.get("settingConfirmImportLocal"):
self.platform.chooser.choose_content('*/*')
def translate(self, lang):
self.text.selectedLanguage = lang
for element in self.text.elements:
try:
# not all language chunks have their respective id'd counterparts like
# * dropdown-objects
obj = self.screen.ids[element]
if hasattr(obj, "hint_text") and obj.hint_text:
obj.hint_text = self.text.elements[element][lang]
continue
elif hasattr(obj, "text") and obj.text:
obj.text = self.text.elements[element][lang]
except:
continue
def save_setting(self, key, value):
sanitize={
"default": lambda x: int(x),
"lang": lambda x: x.strip(),
}
try:
if key in sanitize:
value=sanitize[key](value)
else:
value=sanitize["default"](value)
except Exception as e:
value=""
if value in ("", "NULL"):
self.database.delete("SETTING", {"KEY": key})
else:
self.database.write("SETTING", {"KEY": key, "VALUE": value}, {"KEY": key})
return str(value)
def set_current_rating(self, *args) -> None:
rating = None
selected = args[1].text
for i, option in enumerate(["productRatingBad", "productRatingMeh", "productRatingGood"]):
if selected == self.text.elements[option][self.text.selectedLanguage]:
rating = i
break
self.currentRating = (rating)
def save_inputs(self):
productCode = self.screen.ids["productCode"].text
if "|" in productCode and len(productCode[productCode.index("|")+1:]):
key_value = {
"ID": productCode,
"DATE": datetime.now().strftime("%Y-%m-%d"),
"MEMO": self.screen.ids["productNotes"].text if self.screen.ids["productNotes"].text else "NULL",
"RATING": self.currentRating
}
self.session = self.database.write("DATA", key_value, {"ID": productCode})
else:
self.notif(self.text.get("missingRateNotif"))
def prefill_inputs(self, productCode):
# this is to be passed to the platformhandler and executed if something like a code is recognized
known = self.database.read(["*"], "DATA", {"ID": productCode})
if not known:
self.screen.ids["productNotes"].text = ""
self.screen.ids["productRateDate"].text = ""
return
self.screen.ids["productNotes"].text = known[0][2] if known[0][2] else ""
self.screen.ids["productRateDate"].text = known[0][1] if known[0][1] else ""
rating = self.screen.ids["productRating"]
segment = rating.ids.segment_panel.children[known[0][3] * 2]
if rating.current_active_segment != segment:
rating.animation_segment_switch(segment)
rating.current_active_segment = segment
rating.dispatch("on_active", segment)
def display_library(self):
library = self.database.read(["*"], "DATA")
rating = ["productRatingBad", "productRatingMeh", "productRatingGood"]
self.screen.ids["libraryLocal"].clear_widgets()
if library:
for item in library:
self.screen.ids["libraryLocal"].add_widget(
SwipeToDeleteItem(
text = f"{item[0]}: {item[1]} - {self.text.elements[rating[item[3]]][self.text.selectedLanguage]}\n{item[2]}"
)
)
def delete_item(self, instance):
id = re.findall(r"^([^\n\r]+?)(?=$|: \d{4}\-)", instance.text, re.MULTILINE)[0]
if id:
self.database.delete("DATA", {"id": id})
self.screen.ids.libraryLocal.remove_widget(instance)
def lookup_item(self, search = ""):
if not search:
return
search = re.findall(r"^.+?\| ([^\n\r]+?)(?=$|: \d{4}\-)", search, re.MULTILINE)[0]
if search:
self.weblink(f"https://ecosia.org/search?q={search}")
def weblink(self, url):
webbrowser.open(url)
if __name__ == "__main__":
ExternalMemoryApp().run()