forked from ccbogel/QualCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
2038 lines (1857 loc) · 90.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
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Colin Curtain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Author: Colin Curtain (ccbogel)
https://github.com/ccbogel/QualCoder
https://qualcoder.wordpress.com/
"""
import base64
import configparser
import datetime
import gettext
import json # to get latest Github release information
import logging
from logging.handlers import RotatingFileHandler
import os
import platform
import shutil
import sys
import sqlite3
import traceback
import urllib.request
import webbrowser
from copy import copy
from PyQt5 import QtCore, QtGui, QtWidgets
from qualcoder.attributes import DialogManageAttributes
from qualcoder.cases import DialogCases
from qualcoder.codebook import Codebook
from qualcoder.code_text import DialogCodeText
from qualcoder.code_by_case import DialogCodeByCase
from qualcoder.GUI.base64_helper import * # qualcoder32
from qualcoder.GUI.ui_main import Ui_MainWindow
from qualcoder.helpers import Message
from qualcoder.import_survey import DialogImportSurvey
from qualcoder.information import DialogInformation
from qualcoder.locale.base64_lang_helper import *
from qualcoder.journals import DialogJournals
from qualcoder.manage_files import DialogManageFiles
from qualcoder.manage_links import DialogManageLinks
from qualcoder.memo import DialogMemo
from qualcoder.refi import RefiExport, RefiImport
from qualcoder.reports import DialogReportCoderComparisons, DialogReportCodeFrequencies
from qualcoder.report_code_summary import DialogReportCodeSummary
from qualcoder.report_compare_coder_file import DialogCompareCoderByFile
from qualcoder.report_codes import DialogReportCodes
from qualcoder.report_file_summary import DialogReportFileSummary
from qualcoder.report_relations import DialogReportRelations
from qualcoder.report_sql import DialogSQL
from qualcoder.rqda import Rqda_import
from qualcoder.settings import DialogSettings
from qualcoder.special_functions import DialogSpecialFunctions
# from qualcoder.text_mining import DialogTextMining
from qualcoder.view_av import DialogCodeAV
from qualcoder.view_graph_original import ViewGraphOriginal
from qualcoder.view_image import DialogCodeImage
qualcoder_version = "QualCoder 2.9"
path = os.path.abspath(os.path.dirname(__file__))
home = os.path.expanduser('~')
if not os.path.exists(home + '/.qualcoder'):
try:
os.mkdir(home + '/.qualcoder')
except Exception as e:
print("Cannot add .qualcoder folder to home directory\n" + str(e))
raise
logfile = home + '/.qualcoder/QualCoder.log'
# Hack for Windows 10 PermissionError that stops the rotating file handler, will produce massive files.
try:
log_file = open(logfile, "r")
data = log_file.read()
log_file.close()
if len(data) > 12000:
os.remove(logfile)
log_file = open(logfile, "w")
log_file.write(data[10000:])
log_file.close()
except Exception as e:
print(e)
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s.%(funcName)s %(message)s',
datefmt='%Y/%m/%d %H:%M:%S', filename=logfile)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# The rotating file handler does not work on Windows
handler = RotatingFileHandler(logfile, maxBytes=4000, backupCount=2)
logger.addHandler(handler)
def exception_handler(exception_type, value, tb_obj):
""" Global exception handler useful in GUIs.
tb_obj: exception.__traceback__ """
tb = '\n'.join(traceback.format_tb(tb_obj))
msg = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(msg)
mb = QtWidgets.QMessageBox()
mb.setStyleSheet("* {font-size: 10pt}")
mb.setText(msg)
mb.exec_()
class App(object):
""" General methods for loading settings and recent project stored in .qualcoder folder.
Savable settings does not contain project name, project path or db connection.
"""
version = qualcoder_version
conn = None
project_path = ""
project_name = ""
# Can delete the most current back up if the project has not been altered
delete_backup_path_name = ""
delete_backup = True
# Used as a default export location, which may be different from the working directory
last_export_directory = ""
def __init__(self):
sys.excepthook = exception_handler
self.conn = None
self.project_path = ""
self.project_name = ""
self.last_export_directory = ""
self.delete_backup = True
self.delete_backup_path_name = ""
self.confighome = os.path.expanduser('~/.qualcoder')
self.configpath = os.path.join(self.confighome, 'config.ini')
self.persist_path = os.path.join(self.confighome, 'recent_projects.txt')
self.settings = self.load_settings()
self.last_export_directory = copy(self.settings['directory'])
self.version = qualcoder_version
def read_previous_project_paths(self):
""" Recent project paths are stored in .qualcoder/recent_projects.txt
Remove paths that no longer exist.
Moving from only listing the previous project path to: date opened | previous project path.
Write a new file in order of most recent opened to older and without duplicate projects.
"""
previous = []
try:
with open(self.persist_path, 'r') as f:
for line in f:
previous.append(line.strip())
except FileNotFoundError:
logger.info('No previous projects found')
# Add paths that exist
interim_result = []
for p in previous:
splt = p.split("|")
proj_path = ""
if len(splt) == 1:
proj_path = splt[0]
if len(splt) == 2:
proj_path = splt[1]
if os.path.exists(proj_path):
interim_result.append(p)
# Remove duplicate project names, keep the most recent
interim_result.sort(reverse=True)
result = []
proj_paths = []
for i in interim_result:
splt = i.split("|")
proj_path = ""
if len(splt) == 1:
proj_path = splt[0]
if len(splt) == 2:
proj_path = splt[1]
if proj_path not in proj_paths:
proj_paths.append(proj_path)
result.append(i)
# Write the latest projects file in order of most recently opened and without duplicate projects
with open(self.persist_path, 'w') as f:
for i, line in enumerate(result):
if i < 8:
f.write(line)
f.write(os.linesep)
return result
def append_recent_project(self, path):
""" Add project path as first entry to .qualcoder/recent_projects.txt
"""
if path == "":
return
nowdate = datetime.datetime.now().astimezone().strftime("%Y-%m-%d_%H:%M:%S")
# Result is a list of strings containing yyyy-mm-dd:hh:mm:ss|projectpath
result = self.read_previous_project_paths()
dated_path = nowdate + "|" + path
if not result:
with open(self.persist_path, 'w') as f:
f.write(dated_path)
f.write(os.linesep)
return
# Compare first persisted project path to the currently open project path
if "|" in result[0]: # safety check
if result[0].split("|")[1] != path:
result.append(dated_path)
result.sort()
if len(result) > 8:
result = result[0:8]
with open(self.persist_path, 'w') as f:
for i, line in enumerate(result):
f.write(line)
f.write(os.linesep)
def get_most_recent_projectpath(self):
""" Get most recent project path from .qualcoder/recent_projects.txt """
result = self.read_previous_project_paths()
if result:
return result[0]
def create_connection(self, project_path):
""" Create connection to recent project. """
self.project_path = project_path
self.project_name = project_path.split('/')[-1]
self.conn = sqlite3.connect(os.path.join(project_path, 'data.qda'))
def get_code_names(self):
cur = self.conn.cursor()
cur.execute("select name, memo, owner, date, cid, catid, color from code_name order by lower(name)")
result = cur.fetchall()
res = []
keys = 'name', 'memo', 'owner', 'date', 'cid', 'catid', 'color'
for row in result:
res.append(dict(zip(keys, row)))
return res
def get_filenames(self):
""" Get all filenames. As id, name, memo """
cur = self.conn.cursor()
cur.execute("select id, name, memo from source order by lower(name)")
result = cur.fetchall()
res = []
for row in result:
res.append({'id': row[0], 'name': row[1], 'memo': row[2]})
return res
def get_casenames(self):
""" Get all case names. As id, name, memo. """
cur = self.conn.cursor()
cur.execute("select caseid, name, memo from cases order by lower(name)")
result = cur.fetchall()
res = []
for row in result:
res.append({'id': row[0], 'name': row[1], 'memo': row[2]})
return res
def get_text_filenames(self, ids=[]):
""" Get filenames of text files.
param:
ids: list of Integer ids for a restricted list of files. """
sql = "select id, name, memo from source where (mediapath is Null or mediapath like 'docs:%') "
if ids:
str_ids = list(map(str, ids))
sql += " and id in (" + ",".join(str_ids) + ")"
sql += "order by lower(name)"
cur = self.conn.cursor()
cur.execute(sql)
result = cur.fetchall()
res = []
for row in result:
res.append({'id': row[0], 'name': row[1], 'memo': row[2]})
return res
def get_image_filenames(self, ids=[]):
""" Get filenames of image files only.
param:
ids: list of Integer ids for a restricted list of files. """
sql = "select id, name, memo from source where mediapath like '/images/%' or mediapath like 'images:%'"
if ids:
str_ids = list(map(str, ids))
sql += " and id in (" + ",".join(str_ids) + ")"
sql += " order by lower(name)"
cur = self.conn.cursor()
cur.execute(sql)
result = cur.fetchall()
res = []
for row in result:
res.append({'id': row[0], 'name': row[1], 'memo': row[2]})
return res
def get_av_filenames(self, ids=[]):
""" Get filenames of audio video files only.
param:
ids: list of Integer ids for a restricted list of files. """
sql = "select id, name, memo from source where "
sql += "(mediapath like '/audio/%' or mediapath like 'audio:%' or mediapath like '/video/%' or mediapath like 'video:%') "
if ids:
str_ids = list(map(str, ids))
sql += " and id in (" + ",".join(str_ids) + ")"
sql += " order by lower(name)"
cur = self.conn.cursor()
cur.execute(sql)
result = cur.fetchall()
res = []
for row in result:
res.append({'id': row[0], 'name': row[1], 'memo': row[2]})
return res
def get_annotations(self):
""" Get annotations for text files. """
cur = self.conn.cursor()
cur.execute("select anid, fid, pos0, pos1, memo, owner, date from annotation where owner=?",
[self.settings['codername'], ])
result = cur.fetchall()
res = []
keys = 'anid', 'fid', 'pos0', 'pos1', 'memo', 'owner', 'date'
for row in result:
res.append(dict(zip(keys, row)))
return res
def get_codes_categories(self):
""" Gets all the codes, categories.
Called from code_text, code_av, code_image, reports, report_relations """
cur = self.conn.cursor()
categories = []
cur.execute("select name, catid, owner, date, memo, supercatid from code_cat order by lower(name)")
result = cur.fetchall()
keys = 'name', 'catid', 'owner', 'date', 'memo', 'supercatid'
for row in result:
categories.append(dict(zip(keys, row)))
codes = []
cur = self.conn.cursor()
cur.execute("select name, memo, owner, date, cid, catid, color from code_name order by lower(name)")
result = cur.fetchall()
keys = 'name', 'memo', 'owner', 'date', 'cid', 'catid', 'color'
for row in result:
codes.append(dict(zip(keys, row)))
return codes, categories
def check_bad_file_links(self):
""" Check all linked files are present.
Called from MainWindow.open_project, view_av.
Returns:
dictionary of id,name, mediapath for bad links
"""
cur = self.conn.cursor()
sql = "select id, name, mediapath from source where \
substr(mediapath,1,6) = 'audio:' \
or substr(mediapath,1,5) = 'docs:' \
or substr(mediapath,1,7) = 'images:' \
or substr(mediapath,1,6) = 'video:' order by name"
cur.execute(sql)
result = cur.fetchall()
bad_links = []
for r in result:
if r[2][0:5] == "docs:" and not os.path.exists(r[2][5:]):
bad_links.append({'name': r[1], 'mediapath': r[2], 'id': r[0]})
if r[2][0:7] == "images:" and not os.path.exists(r[2][7:]):
bad_links.append({'name': r[1], 'mediapath': r[2], 'id': r[0]})
if r[2][0:6] == "video:" and not os.path.exists(r[2][6:]):
bad_links.append({'name': r[1], 'mediapath': r[2], 'id': r[0]})
if r[2][0:6] == "audio:" and not os.path.exists(r[2][6:]):
bad_links.append({'name': r[1], 'mediapath': r[2], 'id': r[0]})
return bad_links
def write_config_ini(self, settings):
""" Stores settings for fonts, current coder, directory, and window sizes in .qualcoder folder
Called by qualcoder.App.load_settings, qualcoder.MainWindow.open_project, settings.DialogSettings
"""
config = configparser.ConfigParser()
config['DEFAULT'] = settings
with open(self.configpath, 'w') as configfile:
config.write(configfile)
def _load_config_ini(self):
config = configparser.ConfigParser()
config.read(self.configpath)
default = config['DEFAULT']
result = dict(default)
# convert to int can be removed when all manual styles are removed
if 'fontsize' in default:
result['fontsize'] = default.getint('fontsize')
if 'treefontsize' in default:
result['treefontsize'] = default.getint('treefontsize')
if 'docfontsize' in default:
result['docfontsize'] = default.getint('docfontsize')
return result
def check_and_add_additional_settings(self, data):
""" Newer features include width and height settings for many dialogs and main window.
timestamp format.
dialog_crossovers IS dialog relations
:param data: dictionary of most or all settings
:return: dictionary of all settings
"""
dict_len = len(data)
keys = ['mainwindow_w', 'mainwindow_h',
'dialogcasefilemanager_w', 'dialogcasefilemanager_h',
'dialogcodetext_splitter0', 'dialogcodetext_splitter1',
'dialogcodetext_splitter_v0', 'dialogcodetext_splitter_v1',
'dialogcodebycase_splitter0', 'dialogcodebycase_splitter1',
'dialogcodebycase_splitter_v0', 'dialogcodebycase_splitter_v1',
'dialogcodeimage_splitter0', 'dialogcodeimage_splitter1',
'dialogcodeimage_splitter_h0', 'dialogcodeimage_splitter_h1',
'dialogreportcodes_splitter0', 'dialogreportcodes_splitter1',
'dialogreportcodes_splitter_v0', 'dialogreportcodes_splitter_v1',
'dialogreportcodes_splitter_v2',
'dialogjournals_splitter0', 'dialogjournals_splitter1',
'dialogsql_splitter_h0', 'dialogsql_splitter_h1',
'dialogsql_splitter_v0', 'dialogsql_splitter_v1',
'dialogcases_splitter0', 'dialogcases_splitter1',
'dialogcasefilemanager_splitter0', 'dialogcasefilemanager_splitter1',
'timestampformat', 'speakernameformat',
'video_w', 'video_h',
'codeav_abs_pos_x', 'codeav_abs_pos_y',
'viewav_abs_pos_x', 'viewav_abs_pos_y',
'viewav_video_pos_x', 'viewav_video_pos_y',
'codeav_video_pos_x', 'codeav_video_pos_y',
'dialogcodeav_splitter_0', 'dialogcodeav_splitter_1',
'dialogcodeav_splitter_h0', 'dialogcodeav_splitter_h1',
'dialogcodecrossovers_w', 'dialogcodecrossovers_h',
'dialogcodecrossovers_splitter0', 'dialogcodecrossovers_splitter1',
'dialogmanagelinks_w', 'dialogmanagelinks_h',
'docfontsize',
'dialogreport_file_summary_splitter0', 'dialogreport_file_summary_splitter0',
'dialogreport_code_summary_splitter0', 'dialogreport_code_summary_splitter0',
'stylesheet'
]
for key in keys:
if key not in data:
data[key] = 0
if key == "timestampformat":
data[key] = "[hh.mm.ss]"
if key == "speakernameformat":
data[key] = "[]"
# write out new ini file, if needed
if len(data) > dict_len:
self.write_config_ini(data)
return data
def merge_settings_with_default_stylesheet(self, settings):
""" Originally had separate stylesheet file. Now stylesheet is coded because
avoids potential data file import errors with pyinstaller. """
style_dark = "* {font-size: 12px; background-color: #2a2a2a; color:#eeeeee;}\n\
QWidget:focus {border: 2px solid #f89407;}\n\
QDialog {border: 1px solid #707070;}\n\
QLabel#label_search_regex {background-color:#808080;}\n\
QLabel#label_search_case_sensitive {background-color:#808080;}\n\
QLabel#label_search_all_files {background-color:#808080;}\n\
QLabel#label_font_size {background-color:#808080;}\n\
QLabel#label_search_all_journals {background-color:#808080;}\n\
QLabel#label_exports {background-color:#808080;}\n\
QLabel#label_time_3 {background-color:#808080;}\n\
QLabel#label_volume {background-color:#808080;}\n\
QLabel:disabled {color: #808080;}\n\
QSlider::handle:horizontal {background-color: #f89407;}\n\
QCheckBox {border: None}\n\
QCheckBox::indicator {border: 2px solid #808080; background-color: #2a2a2a;}\n\
QCheckBox::indicator::checked {border: 2px solid #808080; background-color: orange;}\n\
QRadioButton::indicator {border: 1px solid #808080; background-color: #2a2a2a;}\n\
QRadioButton::indicator::checked {border: 2px solid #808080; background-color: orange;}\n\
QLineEdit {border: 1px solid #808080;}\n\
QMenuBar::item:selected {background-color: #3498db; }\n\
QMenu {border: 1px solid #808080;}\n\
QMenu::item:selected {background-color: #3498db;}\n\
QMenu::item:disabled {color: #777777;}\n\
QToolTip {background-color: #2a2a2a; color:#eeeeee; border: 1px solid #f89407; }\n\
QPushButton {background-color: #808080;}\n\
QPushButton:hover {border: 2px solid #ffaa00;}\n\
QComboBox {border: 1px solid #707070;}\n\
QComboBox:hover {border: 2px solid #ffaa00;}\n\
QGroupBox {border: None;}\n\
QGroupBox:focus {border: 3px solid #ffaa00;}\n\
QTabWidget::pane {border: 1px solid #808080;}\n\
QTabBar {border: 2px solid #808080;}\n\
QTabBar::tab {border: 1px solid #808080;}\n\
QTabBar::tab:selected {border: 2px solid #f89407; background-color: #707070; margin-left: 3px;}\n\
QTabBar::tab:!selected {border: 2px solid #707070; background-color: #2a2a2a; margin-left: 3px;}\n\
QTextEdit {border: 1px solid #ffaa00;}\n\
QTextEdit:focus {border: 2px solid #ffaa00;}\n\
QTableWidget {border: 1px solid #ffaa00; gridline-color: #707070;}\n\
QTableWidget:focus {border: 3px solid #ffaa00;}\n\
QListWidget::item:selected {border-left: 3px solid red; color: #eeeeee;}\n\
QHeaderView::section {background-color: #505050; color: #ffce42;}\n\
QTreeWidget {font-size: 12px;}\n\
QTreeWidget::branch:selected {border-left: 2px solid red; color: #eeeeee;}"
style_dark = style_dark.replace("* {font-size: 12", "* {font-size:" + str(settings.get('fontsize')))
style_dark = style_dark.replace("QTreeWidget {font-size: 12",
"QTreeWidget {font-size: " + str(settings.get('treefontsize')))
style = "* {font-size: 12px; color: #000000;}\n\
QWidget:focus {border: 2px solid #f89407;}\n\
QComboBox:hover,QPushButton:hover {border: 2px solid #ffaa00;}\n\
QGroupBox {border: None;}\n\
QGroupBox:focus {border: 3px solid #ffaa00;}\n\
QTextEdit:focus {border: 2px solid #ffaa00;}\n\
QToolTip {background-color: #fffacd; color:#000000; border: 1px solid #f89407; }\n\
QListWidget::item:selected {border-left: 2px solid red; color: #000000;}\n\
QTableWidget:focus {border: 3px solid #ffaa00;}\n\
QTreeWidget {font-size: 12px;}\n\
QTreeWidget::branch:selected {border-left: 2px solid red; color: #000000;}"
style = style.replace("* {font-size: 12", "* {font-size:" + str(settings.get('fontsize')))
style = style.replace("QTreeWidget {font-size: 12",
"QTreeWidget {font-size: " + str(settings.get('treefontsize')))
if self.settings['stylesheet'] == 'dark':
return style_dark
return style
def load_settings(self):
result = self._load_config_ini()
if not len(result):
self.write_config_ini(self.default_settings)
logger.info('Initialized config.ini')
result = self._load_config_ini()
# codername is alo legacy, v2.8 plus keeps current coder name in database project table
if result['codername'] == "":
result['codername'] = "default"
result = self.check_and_add_additional_settings(result)
# TODO TEMPORARY delete in 2022, legacy
if result['speakernameformat'] == 0:
result['speakernameformat'] = "[]"
if result['stylesheet'] == 0:
result['stylesheet'] = "original"
return result
@property
def default_settings(self):
""" Standard Settings for config.ini file. """
return {
'codername': 'default',
'font': 'Noto Sans',
'fontsize': 14,
'docfontsize': 12,
'treefontsize': 12,
'directory': os.path.expanduser('~'),
'showids': False,
'language': 'en',
'backup_on_open': True,
'backup_av_files': True,
'timestampformat': "[hh.mm.ss]",
'speakernameformat': "[]",
'mainwindow_w': 0,
'mainwindow_h': 0,
'dialogcodetext_splitter0': 1,
'dialogcodetext_splitter1': 1,
'dialogcodetext_splitter_v0': 1,
'dialogcodetext_splitter_v1': 1,
'dialogcodebycase_splitter0': 1,
'dialogcodebycase_splitter1': 1,
'dialogcodebycase_splitter_v0': 1,
'dialogcodebycase_splitter_v1': 1,
'dialogcodeimage_splitter0': 1,
'dialogcodeimage_splitter1': 1,
'dialogcodeimage_splitter_h0': 1,
'dialogcodeimage_splitter_h1': 1,
'dialogreportcodes_splitter0': 1,
'dialogreportcodes_splitter1': 1,
'dialogreportcodes_splitter_v0': 30,
'dialogreportcodes_splitter_v1': 30,
'dialogreportcodes_splitter_v2': 30,
'dialogjournals_splitter0': 1,
'dialogjournals_splitter1': 1,
'dialogsql_splitter_h0': 1,
'dialogsql_splitter_h1': 1,
'dialogsql_splitter_v0': 1,
'dialogsql_splitter_v1': 1,
'dialogcases_splitter0': 1,
'dialogcases_splitter1': 1,
'dialogcasefilemanager_w': 0,
'dialogcasefilemanager_h': 0,
'dialogcasefilemanager_splitter0': 1,
'dialogcasefilemanager_splitter1': 1,
'video_w': 0,
'video_h': 0,
'viewav_video_pos_x': 0,
'viewav_video_pos_y': 0,
'codeav_video_pos_x': 0,
'codeav_video_pos_y': 0,
'codeav_abs_pos_x': 0,
'codeav_abs_pos_y': 0,
'dialogcodeav_splitter_0': 0,
'dialogcodeav_splitter_1': 0,
'dialogcodeav_splitter_h0': 0,
'dialogcodeav_splitter_h1': 0,
'viewav_abs_pos_x': 0,
'viewav_abs_pos_y': 0,
'dialogcodecrossovers_w': 0,
'dialogcodecrossovers_h': 0,
'dialogcodecrossovers_splitter0': 0,
'dialogcodecrossovers_splitter1': 0,
'dialogmanagelinks_w': 0,
'dialogmanagelinks_h': 0,
'bookmark_file_id': 0,
'bookmark_pos': 0,
'dialogreport_file_summary_splitter0': 100,
'dialogreport_file_summary_splitter1': 100,
'dialogreport_code_summary_splitter0': 100,
'dialogreport_code_summary_splitter1': 100,
'stylesheet': 'original'
}
def get_file_texts(self, fileids=None):
""" Get the texts of all text files as a list of dictionaries.
Called by DialogCodeText.search_for_text
param:
fileids - a list of fileids or None
"""
cur = self.conn.cursor()
if fileids is not None:
cur.execute(
"select name, id, fulltext, memo, owner, date from source where id in (?) and fulltext is not null",
fileids
)
else:
cur.execute(
"select name, id, fulltext, memo, owner, date from source where fulltext is not null order by name")
keys = 'name', 'id', 'fulltext', 'memo', 'owner', 'date'
result = []
for row in cur.fetchall():
result.append(dict(zip(keys, row)))
return result
def get_journal_texts(self, jids=None):
""" Get the texts of all journals as a list of dictionaries.
Called by DialogJournals.search_for_text
param:
jids - a list of jids or None
"""
cur = self.conn.cursor()
if jids is not None:
cur.execute(
"select name, jid, jentry, owner, date from journal where jid in (?)",
jids
)
else:
cur.execute("select name, jid, jentry, owner, date from journal order by date desc")
keys = 'name', 'jid', 'jentry', 'owner', 'date'
result = []
for row in cur.fetchall():
result.append(dict(zip(keys, row)))
return result
def get_coder_names_in_project(self):
""" Get all coder names from all tables and from the config.ini file
Design flaw is that current codername is not stored in a specific table in Database Versions 1 to 4.
Coder name is stored in Database version 5.
Current coder name is in position 0.
"""
# Try except, as there may not be an open project, and might be an older <= v4 database
try:
cur = self.conn.cursor()
cur.execute("select codername from project")
res = cur.fetchone()
if res[0] is not None:
self.settings['codername'] = res[0]
except:
pass
# For versions 1 to 4, current coder name stored in the config.ini file, so is added here.
coder_names = [self.settings['codername']]
# Try except, as there may not be an open project
try:
cur = self.conn.cursor()
sql = "select owner from code_image union select owner from code_text union select owner from code_av "
sql += "union select owner from cases union select owner from source union select owner from code_name"
cur.execute(sql)
res = cur.fetchall()
for r in res:
if r[0] not in coder_names:
coder_names.append(r[0])
except:
pass
return coder_names
class MainWindow(QtWidgets.QMainWindow):
""" Main GUI window.
Project data is stored in a directory with .qda suffix
core data is stored in data.qda sqlite file.
Journal and coding dialogs can be shown non-modally - multiple dialogs open.
There is a risk of a clash if two coding windows are open with the same file text or
two journals open with the same journal entry.
Note: App.settings does not contain projectName, conn or path (to database)
app.project_name and app.project_path contain these.
"""
project = {"databaseversion": "", "date": "", "memo": "", "about": ""}
recent_projects = [] # a list of recent projects for the qmenu
def __init__(self, app, force_quit=False):
""" Set up user interface from ui_main.py file. """
self.app = app
self.force_quit = force_quit
sys.excepthook = exception_handler
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Test of MacOS menu bar
self.ui.menubar.setNativeMenuBar(False)
self.get_latest_github_release()
try:
w = int(self.app.settings['mainwindow_w'])
h = int(self.app.settings['mainwindow_h'])
if h > 40 and w > 50:
self.resize(w, h)
except:
pass
self.hide_menu_options()
font = 'font: ' + str(self.app.settings['fontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.setStyleSheet(font)
self.init_ui()
self.show()
def init_ui(self):
""" Set up menu triggers """
# project menu
self.ui.actionCreate_New_Project.triggered.connect(self.new_project)
self.ui.actionCreate_New_Project.setShortcut('Ctrl+N')
self.ui.actionOpen_Project.triggered.connect(self.open_project)
self.ui.actionOpen_Project.setShortcut('Ctrl+O')
self.fill_recent_projects_menu_actions()
self.ui.actionProject_Memo.triggered.connect(self.project_memo)
self.ui.actionProject_Memo.setShortcut('Ctrl+M')
self.ui.actionClose_Project.triggered.connect(self.close_project)
self.ui.actionClose_Project.setShortcut('Alt+X')
self.ui.actionSettings.triggered.connect(self.change_settings)
self.ui.actionSettings.setShortcut('Alt+S')
self.ui.actionProject_summary.triggered.connect(self.project_summary_report)
self.ui.actionProject_Exchange_Export.triggered.connect(self.refi_project_export)
self.ui.actionREFI_Codebook_export.triggered.connect(self.refi_codebook_export)
self.ui.actionREFI_Codebook_import.triggered.connect(self.refi_codebook_import)
self.ui.actionREFI_QDA_Project_import.triggered.connect(self.refi_project_import)
self.ui.actionRQDA_Project_import.triggered.connect(self.rqda_project_import)
self.ui.actionExit.triggered.connect(self.closeEvent)
self.ui.actionExit.setShortcut('Ctrl+Q')
# File cases and journals menu
self.ui.actionManage_files.triggered.connect(self.manage_files)
self.ui.actionManage_journals.triggered.connect(self.journals)
self.ui.actionManage_journals.setShortcut('Alt+J')
self.ui.actionManage_cases.triggered.connect(self.manage_cases)
self.ui.actionManage_cases.setShortcut('Alt+C')
self.ui.actionManage_attributes.triggered.connect(self.manage_attributes)
self.ui.actionManage_attributes.setShortcut('Alt+A')
self.ui.actionImport_survey.triggered.connect(self.import_survey)
self.ui.actionImport_survey.setShortcut('Alt+I')
self.ui.actionManage_bad_links_to_files.triggered.connect(self.manage_bad_file_links)
# Codes menu
self.ui.actionCodes.triggered.connect(self.text_coding)
self.ui.actionCodes.setShortcut('Alt+T')
self.ui.actionCode_image.triggered.connect(self.image_coding)
self.ui.actionCode_image.setShortcut('Alt+I')
self.ui.actionCode_audio_video.triggered.connect(self.av_coding)
self.ui.actionCode_audio_video.setShortcut('Alt+V')
self.ui.actionCode_by_case.triggered.connect(self.code_by_case)
self.ui.actionExport_codebook.triggered.connect(self.codebook)
# Reports menu
self.ui.actionCoding_reports.triggered.connect(self.report_coding)
# self.ui.actionCoding_reports.setShortcut('Ctrl+R') Affects code AV function
self.ui.actionCoding_comparison.triggered.connect(self.report_coding_comparison)
self.ui.actionCoding_comparison_by_file.triggered.connect(self.report_compare_coders_by_file)
self.ui.actionCode_frequencies.triggered.connect(self.report_code_frequencies)
self.ui.actionView_Graph.triggered.connect(self.view_graph_original)
self.ui.actionView_Graph.setShortcut('Ctrl+G')
self.ui.actionCode_relations.triggered.connect(self.report_code_relations)
self.ui.actionFile_summary.triggered.connect(self.report_file_summary)
self.ui.actionCode_summary.triggered.connect(self.report_code_summary)
# TODO self.ui.actionText_mining.triggered.connect(self.text_mining)
self.ui.actionSQL_statements.triggered.connect(self.report_sql)
# help menu
self.ui.actionContents.triggered.connect(self.help)
self.ui.actionContents.setShortcut('Ctrl+H')
self.ui.actionAbout.triggered.connect(self.about)
self.ui.actionSpecial_functions.triggered.connect(self.special_functions)
font = 'font: ' + str(self.app.settings['fontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.setStyleSheet(font)
self.ui.textEdit.setReadOnly(True)
self.settings_report()
def resizeEvent(self, new_size):
""" Update the widget size details in the app.settings variables """
self.app.settings['mainwindow_w'] = new_size.size().width()
self.app.settings['mainwindow_h'] = new_size.size().height()
def fill_recent_projects_menu_actions(self):
""" Get the recent projects from the .qualcoder txt file.
Add up to 7 recent projects to the menu. """
self.recent_projects = self.app.read_previous_project_paths()
if len(self.recent_projects) == 0:
return
# Removes the qtdesigner default action. Also clears the section when a proect is closed
# so that the options for recent projects can be updated
self.ui.menuOpen_Recent_Project.clear()
for i, r in enumerate(self.recent_projects):
display_name = r
if len(r.split("|")) == 2:
display_name = r.split("|")[1]
if i == 0:
action0 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action0)
action0.triggered.connect(self.project0)
if i == 1:
action1 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action1)
action1.triggered.connect(self.project1)
if i == 2:
action2 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action2)
action2.triggered.connect(self.project2)
if i == 3:
action3 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action3)
action3.triggered.connect(self.project3)
if i == 4:
action4 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action4)
action4.triggered.connect(self.project4)
if i == 5:
action5 = QtWidgets.QAction(display_name, self)
self.ui.menuOpen_Recent_Project.addAction(action5)
action5.triggered.connect(self.project5)
def project0(self):
self.open_project(self.recent_projects[0])
def project1(self):
self.open_project(self.recent_projects[1])
def project2(self):
self.open_project(self.recent_projects[2])
def project3(self):
self.open_project(self.recent_projects[3])
def project4(self):
self.open_project(self.recent_projects[4])
def project5(self):
self.open_project(self.recent_projects[5])
def hide_menu_options(self):
""" No project opened, hide most menu options.
Enable project import options.
Called by init and by close_project. """
# project menu
self.ui.actionClose_Project.setEnabled(False)
self.ui.actionProject_Memo.setEnabled(False)
self.ui.actionProject_Exchange_Export.setEnabled(False)
self.ui.actionREFI_Codebook_export.setEnabled(False)
self.ui.actionREFI_Codebook_import.setEnabled(False)
self.ui.actionREFI_QDA_Project_import.setEnabled(True)
self.ui.actionRQDA_Project_import.setEnabled(True)
self.ui.actionExport_codebook.setEnabled(False)
# files cases journals menu
self.ui.actionManage_files.setEnabled(False)
self.ui.actionManage_journals.setEnabled(False)
self.ui.actionManage_cases.setEnabled(False)
self.ui.actionManage_attributes.setEnabled(False)
self.ui.actionImport_survey.setEnabled(False)
self.ui.actionManage_bad_links_to_files.setEnabled(False)
# codes menu
self.ui.actionCodes.setEnabled(False)
self.ui.actionCode_image.setEnabled(False)
self.ui.actionCode_audio_video.setEnabled(False)
self.ui.actionCode_by_case.setEnabled(False)
# reports menu
self.ui.actionCoding_reports.setEnabled(False)
self.ui.actionCoding_comparison.setEnabled(False)
self.ui.actionCoding_comparison_by_file.setEnabled(False)
self.ui.actionCode_frequencies.setEnabled(False)
self.ui.actionCode_relations.setEnabled(False)
self.ui.actionText_mining.setEnabled(False)
self.ui.actionSQL_statements.setEnabled(False)
self.ui.actionFile_summary.setEnabled(False)
self.ui.actionCode_summary.setEnabled(False)
self.ui.actionCategories.setEnabled(False)
self.ui.actionView_Graph.setEnabled(False)
# help menu
self.ui.actionSpecial_functions.setEnabled(False)
def show_menu_options(self):
""" Project opened, show most menu options.
Disable project import options. """
# Project menu
self.ui.actionClose_Project.setEnabled(True)
self.ui.actionProject_Memo.setEnabled(True)
self.ui.actionProject_Exchange_Export.setEnabled(True)
self.ui.actionREFI_Codebook_export.setEnabled(True)
self.ui.actionREFI_Codebook_import.setEnabled(True)
self.ui.actionREFI_QDA_Project_import.setEnabled(False)
self.ui.actionRQDA_Project_import.setEnabled(False)
self.ui.actionExport_codebook.setEnabled(True)
# Files cases journals menu
self.ui.actionManage_files.setEnabled(True)
self.ui.actionManage_journals.setEnabled(True)
self.ui.actionManage_cases.setEnabled(True)
self.ui.actionManage_attributes.setEnabled(True)
self.ui.actionImport_survey.setEnabled(True)
# Codes menu
self.ui.actionCodes.setEnabled(True)
self.ui.actionCode_image.setEnabled(True)
self.ui.actionCode_audio_video.setEnabled(True)
self.ui.actionCode_by_case.setEnabled(True)
# Reports menu
self.ui.actionCoding_reports.setEnabled(True)
self.ui.actionCoding_comparison.setEnabled(True)
self.ui.actionCoding_comparison_by_file.setEnabled(True)
self.ui.actionCode_frequencies.setEnabled(True)
self.ui.actionCode_relations.setEnabled(True)
self.ui.actionSQL_statements.setEnabled(True)
self.ui.actionFile_summary.setEnabled(True)
self.ui.actionCode_summary.setEnabled(True)
self.ui.actionCategories.setEnabled(True)
self.ui.actionView_Graph.setEnabled(True)
# Help menu
self.ui.actionSpecial_functions.setEnabled(True)
# TODO FOR FUTURE EXPANSION text mining
self.ui.actionText_mining.setEnabled(False)
self.ui.actionText_mining.setVisible(False)
def settings_report(self):
""" Display general settings and project summary """
msg = _("Settings")
msg += "\n========\n"
msg += _("Coder") + ": " + self.app.settings['codername'] + "\n"
msg += _("Font") + ": " + self.app.settings['font'] + " " + str(self.app.settings['fontsize']) + "\n"
msg += _("Tree font size") + ": " + str(self.app.settings['treefontsize']) + "\n"
msg += _("Working directory") + ": " + self.app.settings['directory']
msg += "\n" + _("Show IDs") + ": " + str(self.app.settings['showids']) + "\n"
msg += _("Language") + ": " + self.app.settings['language'] + "\n"
msg += _("Timestamp format") + ": " + self.app.settings['timestampformat'] + "\n"
msg += _("Speaker name format") + ": " + str(self.app.settings['speakernameformat']) + "\n"
msg += _("Backup on open") + ": " + str(self.app.settings['backup_on_open']) + "\n"
msg += _("Backup AV files") + ": " + str(self.app.settings['backup_av_files'])
if platform.system() == "Windows":
msg += "\n" + _("Directory (folder) paths / represents \\")
msg += "\n========"
self.ui.textEdit.append(msg)
self.ui.textEdit.textCursor().movePosition(QtGui.QTextCursor.End)
self.ui.tabWidget.setCurrentWidget(self.ui.tab_action_log)
def report_sql(self):
""" Run SQL statements on database. """
self.ui.label_reports.hide()
ui = DialogSQL(self.app, self.ui.textEdit)
self.tab_layout_helper(self.ui.tab_reports, ui)
"""def text_mining(self):
''' text analysis of files / cases / codings.
NOT CURRENTLY IMPLEMENTED, FOR FUTURE EXPANSION.
'''
ui = DialogTextMining(self.app, self.ui.textEdit)
ui.show()"""
def report_coding_comparison(self):