-
Notifications
You must be signed in to change notification settings - Fork 0
/
AGeMain.py
3696 lines (3392 loc) · 181 KB
/
AGeMain.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
# Astus General Library Main File
Version = "2.0.0"
# Using Semantic Versioning 2.0.0 https://semver.org/
version = Version
Author = "Robin \'Astus\' Albers"
"""
Copyright (C) 2020 Robin Albers
"""
try:
from AGeLib import AGeColour
except ModuleNotFoundError:
import AGeColour
import sys
from PyQt5 import QtWidgets,QtCore,QtGui,Qt
from PyQt5.QtWebEngineWidgets import QWebEngineView # pylint: disable=no-name-in-module
import datetime
import time
from time import time as timetime
import platform
import errno
import os
import re
import string
import traceback
import pathlib
import getpass
import importlib
from packaging.version import parse as versionParser
import sympy
from sympy.parsing.sympy_parser import parse_expr
from numpy import __version__ as numpy_version
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
from distutils.spawn import find_executable
if find_executable('latex') and find_executable('dvipng'): LaTeX_dvipng_Installed = True
else : LaTeX_dvipng_Installed = False
#TODO: Add documentation to ALL classes, methods and functions
#region Notifications and exceptions
common_exceptions = (TypeError , SyntaxError , sympy.SympifyError , sympy.parsing.sympy_parser.TokenError , re.error , AttributeError , ValueError , NotImplementedError , Exception , RuntimeError , ImportError)
def ExceptionOutput(exc_info = None, extraInfo = True):
"""
Console output for exceptions\n
Use in `except:`: Error = ExceptionOutput(sys.exc_info())\n
Prints Time, ExceptionType, Filename+Line and (if extraInfo in not False) the exception description to the console\n
Returns a string
"""
try:
if False:
if exc_info == None:
exc_info = True
return NC(exc=exc_info)
else:
print(cTimeSStr(),":")
if exc_info==None:
exc_type, exc_obj, exc_tb = sys.exc_info()
else:
exc_type, exc_obj, exc_tb = exc_info
fName = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
if extraInfo:
print(exc_type, " in", fName, " line", exc_tb.tb_lineno ,": ", exc_obj)
else:
print(exc_type, " in", fName, " line", exc_tb.tb_lineno)
return str(exc_type)+": "+str(exc_obj)
except common_exceptions as inst:
print("An exception occurred while trying to print an exception!")
print(inst)
# -----------------------------------------------------------------------------------------------------------------
class NotificationEvent(QtCore.QEvent):
EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())
def __init__(self, N):
QtCore.QEvent.__init__(self, NotificationEvent.EVENT_TYPE)
self.N = N
class NC: # Notification Class
"""
This is the basic notification class of AGeLib. \n
All notifications are stored and accessible via the Notification Window which is opened by pressing on Notification button of any (AWWF) window. \n
Notifications are used to communicate with the user and can be used for exception handling as they provide space for an entire bug report. \n
They contain the version number of all modules that are in MainApp.ModuleVersions and can extract all information from exceptions. \n
There are various levels of notifications: lvl: 0 = Nothing , 1 = Error , 2 = Warning , 3 = Notification , 4 = Advanced Mode Notification , 10 = Direct Notification \n
The notification sends itself automatically. If you want to modify the notification before it is send set ``send=False`` and call ``.send()`` after the modifications are done \n
The creation is very flexible. Here are a few examples: \n
```python
NC(10,"This message is directly displayed in the top bar and should be held very short and not contain any linebreaks (a single linebreak is ok in spacial cases)")
NC("This creates a normal notification")
NC(2,"This creates a warning")
NC((2,"A tuple with level and message is also acceptable"))
NC("This generates an error notification with the last caught exception",exc = sys.exc_info())
NC("This notification includes the callstack",tb=True)
```
Even this is valid: ``NC()`` (Though not recommended) \n
``lvl=0`` can be useful if you want to create a notification in a function (with ``Notification = NC(lvl=0,send=False)``), fill it with information dynamically and return it for the caller.
The caller can then send the Notification. If ``lvl=0`` the MainApp will ignore the notification thus the caller does not need to care whether the function actually had anything to notify the user about. \n
If you want to notify the user about exceptions ``exc`` should be ``True`` or ``sys.exc_info()``. If the exception should be logged but is usually not important set ``lvl=4``.
If the exception is not critical but should be noted as it might lead to unwanted behaviour set ``lvl=2`` to warn the user.
Exception notifications should set ``msg`` to give a short description that a regular user can understand (for example ``msg="The input could not be interpreted."`` or ``msg="Could not connect to the website."``).
It is also useful to set ``input`` to log the input that lead to the error. This should also include any settings that were used. \n
Only ``lvl=int``,``time=datetime.datetime.now()``,``send=bool`` and ``exc=True or sys.exc_info()`` need a specific data type.
Everything else will be stored (msg will be converted into a string before storing). The access methods will return a string (and cast all input to a string before saving)
but the variables can still be accessed directly with the data type that was given to the init. \n
Please note that ``err`` and ``tb`` are ignored when ``exc != None`` as they will be extracted from the exception. \n
``tb`` should be a string containing the callstack or ``True`` to generate a callstack
"""
def __init__(self, lvl=None, msg=None, time=None, input=None, err=None, tb=None, exc=None, win=None, func=None, DplStr=None, send=True):
"""
Creates a new notification object \n
The creation is very flexible. Here are a few examples: \n
```python
NC(10,"This message is directly displayed in the top bar and should be held short and without linebreaks")
NC("This creates a normal notification")
NC(2,"This creates a warning")
NC((2,"A tuple with level and message is also acceptable"))
NC("This generates an error notification with the last caught exception",exc = sys.exc_info())
NC("This notification includes the callstack",tb=True)
```
lvl: 0 = Nothing , 1 = Error , 2 = Warning , 3 = Notification , 4 = Advanced Mode Notification , 10 = Direct Notification \n
``exc = True`` or ``sys.exc_info()`` \n
``tb`` should be a string containing the callstack or ``True`` to generate a callstack
"""
self._time_time = timetime()
self._init_Values()
self._was_send = False
try:
self._time = datetime.datetime.now() if time == None else time
self.Time = self._time.strftime('%H:%M:%S')
self.DplStr = DplStr
self.Window = win
self.Function = func
self.Input = input
if exc != None:
if exc == True:
self.exc_type, self.exc_obj, self.exc_tb = sys.exc_info()
else:
self.exc_type, self.exc_obj, self.exc_tb = exc
fName = os.path.split(self.exc_tb.tb_frame.f_code.co_filename)[1]
if type(lvl)==str:
self.level = 1
self.Message = lvl
elif msg==None and type(lvl) == tuple:
self.level, self.Message = lvl[0], lvl[1]
else:
self.level = 1 if lvl == None else lvl
self.Message = str(msg) if msg!=None else None
self.ErrorTraceback = str(self.exc_type)+" in "+str(fName)+" line "+str(self.exc_tb.tb_lineno)+"\n\n"+str(traceback.format_exc())#[:-1]) # TODO: Use traceback.format_exc() to get full traceback or something like traceback.extract_stack()[:-1] ([:-1] removes the NC.__init__())
print(self.Time,":")
if len(str(self.exc_obj))<150:
self.Error = str(self.exc_type)+": "+str(self.exc_obj)
print(self.exc_type, " in", fName, " line", self.exc_tb.tb_lineno,": ", self.exc_obj)
else:
self.Error = str(self.exc_type)
self.ErrorLongDesc = str(self.exc_obj)
print(self.exc_type, " in", fName, " line", self.exc_tb.tb_lineno)
else:
if type(lvl)==str:
self.level = 3
self.Message = lvl
elif msg==None and type(lvl) == tuple:
self.level, self.Message = lvl[0], lvl[1]
else:
self.level = 3 if lvl == None else lvl
self.Message = str(msg) if msg!=None else None
self.Error = err
if tb == True:
self.ErrorTraceback = ""
try:
for i in traceback.format_stack()[0:-1]:
self.ErrorTraceback += str(i)
except:
self.ErrorTraceback = "Could not extract callstack"
else:
self.ErrorTraceback = tb
self.GenerateLevelName()
if send == True:
self.send()
except common_exceptions as inst:
self._init_Values()
print(cTimeSStr(),": An exception occurred while trying to create a Notification")
print(inst)
self._time = datetime.datetime.now() if time == None else time
self.Time = self._time.strftime('%H:%M:%S')
self.Message = "An exception occurred while trying to create a Notification"
self.exc_obj = inst
self.Error = str(inst)
self.GenerateLevelName()
self.send(force=True)
def _init_Values(self):
self.exc_type, self.exc_obj, self.exc_tb = None,None,None
self._time, self.Time, self.Error = None,None,None
self.Window, self.ErrorTraceback, self.Function = None,None,None
self.level, self.Level, self.Message = 1,"Notification level 1",None
self.Input, self.ErrorLongDesc = None,None
self.DplStr, self.TTStr = None,None
self.icon = QtGui.QIcon()
try:
self.Flash = QtWidgets.QApplication.instance().NCF_NONE
except common_exceptions as inst:
print(inst)
self.Flash = None
self.itemDict = {"Time:\n":self.Time,"Level: ":self.Level,"Message:\n":self.Message,
"Error:\n":self.Error,"Error Description:\n":self.ErrorLongDesc,"Error Traceback:\n":self.ErrorTraceback,
"Function:\n":self.Function,"Window:\n":self.Window,"Input:\n":self.Input}
#---------- send, print ----------#
def send(self,force=False):
"""
Displays this notification (This method is thread save but this object should not be modified after using send) \n
A notification can only be send once. ``force=True`` allows to send an already send notification again
"""
if force or not self._was_send:
self._was_send = True
QtWidgets.QApplication.postEvent(QtCore.QThread.currentThread(), NotificationEvent(self))
def print(self):
"""Prints this notification to the console"""
print("\n",self.Level, "at",self.Time,"\nMessage:",self.Message)
if self.Error != None:
print("Error:",self.Error,"Traceback:",self.ErrorTraceback,"\n")
#---------- items, unpack ----------#
def items(self):
"""
Returns self.itemDict.items() \n
self.itemDict contains all relevant data about this notification. \n
Please note that not all values are strings and should be converted before diplaying them.
This allows ``if v!=None:`` to filter out all empty entries. \n
The keys already end with ``:\\n`` thus it is advised to simply use ``k+str(v)`` for formatting. \n
For an example how to use this method see the source code of ``NotificationInfoWidget``.
"""
self.itemDict = {"Time:\n":self.Time,"Level: ":"({})\n{}".format(str(self.level),self.Level),"Message:\n":self.Message,
"Error:\n":self.Error,"Error Description:\n":self.ErrorLongDesc,"Error Traceback:\n":self.ErrorTraceback,
"Function:\n":self.Function,"Window:\n":self.Window,"Input:\n":self.Input,"Versions:\n":QtWidgets.QApplication.instance().ModuleVersions}
return self.itemDict.items()
def unpack(self): #CLEANUP: remove unpack
"""DEPRECATED: Returns a tuple ``(int(level),str(Message),str(Time))``"""
return (self.level, str(self.Message), self.Time)
#---------- access variables ----------#
def l(self, level=None):
"""
Returns int(level) \n
An int can be given to change the level
"""
if level != None:
self.level = level
self.GenerateLevelName()
return self.level
def m(self, message=None):
"""
Returns str(Message) \n
A str can be given to change the Message
"""
if message != None:
self.Message = str(message)
if self.Message == None and self.Error != None:
return str(self.Error)
else:
return str(self.Message)
def DPS(self, DplStr = None):
"""
Returns str(DplStr) \n
DplStr is the string that is intended to be displayed directly \n
A str can be given to change the DplStr
"""
if DplStr != None:
self.DplStr = str(DplStr)
elif self.DplStr == None:
if self.level == 10:
self.DplStr = self.m()
else:
self.DplStr = self.Level + " at " + self.t()
return str(self.DplStr)
def TTS(self, TTStr = None):
"""
Returns str(TTStr) \n
TTStr is the string that is intended to be displayed as the tool tip \n
A str can be given to change the TTStr
"""
if TTStr != None:
self.TTStr = str(TTStr)
elif self.TTStr == None:
if self.level == 10:
self.TTStr = self.Level + " at " + self.t()
else:
self.TTStr = self.m()
return str(self.TTStr)
def t(self, time=None):
"""
Returns the time as %H:%M:%S \n
datetime.datetime.now() can be given to change the time
"""
if time != None:
self._time = time
self.Time = self._time.strftime('%H:%M:%S')
return self.Time
def e(self, Error=None, ErrorTraceback=None):
"""
Returns str(Error) \n
strings can be given to change the Error and ErrorTraceback
"""
if Error != None:
self.Error = str(Error)
if ErrorTraceback != None:
self.ErrorTraceback = str(ErrorTraceback)
return str(self.Error)
def tb(self, ErrorTraceback=None):
"""
Returns str(ErrorTraceback) \n
A str can be given to change the ErrorTraceback
"""
if ErrorTraceback != None:
self.ErrorTraceback = str(ErrorTraceback)
return str(self.ErrorTraceback)
def f(self, func=None):
"""
Returns str(Function) \n
A str can be given to change the Function \n
Function is the name of the function from which this notification originates
"""
if func != None:
self.Function = str(func)
return str(self.Function)
def w(self, win=None):
"""
Returns str(Window) \n
A str can be given to change the Window \n
Window is the name of the window from which this notification originates
"""
if win != None:
self.Window = str(win)
return str(self.Window)
def i(self, input=None):
"""
Returns str(Input) \n
A str can be given to change the Input \n
Input is the (user-)input that caused this notification
"""
if input != None:
self.Input = str(input)
return str(self.Input)
#---------- GenerateLevelName ----------#
def GenerateLevelName(self):
"""
Generates str(self.Level) from int(self.level)
"""
try:
if self.level == 0:
self.Level = "Empty Notification"
self.icon = QtGui.QIcon()
self.Flash = QtWidgets.QApplication.instance().NCF_NONE
elif self.level == 1:
self.Level = "Error"
self.icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxCritical)
self.Flash = QtWidgets.QApplication.instance().NCF_r
elif self.level == 2:
self.Level = "Warning"
self.icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxWarning)
self.Flash = QtWidgets.QApplication.instance().NCF_y
elif self.level == 3:
self.Level = "Notification"
self.icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxInformation)
self.Flash = QtWidgets.QApplication.instance().NCF_b
elif self.level == 4:
self.Level = "Advanced Mode Notification"
self.icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxInformation)
self.Flash = QtWidgets.QApplication.instance().NCF_b
elif self.level == 10:
self.Level = "Direct Notification"
self.icon = QtGui.QIcon()
self.Flash = QtWidgets.QApplication.instance().NCF_NONE
else:
self.Level = "Notification level "+str(self.level)
self.Flash = QtWidgets.QApplication.instance().NCF_b
return self.Level
except common_exceptions as inst:
print(inst)
return "Could not generate Level Name"
#---------- __...__ ----------#
def __add__(self,other):
if self.Error != None:
return str(self.Error) + str(other)
else:
return str(self.Message) + str(other)
def __radd__(self,other):
if self.Error != None:
return str(other) + str(self.Error)
else:
return str(other) + str(self.Message)
def __call__(self):
return str(self.Message)
def __str__(self):
if self.Error != None:
if self.Message == None:
return "Exception at "+str(self.Time)+":\n"+str(self.Error)
else:
return str(self.Level)+" at "+str(self.Time)+":\n"+str(self.Message)+"\n"+str(self.Error)
else:
return str(self.Level)+" at "+str(self.Time)+":\n"+str(self.Message)
#endregion
#region Helper Classes
class ColourDict(dict):
"""
This class is used to store the special colours. \n
It is used to ensure that a missing colour does not cause a crash by returning the "Blue" colour.
"""
def __getitem__(self, key):
try:
Colour = dict.__getitem__(self, key)
except:
for v in self.values():
Colour = v
break
return Colour
def copyFromDict(self, dict):
for i,v in dict.items():
self[i] = v
#endregion
#region Functions
def cTimeStr():
"""
Returns the time (excluding seconds) as a string\n
%H:%M
"""
return str(datetime.datetime.now().strftime('%H:%M'))
def cTimeSStr():
"""
Returns the time (including seconds) as a string\n
%H:%M:%S
"""
return str(datetime.datetime.now().strftime('%H:%M:%S'))
def cTimeFullStr(separator = None):
"""
Returns the date and time as a string\n
If given uses `separator` to separate the values\n
%Y.%m.%d-%H:%M:%S or separator.join(['%Y','%m','%d','%H','%M','%S'])
"""
if separator == None:
return str(datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S'))
else:
TheFormat = separator.join(['%Y','%m','%d','%H','%M','%S'])
return str(datetime.datetime.now().strftime(TheFormat))
def trap_exc_during_debug(*args):
# when app raises uncaught exception, send info
NC(1,"An unhandled exception occurred in a QThread!!!",err=str(args))
#endregion
#region Shortcut Functions
def advancedMode() -> bool:
"""
Used to check whether the advanced mode is active in the application. \n
The ``Main_App`` emits ``S_advanced_mode_changed`` when ``ToggleAdvancedMode`` is called. \n
"Dangerous" functions and "rarely used" should only be accessible if the advanced mode is on.
- "Dangerous": Dev-functions and anything that a user should not accidentely press.
- "rarely used": Anything that is rarely used and would clutter up the UI. \n
The advanced mode can also be used to determine the behaviour of certain function:
- off: Functionality is easy to use but is limited to the most frequent use cases
- on: User has full control over behaviour (which makes the controls more complex and time consuming) \n
This can also be used to control the displayed information:
- off: Only relevant information is shown
- on: All information is shown (but the GUI is flooded with text)
"""
return QtWidgets.QApplication.instance().advanced_mode
def App() -> QtWidgets.QApplication:
"""Convenient shortcut for ``QtWidgets.QApplication.instance()``"""
return QtWidgets.QApplication.instance()
#endregion
#region Application
# ---------------------------------- Main Application ----------------------------------
AltModifier = QtCore.Qt.AltModifier
ControlModifier = QtCore.Qt.ControlModifier
GroupSwitchModifier = QtCore.Qt.GroupSwitchModifier
ShiftModifier = QtCore.Qt.ShiftModifier
MetaModifier = QtCore.Qt.MetaModifier
class Main_App(QtWidgets.QApplication):
"""
This class is the core of AGeLib. \n
Methods beginning with ``r_`` are virtual templates that can be reimplemented. \n
TODO: MORE INFO
"""
#MAYBE: Make standard hotkeys optional (in case a dev wants to use these hotkeys) but write a warning that changing these is not recommended as it might confuse users that are used to the standard AGeLib Hotkeys
#
# See:
# https://doc.qt.io/qt-5/qapplication.html
# https://doc.qt.io/qt-5/qguiapplication.html
# https://doc.qt.io/qt-5/qcoreapplication.html
S_New_Notification = QtCore.pyqtSignal(NC)
S_FontChanged = QtCore.pyqtSignal()
S_ColourChanged = QtCore.pyqtSignal()
S_advanced_mode_changed = QtCore.pyqtSignal(bool)
def __init__(self, args):
self.enableHotkeys = True
super(Main_App, self).__init__(args)
self.setStyle("fusion")
sys.excepthook = trap_exc_during_debug
try:
msg = "Welcome " + getpass.getuser()
except:
msg = "Welcome"
self.LastNotificationText = msg
self.LastNotificationToolTip = msg
self.LastNotificationIcon = QtGui.QIcon()
self.MainWindow = None
self.Notification_Window = None
self.exec_Window = None
self.optionWindow = None
self.AppPalettes = {}
self.installEventFilter(self)
self.aboutToQuit.connect(self._SaveClipboard)
self.advanced_mode = False
self.setOrganizationName("Robin Albers")
self.setOrganizationDomain("https://github.com/AstusRush")
self.Notification_List = []
self._init_NCF()
self._MakeAGeLibPath()
###########################
#TODO: Load Settings like standard palette and font
#self.Palette , self.BG_Colour , self.TextColour = AGeColour.Dark()
#self.colour_Pack = (self.Palette , self.BG_Colour , self.TextColour)
self.Colour_Font_Init()
self.ModuleVersions = "Python %s\nAGeLib %s\nSymPy %s\nNumpy %s\nMatplotLib %s\nPyQt %s (Qt %s)" % ("%d.%d" % (sys.version_info.major, sys.version_info.minor),
version,
sympy.__version__,
numpy_version,
matplotlib.__version__,
QtCore.PYQT_VERSION_STR, QtCore.qVersion())
self.r_init_Options()
def setMainWindow(self, TheWindow):
"""
This method allows you to declare the primary window of your application. \n
You can use ``self.MainWindow`` to access it. \n
Setting a main window is not obligatory and does nothing on its own. \n
The intention behind declaring a main window is to make the code more readable
and to provide a convenient way to refer to it. \n
This can also be useful if a function needs to access the main window in an application where the main window changes.
"""
self.MainWindow = TheWindow
#def notify(self, obj, event): # Reimplementation of notify that does nothing other than redirecting to normal implementation for now...
#try:
# return super().notify(obj, event)
#except:
# ExceptionOutput(sys.exc_info())
# print("Caught: ",obj,event)
# return False
def eventFilter(self, source, event):
if event.type() == 6 and self.enableHotkeys: # QtCore.QEvent.KeyPress
if event.key() == QtCore.Qt.Key_F12:
if self.AGeLibPathOK:
name = self.applicationName()
nameValid = ""
for i in name:
if i in string.ascii_letters + string.digits + "~ -_.":
nameValid += i
nameValid = nameValid.replace(" ","")
Filename = nameValid + "-" + cTimeFullStr("-") + ".png"
Filename = os.path.join(self.ScreenshotFolderPath,Filename)
try:
try:
WID = source.window().winId()
screen = source.window().screen()
except:
WID = source.winId()
screen = source.screen()
screen.grabWindow(WID).save(Filename)
print(Filename)
except:
NC(msg="Could not save Screenshot",exc=sys.exc_info(),func="Main_App.eventFilter",input=Filename)
else:
NC(3,"Screenshot of currently active window saved as:\n"+Filename,func="Main_App.eventFilter",input=Filename)
else:
print("Could not save Screenshot: Could not validate save location")
NC(1,"Could not save Screenshot: Could not validate save location",func="Main_App.eventFilter",input=self.AGeLibPath)
return True
if event.modifiers() == ControlModifier:
if event.key() == QtCore.Qt.Key_0: # FEATURE: HelpWindow: Inform the User that this feature exists. Make Help window that is opened with F1
for w in self.topLevelWidgets():
if w.isVisible():
w.positionReset()
return True
if event.key() == QtCore.Qt.Key_T:
self.Show_exec_Window()
return True
if event.modifiers() == AltModifier:
if event.key() == QtCore.Qt.Key_A:
self.ToggleAdvancedMode(not self.advanced_mode)
return True
elif event.key() == QtCore.Qt.Key_O:
self.Show_Options()
return True
elif event.type() == NotificationEvent.EVENT_TYPE:
self._NotifyUser(event.N)
return True
return super(Main_App, self).eventFilter(source, event)
def _SaveClipboard(self):
"""
On MS Windows this method ensures that the clipboard is kept:\n
The contents of the clipboard are only stored as references.
When you copy text from an application it can be pasted in all other applications
but as soon as you close the application the reference is no longer valid and the clipboard is empty. \n
Note: This is not a problem if the user has a clipboard manager as they don't use references but instead copy the data. \n
On MS Windows this method writes the text into the clipboard.
On other platforms it gives the clipboard manager an additional chance to copy the data. \n
This method is called automatically when the application exits and does not need to be called manually
except if you expect your program to crash regularly and want to ensure that the clipboard is not lost
on systems that have no active clipboard manager.
"""
clipboard = Qt.QApplication.clipboard()
if platform.system() == 'Windows':
try:
import win32clipboard
text = clipboard.text()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
except:
print("Could not save clipboard data:")
ExceptionOutput(sys.exc_info())
else: #FEATURE: Find a linux version of win32clipboard
print("Clipboard is only saved if a clipboard manager is installed due to OS limitations.")
event = QtCore.QEvent(QtCore.QEvent.Clipboard)
Qt.QApplication.sendEvent(clipboard, event)
self.processEvents()
def ToggleAdvancedMode(self, checked):
"""
This function changes the state of the advanced mode to ``checked``. \n
``S_advanced_mode_changed`` is emitted and the checkbox ``AdvancedCB`` of all ``TopBar_Widget``'s is updated. \n
Do not change ``advanced_mode`` manually!!! Always use this function!
"""
try:
self.advanced_mode = checked
for w in self.topLevelWidgets():
for i in w.findChildren(TopBar_Widget):
if i.IncludeAdvancedCB:
i.AdvancedCB.setChecked(self.advanced_mode)
self.S_advanced_mode_changed.emit(self.advanced_mode)
except:
NC(1,"Exception while toggling advanced mode",exc=sys.exc_info(),func="Main_App.ToggleAdvancedMode",input="{}: {}".format(str(type(checked)),str(checked)))
# ---------------------------------- Colour and Font ----------------------------------
def Recolour(self, Colour = "Dark"):
"""
Applies a colour scheme: \n
This method takes the name (string) of a colour scheme. \n
First AGeColour (standard AGeLib colours) and CustomColourPalettes (user created colours) are (re-)imported and their dictionaries are loaded. \n
Then the AGeColour dict is searched for the name. If it is not found the dict of CustomColourPalettes is searched. AppPalettes is searched last. \n
As soon as the name is found the colourpalette is applied (by calling _Recolour). \n
Please note: \n
If you have code that needs to run after the palette has changed (like applying colours to specific widgets) reimplement ``r_Recolour``. \n
``r_Recolour`` is called by ``_Recolour`` after the new palette has been applied. \n
Furthermore the signal ``S_ColourChanged`` is emitted after ``_Recolour``. \n
To add custom colour palettes for your application use the method ``AddPalette``. \n \n
COLOURS
===========
+ ``Palette1``, ``Palette2`` and ``Palette3`` and full QPalettes that can be used to colour different ports of the UI. Use ``r_Recolour`` to apply these Palettes to widgets.
``Palette`` is deprecated and only accessible for compatibility reasons! It will be removed in future versions!
+ ``BG_Colour`` and ``TextColour`` can be used to colour different parts that are incompatible with QPalettes.
These are tuples with 3 floats between 0 and 1 that specify RGB values and are taken from the Base and Text colours from Palette1.
+ ``PenColours`` is a dict containing QBrushes. Use ``.color()`` to access the QColor.
The colours in this dict are visually distinct from the background (and don't necessarily correspond to their name).
These colours should be used for graphs (and are automatically set as the numpy colour cycle), pen colours for editors,
player colours for games and all other cases where visually distinct colours are needed.
+ ``NotificationColours`` is a dict that contains the colours for the notification flashes but can also be used for similar purposes like highlighting text.
+ ``MiscColours`` is a dict for all other colour needs. It contains some basic colours that are labelled for games but I encourage creative interpretation!
The colours that are labelled for rarity for example could also be used to colourcode a dataset regarding the importance of the values:
Common values are coloured as common and rare values that need attention are coloured as rare. \n
These dicts are subclassed to ensure that a bracket access (dict["key"]) on an invalid key returns a random colour instead of raising an exception to allow expansion.
However it is not advisable to expand these dicts at the moment. This colour system is still WIP and might change in the future.
"""
try:
try:
importlib.reload(AGeColour)
except:
NC(2,"Could not reload AGeColour",exc=sys.exc_info(),func="Main_App.Recolour",input=str(Colour))
try:
spec = importlib.util.spec_from_file_location("CustomColourPalettes", os.path.join(self.AGeLibSettingsPath,"CustomColourPalettes.py"))
CustomColours = importlib.util.module_from_spec(spec)
spec.loader.exec_module(CustomColours)
#CustomColours.MyClass()
except:
NC(4,"Could not load custom colours",exc=sys.exc_info(),func="Main_App.Recolour",input=str(Colour))
try:
self._Recolour(*AGeColour.Colours[Colour]())
except:
try:
self._Recolour(*CustomColours.Colours[Colour]())
except:
self._Recolour(*self.AppPalettes[Colour]())
except:
NC(1,"Exception while loading colour palette",exc=sys.exc_info(),func="Main_App.Recolour",input=str(Colour))
def AddPalette(self, name, palette):
"""
Use this method to add custom colour palettes. (They are saved in the dict ``AppPalettes``.) \n
``name`` should be a string and ``palette`` must be a function that returns the palette. \n
Please note that the users custom colours take priority over application palettes
thus you need to add a tag in front of your names that no user would ever use
(for example your application name in square brackets (like ``[AMaDiA] Dark``)). \n
The tag must be unique enough to ensure that no user would ever use it in a custom name!
"""
self.AppPalettes[name] = palette
def _Recolour(self, Palette1, Palette2, Palette3, PenColours, NotificationColours, MiscColours):
"""
This method is called by ``Recolour`` to apply the colour palette. \n
For all colour palette changes ``Recolour`` should be used. \n
If you have code that needs to run after the palette has changed (like applying colours to specific widgets) reimplement ``r_Recolour``.
"""
self.Palette = Palette1 #TODO: Remove self.Palette
self.Palette1 = Palette1
self.Palette2 = Palette2
self.Palette3 = Palette3
self.PenColours = ColourDict()
self.PenColours.copyFromDict(PenColours)
self.NotificationColours = ColourDict()
self.NotificationColours.copyFromDict(NotificationColours)
self.MiscColours = ColourDict()
self.MiscColours.copyFromDict(MiscColours)
Colour = self.Palette1.color(QtGui.QPalette.Active,QtGui.QPalette.Base)
self.BG_Colour = (Colour.red()/255,Colour.green()/255,Colour.blue()/255)
Colour = self.Palette1.color(QtGui.QPalette.Active,QtGui.QPalette.Text)
self.TextColour = (Colour.red()/255,Colour.green()/255,Colour.blue()/255)
self.colour_Pack = (self.Palette , self.BG_Colour , self.TextColour) #TODO: remove self.colour_Pack
self.setPalette(self.Palette)
QtWidgets.QToolTip.setPalette(self.Palette)
self._update_NCF()
c=[]
for v in self.PenColours.values():
c.append(v.color().name(0))
self.mplCycler = matplotlib.cycler(color=c)
matplotlib.rcParams['axes.prop_cycle'] = self.mplCycler
for w in self.topLevelWidgets():
for i in w.findChildren(MplWidget):
i.SetColour(self.BG_Colour, self.TextColour, self.mplCycler)
#for i in w.findChildren(Window_Frame_Widget):
# i.setPalette(FramePalette)
self.r_Recolour()
self.S_ColourChanged.emit()
def r_Recolour(self):
"""
This method is called after the colour palette has changed. \n
All GUI elements usually use the palette of the application but if the method ``setPalette`` is called
the element looses the ability to inherit from the Application and needs special treatment. \n
Reimplement this method to provide such special treatment. \n
For example ``Palette2`` and ``Palette3`` should only be applied to widgets in this method! \n
Furthermore everything that uses ``PenColours``, ``NotificationColours`` or ``MiscColours`` should be updated here or by connecting a custom function to ``S_ColourChanged``.
"""
pass
def Colour_Font_Init(self):
# TODO: Accept more arguments for FontFamily, PointSize and colour Palette Name and use defaults if none were given or if something went wrong while applying them
self.FontFamily = "Arial"
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
self.setFont(font)
self.Recolour()
# Always keep Statusbar Font small
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
for w in self.topLevelWidgets():
for i in w.findChildren(QtWidgets.QStatusBar):
try:
i.setFont(font)
except common_exceptions:
ExceptionOutput(sys.exc_info())
def SetFont(self, Family=None, PointSize=0, source=None, emitSignal=True):
"""
Changes the font to ``Family`` and the font size to ``PointSize`` for the entire application. \n
``Family``: QFont, string or None (None keeps old family and only changes font size) \n
``PointSize``: int, if 0 ans ``Family`` is QFont the pointsize of QFont is used. \n
``source`` : The window from which the font was changed \n
If ``PointSize`` is less than 5 the value from the Font_Size_spinBox of ``source`` will be taken. If this fails it defaults to 9. \n
``emitSignal``: If True (default) ``S_FontChanged`` is emitted after the new font is applied. \n\n
Furthermore the Font_Size_spinBox of all windows is updated with the new value (the signals of Font_Size_spinBox are blocked during the update).\n
All ``TopBar_Widget``s are resized. \n
The fontsize of all statusbars is always kept at 9 but the font family is updated.
"""
if type(Family) == QtGui.QFont:
if PointSize==0:
PointSize = Family.pointSize()
Family = Family.family()
self.FontFamily = Family
elif Family == None:
Family = self.FontFamily
else:
self.FontFamily = Family
if type(PointSize) == str:
PointSize = int(PointSize)
if PointSize < 5:
try:
PointSize = source.TopBar.Font_Size_spinBox.value()
except common_exceptions:
try:
NC(msg="Could not read Font_Size_spinBox.value()",exc=sys.exc_info(),func="Main_App.SetFont",win=source.windowTitle())
except common_exceptions:
NC(msg="Could not read Font_Size_spinBox.value()",exc=sys.exc_info(),func="Main_App.SetFont")
PointSize = 9
if type(PointSize) != int:
print(type(PointSize)," is an invalid type for font size (",PointSize,")")
try:
NC(msg="{} is an invalid type for font size ({})".format(str(type(PointSize)),str(PointSize)),exc=sys.exc_info(),func="Main_App.SetFont",win=source.windowTitle())
except:
NC(msg="{} is an invalid type for font size ({})".format(str(type(PointSize)),str(PointSize)),exc=sys.exc_info(),func="Main_App.SetFont")
PointSize = 9
for w in self.topLevelWidgets():
for i in w.findChildren(TopBar_Widget):
try:
if i.IncludeFontSpinBox:
# setValue emits ValueChanged and thus calls ChangeFontSize if the new Value is different from the old one.
# If the new Value is the same it is NOT emitted.
# To ensure that this behaves correctly either way the signals are blocked while changing the Value.
i.Font_Size_spinBox.blockSignals(True)
i.Font_Size_spinBox.setValue(PointSize)
i.Font_Size_spinBox.blockSignals(False)
except common_exceptions:
ExceptionOutput(sys.exc_info())
font = QtGui.QFont()
font.setFamily(Family)
font.setPointSize(PointSize)
self.setFont(font)
for w in self.topLevelWidgets():
for i in w.findChildren(TopBar_Widget):
try:
if type(i.parentWidget()) == MMenuBar:
i.setMinimumHeight(i.parentWidget().minimumHeight())
elif type(i.parentWidget()) == QtWidgets.QTabWidget:
i.setMinimumHeight(i.parentWidget().tabBar().minimumHeight())
except common_exceptions:
ExceptionOutput(sys.exc_info())
# Always keep Statusbar Font small
font = QtGui.QFont()
font.setFamily(Family)
font.setPointSize(9)
for w in self.topLevelWidgets():
for i in w.findChildren(QtWidgets.QStatusBar):
try:
i.setFont(font)
except common_exceptions:
ExceptionOutput(sys.exc_info())
if emitSignal:
self.S_FontChanged.emit()
# ---------------------------------- Notifications ----------------------------------
def _init_NCF(self): # Notification_Flash
"""
NO INTERACTION NEEDED \n
Initiates the notification flash animations. This method is called automatically.
"""
self.NCF_NONE = QtCore.QPropertyAnimation(self)
self.NCF_r = QtCore.QPropertyAnimation(self,b'FLASH_colour')
self.NCF_r.setDuration(1000)
self.NCF_r.setLoopCount(1)
#self.NCF_r.finished.connect(self._NCF_Finished)
self.NCF_y = QtCore.QPropertyAnimation(self,b'FLASH_colour')
self.NCF_y.setDuration(1000)
self.NCF_y.setLoopCount(1)
#self.NCF_y.finished.connect(self._NCF_Finished)
self.NCF_g = QtCore.QPropertyAnimation(self,b'FLASH_colour')
self.NCF_g.setDuration(1000)
self.NCF_g.setLoopCount(1)
#self.NCF_g.finished.connect(self._NCF_Finished)
self.NCF_b = QtCore.QPropertyAnimation(self,b'FLASH_colour')
self.NCF_b.setDuration(1000)
self.NCF_b.setLoopCount(1)
#self.NCF_b.finished.connect(self._NCF_Finished)
def _update_NCF(self):
"""
NO INTERACTION NEEDED \n
Updates the notification flash animations. This method is called automatically.
"""
self.NCF_r.setStartValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_r.setEndValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_r.setKeyValueAt(0.5, self.NotificationColours["Error"].color())
self.NCF_y.setStartValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_y.setEndValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_y.setKeyValueAt(0.5, self.NotificationColours["Warning"].color())
self.NCF_g.setStartValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_g.setEndValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_g.setKeyValueAt(0.5, self.NotificationColours["Message"].color())
self.NCF_b.setStartValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_b.setEndValue(self.Palette.color(QtGui.QPalette.Window))
self.NCF_b.setKeyValueAt(0.5, self.NotificationColours["Notification"].color())
def _set_FLASH_colour(self, col): # Handles changes to the Property FLASH_colour
"""
NO INTERACTION NEEDED \n
Helpfunction that handles changes to the Property FLASH_colour.
"""
palette = self.Palette
palette.setColor(QtGui.QPalette.Window, col)
self.setPalette(palette)
FLASH_colour = QtCore.pyqtProperty(QtGui.QColor, fset=_set_FLASH_colour) # Defines the Property FLASH_colour
#def _NCF_Finished(self):
# """
# This method is called when a notification flash animation is finished. \n
# """
# pass#self.TopBar_Error_Label.setFrameShape(QtWidgets.QFrame.NoFrame)
def _NotifyUser(self, N):
"""
NO INTERACTION NEEDED \n
Displays the notification ``N`` to the user. \n
This method should not be used manually!
"""
if N.l() == 0:
return
elif N.l()!=4 or self.advanced_mode:
Error_Text_TT,icon = self._ListVeryRecentNotifications(N)
self.LastNotificationText = N.DPS()
self.LastNotificationToolTip = Error_Text_TT
self.LastNotificationIcon = icon
for w in self.topLevelWidgets():
for i in w.findChildren(TopBar_Widget):
if i.IncludeErrorButton:
i.Error_Label.setText(N.DPS())
i.Error_Label.setToolTip(Error_Text_TT)
i.Error_Label.setIcon(icon)
if (not N.Flash == self.NCF_NONE) and (not N.Flash == None):
N.Flash.start()
self.Notification_List.append(N)
self.S_New_Notification.emit(N)
# Allow the button to adjust to the new text:
for w in self.topLevelWidgets():
for i in w.findChildren(TopBar_Widget):
if i.IncludeErrorButton:
i.parentWidget().adjustSize()
# REMINDER: Somewhere you need to make the error message "Sorry Dave, I can't let you do this."
def _ListVeryRecentNotifications(self, N):
"""
NO INTERACTION NEEDED \n
This helpfunction is used by _NotifyUser to generate the tooltip for the notification button.
"""