/
hslWindow.py
2386 lines (1703 loc) · 84.1 KB
/
hslWindow.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
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QFrame,
QSplitter, QStyleFactory, QTableWidget,
QTableWidgetItem, QPushButton, QAbstractItemView,
QCheckBox, QMainWindow, QAction, QMenu, QFileDialog,
QMessageBox, QTabWidget, QPlainTextEdit, QInputDialog,
QApplication, QDialog
)
from PyQt5.QtGui import QPainter, QIcon, QDesktopServices
from PyQt5.QtCore import Qt, QUrl, QEvent, QRect, QProcess, QThread
from yaml import safe_load, dump, YAMLError #pip install pyyaml
import kpiTable, hostsTable
import chartArea
import configDialog, aboutDialog
import dpDBCustom
import dpTrace
import dpDummy
import dpDB
from dbi import dbi
import sqlConsole
import datetime
from indicator import indicator
from utils import resourcePath
from utils import loadConfig
from utils import log, deb
from utils import cfg
from utils import Layout
from utils import dbException, msgDialog
from SQLBrowserDialog import SQLBrowserDialog
import utils
import customSQLs
import kpiDescriptions
import sys, os
import time
from _constants import build_date, version
from updatesCheck import checkUpdates
from csvImportDialog import csvImportDialog
import highlight
import presetsDialog
from passwordDialog import pwdDialog
from profiler import profiler
class hslWindow(QMainWindow):
statusbar = None
primaryConf = None # primary connection dictionary, keys: host, port, name, dbi, user, pwd, etc
configurations = {}
kpisTable = None
threadID = None
def __init__(self):
self.layoutDumped = False
self.sqlTabCounter = 0 #static tab counter
self.tabs = None
self.kpisSave = {} # list of kpis for quick save/restore
super().__init__()
self.threadID = int(QThread.currentThreadId())
log(f'[thread] main window thread: {self.threadID}', 5)
self.initUI()
highlight.loadHighlights()
if cfg('updatesCheckInterval', '7'):
if self.layout is not None:
checkUpdates(self, self.updatesCB, self.layout.lo.get('updateNextCheck'), self.layout.lo.get('updateVersionCheck'))
# def tabChanged(self, newidx):
def updatesCB(self, status, buildDate = None):
interval = cfg('updatesCheckInterval', '7')
if interval:
try:
interval = int(interval)
except ValueError:
log('[!] unexpected updateCheckInterval: %s' % str(interval), 2)
interval = 7
else:
interval = 7
log('Updates callback, status: [%s]' % status, 4)
today = datetime.datetime.now().date()
'''
if 'updateVersionCheck' in self.layout.lo:
self.layout.lo.pop('updateVersionCheck')
'''
if 'updateNextCheck' in self.layout.lo:
self.layout.lo.pop('updateNextCheck')
if status in (''):
self.layout['updateNextCheck'] = today + datetime.timedelta(days=interval)
elif status == 'ignoreWeek':
self.layout['updateNextCheck'] = today + datetime.timedelta(days=7)
elif status == 'ignoreYear':
self.layout['updateNextCheck'] = today + datetime.timedelta(days=365)
elif status == 'ignoreVersion':
self.layout['updateNextCheck'] = today + datetime.timedelta(days=interval)
self.layout['updateVersionCheck'] = buildDate
self.layout.dump()
def closeTab(self):
indx = self.tabs.currentIndex()
if indx > 0: #print need a better way to identify sql consoles...
cons = self.tabs.currentWidget()
cons.delayBackup()
abandone = False
if cons.sqlRunning:
tabname = cons.tabname.rstrip(' *')
log(f'CloseTab: Seems the sql still running in {tabname}, need to show a warning', 4)
answer = utils.yesNoDialog('Warning', 'It seems the SQL is still running.\n\nAre you sure you want to close the console and abandon the execution?')
if not answer:
return False
else:
abandone = True
status = cons.close(abandoneExecution=abandone)
if status == True:
self.statusbar.removeWidget(cons.indicator)
self.tabs.removeTab(indx)
def switchTab(self, index):
self.tabs.setCurrentIndex(index)
def keyPressEvent(self, event):
#log('window keypress: %s' % (str(event.key())))
modifiers = event.modifiers()
if (modifiers == Qt.ControlModifier and event.key() == 82) or event.key() == Qt.Key_F5:
log('reload request!')
self.chartArea.reloadChart()
elif modifiers == Qt.AltModifier and Qt.Key_0 < event.key() <= Qt.Key_9:
self.switchTab(event.key() - Qt.Key_1)
elif modifiers == Qt.ControlModifier and event.key() == Qt.Key_W:
self.closeTab()
elif modifiers == Qt.ControlModifier and event.key() == Qt.Key_L:
self.chartArea.widget.toggleLegend()
elif modifiers == Qt.ControlModifier and event.key() == Qt.Key_L:
self.chartArea.widget.toggleLegend()
elif event.key() == Qt.Key_L and modifiers & Qt.ControlModifier and modifiers & Qt.ShiftModifier:
self.chartArea.widget.toggleGanttLabels()
else:
super().keyPressEvent(event)
def statusMessage(self, message, repaint):
if not self.statusbar:
log('self.statusbar.showMessage(''%s'')' % (message))
else:
self.statusbar.showMessage(message)
if repaint:
self.repaint()
def closeEvent(self, event):
if hasattr(profiler, 'report'):
profiler.report()
if cfg('dev'):
utils.configReportStats()
log('Exiting...')
if cfg('saveLayout', True):
self.dumpLayout()
'''
for i in range(self.tabs.count() -1, 0, -1):
w = self.tabs.widget(i)
if isinstance(w, sqlConsole.sqlConsole):
w.delayBackup()
status = w.close(False) # can not abort
clipboard = QApplication.clipboard()
event = QEvent(QEvent.Clipboard)
QApplication.sendEvent(clipboard, event)
'''
def formatKPIs(self):
'''
formats list of kpis for dumpLayout and ESS reconnection
'''
kpis = {}
for i in range(len(self.chartArea.widget.hosts)):
host = self.chartArea.widget.hosts[i]
hst = '%s:%s' % (host['host'], host['port'])
if i < len(self.chartArea.widget.nkpis) and self.chartArea.widget.nkpis[i]:
# this a list assignement we have to copy, otherwise this
# will be implicitly erased in cleanup() at it is the same list
kpis[hst] = self.chartArea.widget.nkpis[i].copy()
return kpis
def dumpLayout(self, closeTabs=True, crashMode=False, mode=None):
# def dumpLayout(self, closeTabs=True, crashMode=False, abandonFlag=None):
'''
dumps a layout.yaml
abandonFlag is a list to return abandon value if any
in normal execution it will also trigger close of the consoles (with backup and disconnection)
in crashMode (called on uncought exception) it is questionable if calling clos() makes any sense
'''
if self.primaryConf:
connection = self.primaryConf.get('name')
else:
connection = None
if self.layoutDumped:
log('self.layoutDumped', 5)
return
if self.layout is None:
log('self.layout is None', 5)
return
log('--> dumpLayout', 5)
self.layoutDumped = True
kpis = self.formatKPIs()
log('--> dumpLayout kpis: %s' % str(kpis), 5)
if len(kpis) == 0:
log('--> no KPIs... maybe check if connected at all and if not - dont reset kpis?')
if kpis:
self.layout['kpis'] = kpis
else:
if 'kpis' in self.layout.lo:
del self.layout.lo['kpis']
#log('--> dumpLayout, kpis: ' + str(kpis))
if connection:
self.layout['connectionName'] = connection
else:
if self.primaryConf:
log('[?] Not possible point', 5)
self.layout['connectionName'] = None
self.layout['pos'] = [self.pos().x(), self.pos().y()]
self.layout['size'] = [self.size().width(), self.size().height()]
if SQLBrowserDialog.layout:
self.layout['SQLBrowser.Layout'] = SQLBrowserDialog.layout
# block the position on topof the file
self.layout['mainSplitter'] = self.mainSplitter.sizes()
self.layout['kpiSplitter'] = self.kpiSplitter.sizes()
hostTableWidth = []
KPIsTableWidth = []
for i in range(self.hostTable.columnCount()):
hostTableWidth.append(self.hostTable.columnWidth(i))
for i in range(self.kpisTable.columnCount()):
KPIsTableWidth.append(self.kpisTable.columnWidth(i))
if self.chartArea.widget.legend:
self.layout['legend'] = True
else:
self.layout['legend'] = False
self.layout['hostTableWidth'] = hostTableWidth
self.layout['KPIsTableWidth'] = KPIsTableWidth
# print(self.pos().x(), self.pos().y())
tabs = []
self.layout['currentTab'] = self.tabs.currentIndex()
tabname = None
somethingRunning = False
for i in range(self.tabs.count() -1, 0, -1):
w = self.tabs.widget(i)
if w.sqlRunning:
somethingRunning = True
tabname = w.tabname.rstrip(' *')
break
abandone = False
if somethingRunning and not crashMode and mode != 'secondaryConnection':
# log('There is something running, need to show a warning', 4)
log(f'dumpLayout: Seems the sql still running in {tabname}, need to show a warning', 4)
if mode == 'reconnect':
wMessage = f'It\'s not recommended to reconnect having stuff running ({tabname})\nIt will hang untl finished anyway.\n\nProceed anyway?'
else:
wMessage = f'It seems there is something still running ({tabname}).\n\nAre you sure you want to exit and abandone the execution?'
answer = utils.yesNoDialog('Warning', wMessage)
if not answer:
self.layoutDumped = False
return False
else:
abandone = True
# if abandonFlag is not None:
# abandonFlag.append('yep')
if cfg('saveOpenTabs', True):
for i in range(self.tabs.count() -1, 0, -1):
w = self.tabs.widget(i)
if isinstance(w, sqlConsole.sqlConsole):
if not crashMode: # during the crash processing explicit backups done outside before dumpLayout call
w.delayBackup()
if w.fileName is not None or w.backup is not None:
pos = w.cons.textCursor().position()
block = w.cons.edit.verticalScrollBar().value()
if w.backup:
bkp = os.path.abspath(w.backup)
else:
bkp = None
tabs.append([w.fileName, bkp, pos, block])
if closeTabs:
log('Do the close tab sequence (for one tab)', 5)
# self.statusbar.removeWidget(w.indicator) <<< this will fail when called from the parallel thread (if smth crashed in parallel thread)
w.close(cancelPossible=False, abandoneExecution=abandone)
self.tabs.removeTab(i)
tabs.reverse()
if len(tabs) > 0:
self.layout['tabs'] = tabs
else:
if 'tabs' in self.layout.lo:
self.layout.lo.pop('tabs')
self.layout['variables'] = kpiDescriptions.vrsStr
if kpiDescriptions.Variables.width:
self.layout['variablesLO'] = {'width': kpiDescriptions.Variables.width, 'height': kpiDescriptions.Variables.height}
log('--> dumpLayout vars: %s' % str(kpiDescriptions.vrsStr), 4)
#print('dumping', self.layout['variables'])
if 'running' in self.layout.lo:
self.layout.lo.pop('running')
if kpiDescriptions.customColors:
colorsHTML = kpiDescriptions.colorsHTML(kpiDescriptions.customColors)
self.layout['customColors'] = colorsHTML
else:
if 'customColors' in self.layout.lo:
del self.layout.lo['customColors']
self.layout.dump()
return True
def menuQuit(self):
'''
for i in range(self.tabs.count() -1, 0, -1):
w = self.tabs.widget(i)
if isinstance(w, sqlConsole.sqlConsole):
status = w.close(True) # can abort
if status == True:
self.tabs.removeTab(i)
if status == False:
return
'''
log('Exit request...')
log('before dump layout', 5)
status = None
if cfg('saveLayout', True):
status = self.dumpLayout()
if status == False:
log('termination aborted....')
return
log('dump layout done', 5)
self.close()
def menuReloadCustomSQLs(self):
customSQLs.loadSQLs()
def menuHighlights(self):
c = highlight.loadHighlights()
if c is not None:
self.statusMessage(f'Highlights definition updated, {c} records loaded', True)
else:
self.statusMessage('Seems an error, check logs for details', True)
highlight.dumpHighlights()
def menuReloadCustomKPIs(self):
'''
delete and rebuild custom kpis
1st step - delete existing custom kpis from KPIs lists and KPIsStyles
2nd step - scann/add back new definitions
by the way - delete stuff from data arrays?
'''
hosts = self.chartArea.widget.hosts
## step one: remove from the existing lists
for h in range(len(hosts)):
hostKPIsStyles = self.chartArea.hostKPIsStyles[h]
hostKPIsList = self.chartArea.hostKPIsList[h]
log(f'{h}: {hostKPIsList=}')
for kpiName in list(hostKPIsStyles):
kpi = hostKPIsStyles[kpiName]
if kpi.get('sql'):
del(hostKPIsStyles[kpiName]) # delete style dict entry
hostKPIsList.remove(kpiName) # delete list entry
# del host custom groups
kpis_len = len(hostKPIsList)
i = 0
while i < kpis_len:
if hostKPIsList[i][:1] == '.' and (i == len(hostKPIsList)-1 or hostKPIsList[i+1][:1] == '.'):
del(hostKPIsList[i])
kpis_len -= 1
else:
i += 1
## load custom KPI definitions into temp structures...
# this is executed just once, data loaded into old host/port structures
# and then distributed/copied to new structures
hostKPIs = []
srvcKPIs = []
kpiStylesNN = {'host':{}, 'service':{}}
try:
dpDBCustom.scanKPIsN(hostKPIs, srvcKPIs, kpiStylesNN)
except Exception as e:
self.chartArea.disableDeadKPIs()
msgDialog('Custom KPIs Error', 'There were errors during custom KPIs load. Load of the custom KPIs STOPPED because of that.\n\n' + str(e))
# now append detected custom KPIs back into lists
for h in range(len(hosts)):
hostKPIsStyles = self.chartArea.hostKPIsStyles[h]
hostKPIsList = self.chartArea.hostKPIsList[h]
if hosts[h]['port'] == '':
hostKPIsList += hostKPIs
for kpiName in kpiStylesNN['host'].keys():
hostKPIsStyles[kpiName] = kpiStylesNN['host'][kpiName]
else:
hostKPIsList += srvcKPIs
for kpiName in kpiStylesNN['service'].keys():
hostKPIsStyles[kpiName] = kpiStylesNN['service'][kpiName]
#not really sure if this one can be called twice...
kpiDescriptions.clarifyGroups(hostKPIsStyles)
log(f'{h}: {hostKPIsList=}')
self.chartArea.widget.initPens()
self.chartArea.widget.update()
#trigger refill
log('refill due to menuReloadCustomKPIs ', 5)
self.kpisTable.refill(self.hostTable.currentRow())
self.statusMessage('Custom KPIs reload finish', False)
def menuReloadConfig(self):
loadConfig()
utils.initGlobalSettings()
self.statusMessage('Configuration file reloaded.', False)
def menuLayoutRestore(self):
size = self.layout['save_size']
spl = self.layout['save_mainSplitter']
pos = self.layout['save_pos']
if pos and spl and size:
self.move(pos[0], pos[1])
self.resize(size[0], size[1])
self.mainSplitter.setSizes(spl)
# def menuPresetRestore(self, preset):
# '''generates function for specific preset restore call'''
# def f(self):
# log(f'Restore preset: {preset}', 3)
# self.menuPresetRestore(preset)
# deb(self)
# f.preset = preset
# f.self = self
# return f
def presetProxy(self, preset):
'''preset factory to hardcode preset as menu callback cannot provide any context'''
def f():
self.menuKPIsRestorePreset(preset)
return f
def menuPresetPopulate(self):
self.presetsSubMenu.clear()
presetNames = presetsDialog.presets.list()
if presetNames:
for preset in presetNames:
presetAct = QAction(preset, self)
presetAct.triggered.connect(
# lambda p = preset: self.menuKPIsRestorePreset(p)
# lambda p=preset: self.presetProxy(preset)
self.presetProxy(preset)
)
self.presetsSubMenu.addAction(presetAct)
else:
noPresets = QAction('No presets', self)
self.presetsSubMenu.addAction(noPresets)
def menuKPIsRestorePreset(self, presetName):
'''restore preset based on name'''
preset = presetsDialog.presets.get(presetName)
log(f'Extracting preset: {presetName}', 4)
if not preset:
log(f'[w] no preset? {presetName} --> {preset}', 2)
return
hostWithKpis = None
for hi in range(len(self.chartArea.widget.hosts)):
host = self.chartArea.widget.hosts[hi]
hname = f"{host['host']}:{host['port']}"
if hname in preset:
kpisList = preset[hname]
kpis = []
for kpisVar in kpisList:
if type(kpisVar) == list and len(kpisVar) == 2:
kpi, vars = kpisVar[0], kpisVar[1]
kpiStyles = self.chartArea.widget.hostKPIsStyles[hi]
style = kpiStyles.get(kpi)
if style:
idx = style.get('sql')
if idx:
log(f'set variables: {idx} -> {vars}', 4)
kpiDescriptions.addVars(idx, vars, True) # update variables
else:
log(f'[w] no idx for existing variables?', 2)
else:
kpi = kpisVar
vars = None
kpis.append(kpi)
if kpis:
log(f'Restoring: {hname} --> {kpis}', 5)
self.chartArea.widget.nkpis[hi] = kpis
if hostWithKpis is None:
hostWithKpis = hi # remmember host to switch to after restore
else:
log(f'Restoring 1: {hname} --> []', 5)
self.chartArea.widget.nkpis[hi].clear()
else:
log(f'Restoring 2: {hname} --> []', 5)
self.chartArea.widget.nkpis[hi].clear()
if hostWithKpis is None:
hostWithKpis = self.hostTable.currentRow()
self.hostTable.setCurrentCell(hostWithKpis, 0)
self.kpisTable.refill(hostWithKpis)
def menuKPIsRestore(self):
'''Restore enabled kpis from local quick list stored before '''
if len(self.kpisSave) == 0:
self.statusMessage('There are no KPIs saved, use Layout -> Save KPIs first', True)
for hi in range(len(self.chartArea.widget.hosts)):
host = self.chartArea.widget.hosts[hi]
hname = f"{host['host']}:{host['port']}"
if hname in self.kpisSave:
log(f'Restoring: {hname} --> {self.kpisSave[hname]}', 5)
self.chartArea.widget.nkpis[hi] = self.kpisSave[hname]
else:
log(f'Restoring: {hname} --> []', 5)
self.chartArea.widget.nkpis[hi].clear()
def menuPresersManage(self):
dialog = presetsDialog.PresetsDialog(self, None)
rslt = dialog.exec_()
if rslt == QDialog.Accepted:
self.menuPresetPopulate()
else:
log('manage presets cancel, do reload...', 4)
presetsDialog.presets = presetsDialog.Presets()
def menuKPIsSave(self):
self.kpisSave = {}
hostPreset = {}
hn = -1
for host, kpis in zip(self.chartArea.widget.hosts, self.chartArea.widget.nkpis):
hn +=1
if not kpis:
continue
hname = f"{host['host']}:{host['port']}"
print('-->', hname)
if cfg('presetVariables', True) == False:
# old style: no variables
self.kpisSave[hname] = kpis.copy()
continue
# build variables
kpisVars = []
for kpi in kpis:
kpiStyles = self.chartArea.widget.hostKPIsStyles[hn]
style = kpiStyles[kpi]
vars = None
idx = style.get('sql')
if idx:
vars = kpiDescriptions.vrsStr.get(idx)
if vars is None:
kpisVars.append(kpi) # no vars - single value
else:
kpisVars.append([kpi, vars]) # tuple --> list because of yaml dump()/safe_load issues
hostPreset[hname] = kpisVars
preset = presetsDialog.PresetsDialog(self, preset=hostPreset)
rslt = preset.exec_()
if rslt == QDialog.Accepted:
self.menuPresetPopulate()
else:
pass
def menuLayout(self):
self.layout['save_size'] = [self.size().width(), self.size().height()]
self.layout['save_pos'] = [self.pos().x(), self.pos().y()]
self.layout['save_mainSplitter'] = self.mainSplitter.sizes()
self.statusMessage('Layout saved', False)
def menuFont(self):
id = QInputDialog
sf = cfg('fontScale', 1)
sf, ok = id.getDouble(self, 'Input the scaling factor', 'Scaling Factor', sf, 0, 5, 2)
if ok:
self.chartArea.widget.calculateMargins(sf)
self.chartArea.adjustScale(sf)
def menuAbout(self):
abt = aboutDialog.About(self)
abt.exec_()
def menuSQLFolder(self):
prc = QProcess()
prc.startDetached('explorer.exe', [cfg('scriptsFolder', 'scripts')])
def menuSQLBrowser(self):
def extractFile(filename):
try:
with open(file) as f:
txt = f.read()
except Exception as e:
txt = '-- [E]: ' + str(e)
return txt
(result, file, offset) = SQLBrowserDialog.getFile(self)
tabIndex = self.tabs.currentIndex()
w = self.tabs.widget(tabIndex)
if result == 'open' or (file and not isinstance(w, sqlConsole.sqlConsole)):
# chart tab is actually PyQt5.QtWidgets.QSplitter, it does not have proper class on top
console = self.newConsole(generateName=True)
txt = extractFile(file)
console.cons.insertTextS(txt)
cursor = console.cons.textCursor()
if offset:
cursor.setPosition(offset, cursor.MoveAnchor)
else:
cursor.setPosition(0, cursor.MoveAnchor)
console.cons.setTextCursor(cursor)
elif result == 'edit':
self.newConsole(filename=file, generateName=False)
elif result == 'insert':
if isinstance(w, sqlConsole.sqlConsole):
txt = extractFile(file)
if len(txt) >= 2:
if txt[-1] == '\n' and txt[-2] != '\n':
txt += '\n'
elif txt[-1] != '\n':
txt += '\n\n'
pos = w.cons.textCursor().position()
w.cons.insertTextS(txt)
if offset:
pos += offset
cursor = w.cons.textCursor()
cursor.setPosition(pos, cursor.MoveAnchor)
w.cons.setTextCursor(cursor)
else:
self.statusMessage('Warning: SQL Console needs to be open to use this option.', True)
def menuVariablesHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/variables'))
def menuVariables(self):
# detect the sql source for currently selected custom KPI if any
idx = None
h = self.hostTable.currentRow()
kpi = self.kpisTable.currentRow()
if h >= 0 and kpi >= 0 and kpi < len(self.kpisTable.kpiNames):
kpiName = self.kpisTable.kpiNames[kpi]
ht = kpiDescriptions.hType(h, self.chartArea.widget.hosts)
if kpiName in kpiDescriptions.kpiStylesNN[ht]:
idx = kpiDescriptions.kpiStylesNN[ht][kpiName].get('sql')
# pass this value to be selected in variables UI
vrs = kpiDescriptions.Variables(self, idx)
vrs.exec_()
if h >= 0:
log('refill due to menuVariables ', 5)
self.kpisTable.refill(h)
def menuCSV(self):
'''
show the CSV import dialog in modal mode
DBI is to be managed outside (here) connection to me banaged inside (there
'''
validDPs = [] # list of data providers with dpDB type, others are not suitable for import
for dp in self.chartArea.ndp:
if type(dp) == dpDB.dataProvider:
validDPs.append(dp)
if not validDPs:
if datetime.datetime.now().second % 17 == 0:
motivation = 'Stay safe, smile once in a while, It\'s not so bad.'
else:
motivation = 'Stay safe.'
msgDialog('No database connection', 'You need to open connection to the database first.\n\n'+motivation, parent=self)
return
csvImport = csvImportDialog(parent=self, ndp=validDPs)
csvImport.exec_()
csvWidth = csvImport.size().width()
csvHeight = csvImport.size().height()
self.layout['csvImportLO'] = {'width': csvWidth, 'height': csvHeight}
log('csvImport done')
def menuSQLHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/sqlconsole'))
def menuDocHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/doc'))
def menuConfHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/config'))
def menuChangelogHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/changelog'))
def menuCustomConfHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/customKPI'))
def menuContextSQLsConfHelp(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/contextSQLs'))
def menuTips(self):
QDesktopServices.openUrl(QUrl('https://www.rybafish.net/tips'))
def menuDummy(self):
dp = dpDummy.dataProvider() # generated data
dpidx = self.chartArea.appendDP(dp)
if cfg('saveKPIs', True):
self.chartArea.initDP(dpidx, self.layout['kpis'])
else:
self.chartArea.initDP(dpidx)
def menuConfig(self):
self.processConnection()
def menuConfigSecondary(self):
self.processConnection(secondary=True)
def updateWindowTitle(self):
dp = None
conf = self.primaryConf
if self.chartArea.ndp:
dp = self.chartArea.ndp[0]
if conf is None and dp is None: # normally, only on start
self.setWindowTitle('RybaFish Charts [%s]' % version)
return
if dp is None:
dp = {} # safity first
sid = dp.dbProperties.get('sid', '')
if conf:
user = conf.get('user', '') + '@' + sid
else:
user = ''
tenant = dp.dbProperties.get('tenant')
if tenant and conf:
windowStr = ('%s %s@%s' % (conf.get('user'), tenant, sid))
else:
if tenant:
windowStr = tenant
else:
windowStr = user
dbver = dp.dbProperties.get('version')
if dbver:
windowStr += ', ' + dbver
windowStr += ' - ' + version
if self.chartArea.widget.timeZoneDelta:
tz = ' time: ' + utils.secondsToTZ(self.chartArea.widget.timeZoneDelta)
else:
tz = ''
self.setWindowTitle(f'RybaFish Charts [{windowStr}]{tz}')
def processConnection(self, secondary=False):
'''
shows the connection dialog and triggers connection
both primary and secondary
!! it will redifine self.primaryConnection configuration if not secondary
initial connection shown in the dialog will be based on self.primaryConf
if not yet connected in this session - primaryConnection loaded from layout.yaml
'''
log(f'processConnection, {secondary=}')
conf = None
if secondary:
connConf = None
else:
if self.primaryConf is None:
connConf = cfg('server')
else:
connConf = self.primaryConf
if not connConf:
connConf = {}
if not connConf.get('name') and self.layout and not secondary:
connConf['setToName'] = self.layout['connectionName']
conf, ok = configDialog.Config.getConfig(connConf, self)
conf['usage'] = None
if ok and not secondary:
self.primaryConf = conf.copy()
if cfg('dev') and False:
log(f'after connection dialog {connConf=}, {self.primaryConf}', 6) # #815
if ok and conf['ok']:
try:
if cfg('saveLayout', True) and len(self.chartArea.widget.hosts):