-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
352 lines (326 loc) · 14 KB
/
gui.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
import datetime
import os
import sys
from pathlib import Path
import tkinter as tk
from tkinter import ttk
import filters
from database import Database
from filmweb import FilmwebAPI
from options import Options
from presenter import Presenter
from updater import Updater
from userdata import DataManager, UserData
VERSION = '1.0.0-beta.4'
class Login(object):
# By default a dormant window that offers a request function to be called by
# the API. That function blocks until user enters data and clicks to log in.
# It then calls API again to do the actual backend login stuff.
default_message = 'Zaloguj się do filmweb.pl'
logerr_message = 'Niepowodzenie logowania!'
conerr_message = 'Sprawdź połączenie z internetem!'
def __init__(self, root):
self.__construct()
self.session = None
self.username = ''
self.root = root
self.window.resizable(False, False)
self.window.attributes("-topmost", True)
self.window.title('Zaloguj się')
self.window.protocol('WM_DELETE_WINDOW', self._cancelClick)
self.isDone = tk.BooleanVar()
self.isDone.set(False)
self.stateGood = True
#PUBLIC
def requestLogin(self, username:str=''):
#clean up if a previous failed attempt was cancelled
self.infoLabel['text'] = ''
#bring up the window and block until user completes
self.window.deiconify()
self.window.grab_set()
self.centerWindow()
#if the username was given by caller, prevent user from changing it
self.username = username
if username:
#because there is no set() method :|
self.usernameEntry.delete(0, 1000)
self.usernameEntry.insert(0, username)
self.usernameEntry.config(state=tk.DISABLED)
self.passwordEntry.focus_set()
else:
self.usernameEntry.config(state=tk.NORMAL)
self.usernameEntry.focus_set()
self.root.wait_variable(self.isDone)
_ses = self.session
self.session = None
self.isDone.set(False)
self.window.grab_release()
#return both the acquired session as well as the (perhaps acquired) username
return _ses, self.username
#CONSTRUCTION
def __construct(self):
self.window = cw = tk.Toplevel()
self.messageLabel = tk.Label(master=cw, text=self.default_message)
self.messageLabel.grid(row=0, column=0, columnspan=2)
tk.Label(master=cw, text='Nazwa użytkownika:').grid(row=1, column=0, sticky=tk.E)
tk.Label(master=cw, text='Hasło:').grid(row=2, column=0, sticky=tk.E)
self.usernameEntry = tk.Entry(master=cw, width=20)
self.usernameEntry.grid(row=1, column=1, sticky=tk.W)
self.usernameEntry.bind('<Key>', self._setStateGood)
self.passwordEntry = tk.Entry(master=cw, width=20, show='*')
self.passwordEntry.grid(row=2, column=1, sticky=tk.W)
self.passwordEntry.bind('<Key>', self._setStateGood)
self.rememberBox = tk.Checkbutton(self.window, text='pamiętaj mnie', variable=Options.var('rememberLogin'))
self.rememberBox.grid(row=3, column=1, columnspan=2, sticky=tk.W)
self.infoLabel = tk.Label(master=cw, text='')
self.infoLabel.grid(row=4, column=0, columnspan=2)
tk.Button(master=cw, text='Zaloguj', command=self._loginClick).grid(row=5, column=1, sticky=tk.W)
tk.Button(master=cw, text='Anuluj', command=self._cancelClick).grid(row=5, column=0, sticky=tk.E)
self.window.withdraw()
def centerWindow(self):
self.window.update()
ws = self.window.winfo_screenwidth()
hs = self.window.winfo_screenheight()
w = self.window.winfo_width()
h = self.window.winfo_height()
x = ws/2 - w/2
y = hs/2 - h/2
self.window.geometry('+{:.0f}+{:.0f}'.format(x, y))
#CALLBACKS
def _setStateBad(self, event=None, connection=False):
message = self.conerr_message if connection else self.logerr_message
self.infoLabel['text'] = message
self.stateGood = False
def _setStateGood(self, event=None):
if not self.stateGood:
self.infoLabel['text'] = ''
self.stateGood = True
#also, maybe the user has hit enter key, meaning to log in
if event.keysym == 'Return':
self._loginClick()
def _loginClick(self):
#collect login data
username = self.usernameEntry.get()
password = self.passwordEntry.get()
self.passwordEntry.delete(0, tk.END) #always clear the password field
#attempt to log in
success, session = FilmwebAPI.login(username, password)
if not success:
# in this case, "session" is actually a connection error flag
self._setStateBad(connection=session)
else:
#clear&hide, store session/username and pass control back to the caller
self.usernameEntry.delete(0, tk.END)
self.session = session
self.username = username
self.isDone.set(True)
self.window.withdraw()
def _cancelClick(self):
self.passwordEntry.delete(0, tk.END)
self.usernameEntry.delete(0, tk.END)
self.session = None
self.isDone.set(True)
self.window.withdraw()
class Main(object):
filename = 'filmatyk.dat' # will be created in user documents/home directory
wintitle = '{}Filmatyk' # format with debug flag
def __init__(self, debugMode=False, isOnLinux=False):
self.debugMode = debugMode
self.isOnLinux = isOnLinux
self.root = root = tk.Tk()
root.title(self.wintitle.format('[DEBUG] ' if self.debugMode else ''))
# load the savefile
self.dataManager = DataManager(self.getFilename(), VERSION)
userdata = self.dataManager.load()
# initialize the options manager
Options.init(userdata.options_json)
# construct the window: first the notebook for tabbed view
self.notebook = ttk.Notebook(root)
self.notebook.grid(row=0, column=0, padx=5, pady=5, sticky=tk.NW)
# set padding for notebook tabs
self.setStyle()
# version string
tk.Label(root, text='v{}'.format(VERSION)).grid(row=0, column=0, padx=5, pady=3, sticky=tk.NE)
# then the control panel
frame = tk.Frame(root)
frame.grid(row=1, column=0, padx=5, pady=5, sticky=tk.SW)
ttk.Button(frame, text='Aktualizuj', command=self._updateData).grid(row=0, column=0, sticky=tk.SW)
ttk.Button(frame, text='PRZEŁADUJ!', command=self._reloadData).grid(row=0, column=1, sticky=tk.SW)
self.progressVar = tk.IntVar()
self.progressbar = ttk.Progressbar(root, orient='horizontal', length=400, mode='determinate', variable=self.progressVar)
self.progressbar.grid(row=1, column=0, padx=5, pady=5)
self._setProgress(-1) # start with the progress bar hidden
ttk.Button(root, text='Wyjście', command=self._quit).grid(row=1, column=0, padx=5, pady=5, sticky=tk.SE)
# construct the login window manager and prepare to load data
self.loginHandler = Login(self.root)
self.abortUpdate = False # database can set this via callback when something goes wrong
self.databases = []
self.presenters = []
# instantiate Presenters and Databases
self.api = FilmwebAPI(self.loginHandler.requestLogin, userdata.username)
self.api.restoreSession(userdata.session_pkl)
movieDatabase = Database.restoreFromString('Movie', userdata.movies_data, self.api, self._setProgress)
self.databases.append(movieDatabase)
moviePresenter = Presenter(self, self.api, movieDatabase, userdata.movies_conf)
moviePresenter.addFilter(filters.YearFilter, row=0, column=0, sticky=tk.EW)
moviePresenter.addFilter(filters.RatingFilter, row=1, column=0, sticky=tk.EW)
moviePresenter.addFilter(filters.DateFilter, row=2, column=0, sticky=tk.EW)
moviePresenter.addFilter(filters.GenreFilter, row=0, column=1, rowspan=3, sticky=tk.NW)
moviePresenter.addFilter(filters.CountryFilter, row=0, column=2, rowspan=3, sticky=tk.NW)
moviePresenter.addFilter(filters.DirectorFilter, row=0, column=3, rowspan=3, sticky=tk.NW)
moviePresenter.placeInTab('Filmy')
moviePresenter.totalUpdate()
self.presenters.append(moviePresenter)
seriesDatabase = Database.restoreFromString('Series', userdata.series_data, self.api, self._setProgress)
self.databases.append(seriesDatabase)
seriesPresenter = Presenter(self, self.api, seriesDatabase, userdata.series_conf)
seriesPresenter.addFilter(filters.YearFilter, row=0, column=0, sticky=tk.EW)
seriesPresenter.addFilter(filters.RatingFilter, row=1, column=0, sticky=tk.EW)
seriesPresenter.addFilter(filters.DateFilter, row=2, column=0, sticky=tk.EW)
seriesPresenter.addFilter(filters.GenreFilter, row=0, column=1, rowspan=3, sticky=tk.NW)
seriesPresenter.addFilter(filters.CountryFilter, row=0, column=2, rowspan=3, sticky=tk.NW)
seriesPresenter.addFilter(filters.DirectorFilter, row=0, column=3, rowspan=3, sticky=tk.NW)
seriesPresenter.placeInTab('Seriale')
seriesPresenter.totalUpdate()
self.presenters.append(seriesPresenter)
gameDatabase = Database.restoreFromString('Game', userdata.games_data, self.api, self._setProgress)
self.databases.append(gameDatabase)
gamePresenter = Presenter(self, self.api, gameDatabase, userdata.games_conf)
gamePresenter.addFilter(filters.YearFilter, row=0, column=0, sticky=tk.EW)
gamePresenter.addFilter(filters.RatingFilter, row=1, column=0, sticky=tk.EW)
gamePresenter.addFilter(filters.DateFilter, row=2, column=0, sticky=tk.EW)
gamePresenter.addFilter(filters.GenreFilter, row=0, column=1, rowspan=3, sticky=tk.NW)
gamePresenter.addFilter(filters.PlatformFilter, row=0, column=2, rowspan=3, sticky=tk.NW)
gamePresenter.addFilter(filters.GamemakerFilter, row=0, column=3, rowspan=3, sticky=tk.NW)
gamePresenter.placeInTab('Gry')
gamePresenter.totalUpdate()
self.presenters.append(gamePresenter)
#center window AFTER creating everything (including plot)
self.centerWindow()
#ensure a controlled exit no matter what user does (X-button, alt+f4)
root.protocol('WM_DELETE_WINDOW', self._quit)
if userdata.is_empty:
self._reloadData() # first run
#instantiate updater and check for updates
self.updater = Updater(self.root, VERSION, progress=self._setProgress, quitter=self._quit, debugMode=self.debugMode, linuxMode=self.isOnLinux)
self.updater.checkUpdates()
#prevent resizing and run the app
root.resizable(False, False)
root.wm_attributes('-topmost', 0)
tk.mainloop()
def setStyle(self):
self.style = ttk.Style()
current = self.style.theme_use()
self.style.theme_settings(current, {
'TNotebook.Tab': {
'configure': {'width': 20, 'anchor': 'center'}
}
})
def centerWindow(self):
self.root.update()
ws = self.root.winfo_screenwidth()
hs = self.root.winfo_screenheight()
w = self.root.winfo_width()
h = self.root.winfo_height()
x = ws/2 - w/2
y = hs/2 - h/2
self.root.geometry('+{:.0f}+{:.0f}'.format(x, y))
# USER DATA MANAGEMENT
def getFilename(self):
if self.debugMode:
return self.filename
subpath = self.filename
userdir = str(Path.home())
return os.path.join(userdir, subpath)
def saveUserData(self):
"""Save the user data, if any of it has changed during the run time."""
# if for any reason the first update hasn't commenced - don't save anything
if self.api.username is None:
return
# if the session is set to be stored - serialize it
# if it is also dirty - set the flag for a check later
session_pkl = 'null'
session_isDirty = False
if Options.get('rememberLogin'):
session_pkl = self.api.storeSession()
if self.api.isDirty:
session_isDirty = True
# if there is no need to save anything - stop right there too
if not (
any([db.isDirty for db in self.databases]) or
any([ps.isDirty for ps in self.presenters]) or
Options.isDirty or
session_isDirty
):
return
# construct the UserData object
serialized_data = UserData(
username=self.api.username,
movies_conf=self.presenters[0].storeToString(),
movies_data=self.databases[0].storeToString(),
series_conf=self.presenters[1].storeToString(),
series_data=self.databases[1].storeToString(),
games_conf=self.presenters[2].storeToString(),
games_data=self.databases[2].storeToString(),
options_json=Options.storeToString(),
session_pkl=session_pkl,
)
# request the manager to save it
self.dataManager.save(serialized_data)
# notify the objects that they were saved
for db in self.databases:
db.isDirty = False
for ps in self.presenters:
ps.isDirty = False
Options.isDirty = False
self.api.isDirty = False
#CALLBACKS
def _setProgress(self, value:int, abort:bool=False):
# allows the caller to set the percentage value of the progress bar
# slightly hacky, but allows cancelling an entire update if the user failed to log in
# non-negative values cause the bar to show up, negative hides it
self.abortUpdate = abort
if value < 0:
self.progressbar.grid_remove()
self.progressVar.set(0)
else:
self.progressbar.grid()
self.progressVar.set(value)
self.root.update()
def _updateData(self):
# call softUpdate on all the databases and update all the presenters
for db, ps in zip(self.databases, self.presenters):
db.softUpdate()
ps.totalUpdate()
# if the user failed to log in or there was a connection error - abort
if self.abortUpdate:
break
# save data
self.saveUserData()
def _reloadData(self):
for db, ps in zip(self.databases, self.presenters):
db.hardUpdate()
ps.totalUpdate()
if self.abortUpdate:
break
self.saveUserData()
def _quit(self, restart=False):
self.saveUserData()
self.root.quit()
# Updater might request the whole app to restart. In this case, a request
# is passed higher to the system shell to launch the app again.
if restart:
command = "cd .. &&"
# remember which launcher was used
if self.isOnLinux:
command += " ./Filmatyk_linux.sh"
else:
command += " Filmatyk.bat"
# maintain debug status
if self.debugMode:
command += " debug"
os.system(command)
if __name__ == "__main__":
debugMode = "debug" in sys.argv
isOnLinux = "linux" in sys.argv
Main(debugMode=debugMode, isOnLinux=isOnLinux)