-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
348 lines (273 loc) · 12.3 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
# -*- coding: utf-8 -*-
# GIFS - Clean up the file
# DOCS - Write some documentation
"""
File: main.py
Creator: MazeFX
Date: 3-8-2016
Main file for Personal Admin Tool.
For initialisation of the main application and handling
login events. Populating the main window with the necessary
sub-forms and widgets.
"""
import logging
Lumberjack = logging.getLogger(__name__)
import os
import json
import sys
from PyQt5.QtGui import QFontDatabase, QIcon
from PyQt5.QtCore import QCoreApplication, QSettings, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QLabel, QTabWidget, QSystemTrayIcon
import qtawesome as qta
from colorama import Fore, Back, Style
from colorama import init as colorama
from dialogs import SettingsDialog, CloseDialog, TerminationDialog
from MyQtness.ui_main_window import Ui_MainWindow
from MyQtness import style
from tabs import BankAccountListTab, ContractListTab, EmailAddressListTab, LetterListTab, \
UserListTab, RelationListTab, TransactionListTab, HomeTab
from db.helper import DbHelper
class MainApp(QMainWindow, Ui_MainWindow):
_translate = QCoreApplication.translate
tab_list = []
# TODO - add dutch translation files
def __init__(self, isolated, *args):
super(MainApp, self).__init__(*args)
Lumberjack.info('spawning the <<< MainApp >>> hey says: I am the Main man here see!')
self.load_settings()
self.setup_tray(isolated)
self.dbhelper = DbHelper()
self.setupUi(self)
self.iconize_controls()
self.load_styling()
self.tabWidget = QTabWidget(self.centralwidget)
self.tabWidget.setTabsClosable(True)
self.tabWidget.setMovable(True)
self.tabWidget.setTabBarAutoHide(True)
self.tabWidget.setObjectName("tabWidget")
self.verticalLayout.addWidget(self.tabWidget)
builderLabel = QLabel('made by: MazeFX Solutions')
self.statusbar.addPermanentWidget(builderLabel)
self.menuPAT.triggered.connect(self.handle_menu_event)
self.menuLists.triggered.connect(self.handle_menu_event)
self.menuHelp.triggered.connect(self.handle_menu_event)
self.tabWidget.tabCloseRequested.connect(self.close_tab)
self.actionHome.trigger()
self._retranslateUi(self)
def iconize_controls(self):
Lumberjack.info('< MainApp > - -> (iconize_controls)')
homeIcon = qta.icon('fa.home', color='white')
self.actionHome.setIcon(homeIcon)
wrenchIcon = qta.icon('fa.wrench', color='white')
self.actionSettings.setIcon(wrenchIcon)
bankIcon = qta.icon('fa.bank', color='white')
self.actionListBankAccounts.setIcon(bankIcon)
contractIcon = QIcon(':/app_icons/rc/handshake_icon.svg')
self.actionListContracts.setIcon(contractIcon)
atIcon = qta.icon('fa.at', color='white')
self.actionListEmailAddresses.setIcon(atIcon)
envelopeIcon = qta.icon('fa.envelope', color='white')
self.actionListLetters.setIcon(envelopeIcon)
relationIcon = qta.icon('fa.group', color='white')
self.actionListRelations.setIcon(relationIcon)
transactionIcon = qta.icon('fa.money', color='white')
self.actionListTransactions.setIcon(transactionIcon)
userIcon = qta.icon('fa.user', color='white')
self.actionListUsers.setIcon(userIcon)
helpIcon = qta.icon('fa.question', color='white')
self.actionHelp.setIcon(helpIcon)
aboutIcon = qta.icon('fa.info', color='white')
self.actionAbout.setIcon(aboutIcon)
def setup_tray(self, isolated):
Lumberjack.info('< MainApp > - -> (setup_tray)')
self.trayIcon = QSystemTrayIcon(QIcon(':/app_icons/rc/PAT_icon.png'), self)
self.trayMenu = QMenu(self)
showAction = self.trayMenu.addAction("Open PAT")
self.trayMenu.addSeparator()
exitAction = self.trayMenu.addAction("Exit")
self.trayIcon.setContextMenu(self.trayMenu)
self.trayMenu.triggered.connect(self.handle_tray_event)
self.trayIcon.activated.connect(self.handle_tray_event)
self.trayIcon.show()
if isolated:
self.trayIcon.showMessage('PAT Service', 'PAT service is now running..')
def handle_tray_event(self, *args):
Lumberjack.info('< MainApp > - -> (handle_tray_event)')
print(Fore.MAGENTA + '$! Received a tray action with args: ', args)
if args[0] == 3:
self.show()
return
elif hasattr(args[0], 'text'):
print(Fore.MAGENTA + '$! Tray event has text!!')
if args[0].text() == 'Open PAT':
self.show()
elif args[0].text() == 'Exit':
self.close()
def _retranslateUi(self, MainWindow):
pass
def handle_menu_event(self, *args):
Lumberjack.info('< MainApp > - -> (handle_menu_event)')
Lumberjack.debug('(handle_menu_event) - args = {}'.format(args))
action_text = args[0].text()
icon = args[0].icon()
Lumberjack.debug('(handle_menu_event) - Action text selector = {}'.format(action_text))
print(Fore.MAGENTA + '$! Action text received: ', action_text)
if action_text == 'Home':
Lumberjack.info('(handle_menu_event) >User action> : Adding Home tab to self')
self.add_tab(HomeTab, 'Home', icon)
if action_text == 'Settings':
Lumberjack.info('(handle_menu_event) >User action> : Showing settings dialog')
self.show_settings()
elif action_text == 'Bank accounts':
Lumberjack.info('(handle_menu_event) >User action> : Adding Bank account List tab to self')
self.add_tab(BankAccountListTab, 'Bank accounts', icon)
elif action_text == 'Contracts':
Lumberjack.info('(handle_menu_event) >User action> : Adding Contracts List tab to self')
self.add_tab(ContractListTab, 'Contracts', icon)
elif action_text == 'Email addresses':
Lumberjack.info('(handle_menu_event) >User action> : Adding EmailAddress List tab to self')
self.add_tab(EmailAddressListTab, 'Email addresses', icon)
elif action_text == 'Letters':
Lumberjack.info('(handle_menu_event) >User action> : Adding Letter List tab to self')
self.add_tab(LetterListTab, 'Letters', icon)
elif action_text == 'Users':
Lumberjack.info('(handle_menu_event) >User action> : Adding User List tab to self')
self.add_tab(UserListTab, 'Users', icon)
elif action_text == 'Relations':
Lumberjack.info('(handle_menu_event) >User action> : Adding Relation List tab to self')
self.add_tab(RelationListTab, 'Relations', icon)
elif action_text == 'Transactions':
Lumberjack.info('(handle_menu_event) >User action> : Adding Transaction List tab to self')
self.add_tab(TransactionListTab, 'Transactions', icon)
elif action_text == 'Help':
Lumberjack.info('(handle_menu_event) >User action> : Showing help dialog')
# TODO - build help dialog and help files
elif action_text == 'About':
Lumberjack.info('(handle_menu_event) >User action> : Showing about dialog')
# TODO build About dialog.
def show_settings(self):
Lumberjack.info('< MainApp > - -> (show_settings)')
settings_dialog = SettingsDialog()
settings_dialog.exec_()
def add_tab(self, tab_cls, tab_name, icon):
Lumberjack.info('< MainApp > - -> (add_tab)')
new_tab = tab_cls(self.dbhelper)
print(Fore.MAGENTA + 'Adding a tab with class: ', str(tab_cls))
new_tab.setObjectName(str(tab_cls))
self.tabWidget.addTab(new_tab, icon, self._translate("MainWindow", tab_name))
print(Fore.MAGENTA + 'New tab added to tab list.')
self.tabWidget.setCurrentIndex(self.tabWidget.indexOf(new_tab))
self.tab_list.append(new_tab)
def close_tab(self, index):
# TODO - Check if index stays correct when moving tabs around
requesting_tab = self.tab_list[index]
print(Fore.MAGENTA + 'requesting tab is: ', requesting_tab)
if hasattr(requesting_tab, 'form'):
if requesting_tab.form.edit_mode:
print(Fore.MAGENTA + 'Tab is in edit mode.')
requesting_tab.form.toggle_edit_mode(False, None, None)
if requesting_tab.form.edit_mode is None:
print(Fore.MAGENTA + 'Tab is now in equil.')
self.tabWidget.removeTab(index)
del self.tab_list[index]
else:
self.tabWidget.removeTab(index)
del self.tab_list[index]
def load_settings(self):
self.settings = QSettings()
db_path = self.settings.value('db_base_path')
db_name = self.settings.value('db_name')
if db_path is not None and db_name is not None:
db_file = os.path.join(db_path, db_name)
Lumberjack.debug('__init__ - db_file = {}'.format(db_file))
if os.path.exists(db_file):
return
Lumberjack.warning('(load_settings) - database not found')
settings_dialog = SettingsDialog()
settings_dialog.exec_()
int_value = self.settings.value('db_type', type=int)
print(Fore.MAGENTA + "load choosen database setting: %s" % repr(int_value))
def load_styling(self):
style.set_window_style(self)
def closeEvent(self, event):
print(Fore.MAGENTA + "User has clicked the red x on the main window")
for tab in self.tab_list:
if hasattr(tab, 'form'):
if tab.form.edit_mode:
print(Fore.MAGENTA + 'Tab is in edit mode.')
tab.form.toggle_edit_mode(False, None, None)
close_dialog = CloseDialog()
result = close_dialog.exec_()
if result == close_dialog.Minimize:
self.hide()
event.ignore()
elif result == close_dialog.Rejected:
event.ignore()
elif result == close_dialog.Exit:
print(Fore.MAGENTA + "Exiting via save dialog, result = ", result)
self.trayIcon.hide()
event.accept()
def setup_logging(
default_path='lumberjack_config.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
if __name__ == "__main__":
import logging.config
colorama(autoreset=True)
setup_logging()
Lumberjack.info('======================= Logger set up.. ')
def spot_the_looney(excType, excValue, traceback, logger=Lumberjack):
logger.error("------ Logging an uncaught exception ---------------------------->",
exc_info=(excType, excValue, traceback))
termination_dialog = TerminationDialog()
result = termination_dialog.exec_()
if result == 0:
Lumberjack.info('-->Trying to exit the app..')
sys.exit(-1)
Lumberjack.info('[result] = ', result)
sys.excepthook = spot_the_looney
Lumberjack.info('======================= Starting Application.. ')
visible = True
app = QApplication(sys.argv)
app.setApplicationName('PAT')
app.setOrganizationName("MazeFX Solutions")
app.setOrganizationDomain("MazeFX.pythonanywhere.com")
# TODO - Make font path relative
QFontDatabase().addApplicationFont("C:\PDE\projects\qt\pat\MyQtness\style/fonts/ethnocentric.ttf")
QFontDatabase().addApplicationFont("C:\PDE\projects\qt\pat\MyQtness\style/fonts/ubuntu_bold.ttf")
# loginDialog = LoginDialog()
'''
isAuth = False
result = -1
while not isAuth:
result = loginDialog.exec_()
if result == loginDialog.Success or result == LoginDialog.Rejected:
isAuth = True
else:
isAuth = False
if result == loginDialog.Success:
'''
for arg in sys.argv:
if 'only-tray' in arg:
isolated = True
else:
isolated = False
w = MainApp(isolated)
if not isolated:
w.show()
app.exec_()
Lumberjack.info('======================= Ending Application.. ')
sys.exit(-1)