forked from ccbogel/QualCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_text.py
1910 lines (1763 loc) · 87.3 KB
/
code_text.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
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 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
"""
from copy import deepcopy
import datetime
import logging
import os
from random import randint
import re
import sys
import traceback
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import QHelpEvent
from PyQt5.QtCore import Qt # for context menu
from PyQt5.QtGui import QBrush
from add_item_name import DialogAddItemName
from color_selector import DialogColorSelect
from color_selector import colors
from confirm_delete import DialogConfirmDelete
from helpers import msecs_to_mins_and_secs
from information import DialogInformation
from GUI.ui_dialog_code_text import Ui_Dialog_code_text
from memo import DialogMemo
from select_items import DialogSelectItems
path = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
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))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
logger.error(_("Uncaught exception:") + "\n" + text)
mb = QtWidgets.QMessageBox()
mb.setStyleSheet("* {font-size: 12pt}")
mb.setWindowTitle(_('Uncaught Exception'))
mb.setText(text)
mb.exec_()
class DialogCodeText(QtWidgets.QWidget):
""" Code management. Add, delete codes. Mark and unmark text.
Add memos and colors to codes.
Trialled using setHtml for documents, but on marking text Html formatting was replaced, also
on unmarking text, the unmark was not immediately cleared (needed to reload the file). """
NAME_COLUMN = 0
ID_COLUMN = 1
MEMO_COLUMN = 2
app = None
dialog_list = None
parent_textEdit = None
codes = []
categories = []
filenames = []
filename = None # contains filename and file id returned from SelectItems
sourceText = None
code_text = []
annotations = []
search_indices = []
search_index = 0
eventFilter = None
def __init__(self, app, parent_textEdit, dialog_list):
super(DialogCodeText, self).__init__()
self.app = app
self.dialog_list = dialog_list
sys.excepthook = exception_handler
self.parent_textEdit = parent_textEdit
self.filenames = self.app.get_text_filenames()
self.annotations = self.app.get_annotations()
self.search_indices = []
self.search_index = 0
self.codes, self.categories = self.app.get_data()
self.ui = Ui_Dialog_code_text()
self.ui.setupUi(self)
try:
w = int(self.app.settings['dialogcodetext_w'])
h = int(self.app.settings['dialogcodetext_h'])
if h > 50 and w > 50:
self.resize(w, h)
except:
pass
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
font = 'font: ' + str(self.app.settings['fontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.setStyleSheet(font)
font = 'font: ' + str(self.app.settings['treefontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.ui.treeWidget.setStyleSheet(font)
self.ui.label_coder.setText("Coder: " + self.app.settings['codername'])
self.ui.textEdit.setPlainText("")
self.ui.textEdit.setAutoFillBackground(True)
self.ui.textEdit.setToolTip("")
self.ui.textEdit.setMouseTracking(True)
self.ui.textEdit.setReadOnly(True)
self.ui.textEdit.installEventFilter(self)
self.eventFilterTT = ToolTip_EventFilter()
self.ui.textEdit.installEventFilter(self.eventFilterTT)
self.ui.textEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.textEdit.customContextMenuRequested.connect(self.textEdit_menu)
self.ui.textEdit.cursorPositionChanged.connect(self.coded_in_text)
self.ui.pushButton_view_file.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.pushButton_view_file.customContextMenuRequested.connect(self.viewfile_menu)
self.ui.pushButton_view_file.clicked.connect(self.view_file_dialog)
self.ui.pushButton_auto_code.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.pushButton_auto_code.customContextMenuRequested.connect(self.auto_code_menu)
self.ui.pushButton_auto_code.clicked.connect(self.auto_code)
self.ui.lineEdit_search.textEdited.connect(self.search_for_text)
self.ui.lineEdit_search.setEnabled(False)
self.ui.checkBox_search_all_files.stateChanged.connect(self.search_for_text)
self.ui.checkBox_search_all_files.setEnabled(False)
self.ui.checkBox_search_case.stateChanged.connect(self.search_for_text)
self.ui.checkBox_search_case.setEnabled(False)
self.ui.pushButton_previous.setEnabled(False)
self.ui.pushButton_next.setEnabled(False)
self.ui.pushButton_next.pressed.connect(self.move_to_next_search_text)
self.ui.pushButton_previous.pressed.connect(self.move_to_previous_search_text)
self.ui.comboBox_codes_in_text.currentIndexChanged.connect(self.combo_code_selected)
self.ui.comboBox_codes_in_text.setEnabled(False)
self.ui.label_codes_count.setEnabled(False)
self.ui.label_codes_clicked_in_text.setEnabled(False)
self.ui.treeWidget.setDragEnabled(True)
self.ui.treeWidget.setAcceptDrops(True)
self.ui.treeWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
self.ui.treeWidget.viewport().installEventFilter(self)
self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.treeWidget.customContextMenuRequested.connect(self.tree_menu)
self.ui.treeWidget.itemClicked.connect(self.fill_code_label)
self.ui.splitter.setSizes([150, 400])
try:
s0 = int(self.app.settings['dialogcodetext_splitter0'])
s1 = int(self.app.settings['dialogcodetext_splitter1'])
if s0 > 10 and s1 > 10:
self.ui.splitter.setSizes([s0, s1])
except:
pass
self.fill_tree()
self.setAttribute(Qt.WA_QuitOnClose, False)
def closeEvent(self, event):
""" Save dialog and splitter dimensions. """
self.app.settings['dialogcodetext_w'] = self.size().width()
self.app.settings['dialogcodetext_h'] = self.size().height()
sizes = self.ui.splitter.sizes()
self.app.settings['dialogcodetext_splitter0'] = sizes[0]
self.app.settings['dialogcodetext_splitter1'] = sizes[1]
def fill_code_label(self):
""" Fill code label with currently selected item's code name and colour.
Also, if text is highlighted, assign the text to this code. """
current = self.ui.treeWidget.currentItem()
if current.text(1)[0:3] == 'cat':
self.ui.label_code.setText(_("NO CODE SELECTED"))
self.ui.label_code.setStyleSheet("QLabel { background-color : None; }");
return
self.ui.label_code.setText("Code: " + current.text(0))
# update background colour of label and store current code for underlining
code_for_underlining = None
for c in self.codes:
if current.text(0) == c['name']:
palette = self.ui.label_code.palette()
code_color = QtGui.QColor(c['color'])
palette.setColor(QtGui.QPalette.Window, code_color)
self.ui.label_code.setPalette(palette)
self.ui.label_code.setAutoFillBackground(True)
code_for_underlining = c
break
selected_text = self.ui.textEdit.textCursor().selectedText()
if len(selected_text) > 0:
self.mark()
self.underline_text_of_this_code(code_for_underlining)
def underline_text_of_this_code(self, code_for_underlining):
""" User interface, highlight coded text selections for the currently selected code.
Qt underline options: # NoUnderline, SingleUnderline, DashUnderline, DotLine, DashDotLine, WaveUnderline
param:
code_for_underlining: dictionary of the code to be underlined """
# Remove all underlining
selstart = 0
selend = len(self.ui.textEdit.toPlainText())
format = QtGui.QTextCharFormat()
format.setUnderlineStyle(QtGui.QTextCharFormat.NoUnderline)
cursor = self.ui.textEdit.textCursor()
cursor.setPosition(selstart)
cursor.setPosition(selend, QtGui.QTextCursor.KeepAnchor)
cursor.mergeCharFormat(format)
# Apply underlining in for selected coded text
format = QtGui.QTextCharFormat()
format.setUnderlineStyle(QtGui.QTextCharFormat.DashUnderline)
format.setUnderlineStyle(QtGui.QTextCharFormat.DashUnderline)
cursor = self.ui.textEdit.textCursor()
for coded_text in self.code_text:
if coded_text['cid'] == code_for_underlining['cid']:
cursor.setPosition(int(coded_text['pos0']), QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(int(coded_text['pos1']), QtGui.QTextCursor.KeepAnchor)
cursor.mergeCharFormat(format)
def fill_tree(self):
""" Fill tree widget, top level items are main categories and unlinked codes.
The Count column counts the number of times that code has been used by selected coder in selected file. """
cats = deepcopy(self.categories)
codes = deepcopy(self.codes)
self.ui.treeWidget.clear()
self.ui.treeWidget.setColumnCount(4)
self.ui.treeWidget.setHeaderLabels([_("Name"), _("Id"), _("Memo"), _("Count")])
if self.app.settings['showids'] == 'False':
self.ui.treeWidget.setColumnHidden(1, True)
else:
self.ui.treeWidget.setColumnHidden(1, False)
self.ui.treeWidget.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.ui.treeWidget.header().setStretchLastSection(False)
# add top level categories
remove_list = []
for c in cats:
if c['supercatid'] is None:
memo = ""
if c['memo'] != "" and c['memo'] is not None:
memo = _("Memo")
top_item = QtWidgets.QTreeWidgetItem([c['name'], 'catid:' + str(c['catid']), memo])
top_item.setToolTip(2, c['memo'])
self.ui.treeWidget.addTopLevelItem(top_item)
remove_list.append(c)
for item in remove_list:
#try:
cats.remove(item)
#except Exception as e:
# logger.debug(e, item)
''' Add child categories. look at each unmatched category, iterate through tree
to add as child, then remove matched categories from the list '''
count = 0
while len(cats) > 0 and count < 10000:
remove_list = []
#logger.debug("Cats: " + str(cats))
for c in cats:
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count2 = 0
while item and count2 < 10000: # while there is an item in the list
if item.text(1) == 'catid:' + str(c['supercatid']):
memo = ""
if c['memo'] != "" and c['memo'] is not None:
memo = _("Memo")
child = QtWidgets.QTreeWidgetItem([c['name'], 'catid:' + str(c['catid']), memo])
child.setToolTip(2, c['memo'])
item.addChild(child)
remove_list.append(c)
it += 1
item = it.value()
count2 += 1
for item in remove_list:
cats.remove(item)
count += 1
# add unlinked codes as top level items
remove_items = []
for c in codes:
if c['catid'] is None:
memo = ""
if c['memo'] != "" and c['memo'] is not None:
memo = _("Memo")
top_item = QtWidgets.QTreeWidgetItem([c['name'], 'cid:' + str(c['cid']), memo])
top_item.setToolTip(2, c['memo'])
top_item.setBackground(0, QBrush(QtGui.QColor(c['color']), Qt.SolidPattern))
top_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
self.ui.treeWidget.addTopLevelItem(top_item)
remove_items.append(c)
for item in remove_items:
codes.remove(item)
# add codes as children
for c in codes:
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count = 0
while item and count < 10000:
if item.text(1) == 'catid:' + str(c['catid']):
memo = ""
if c['memo'] != "" and c['memo'] is not None:
memo = _("Memo")
child = QtWidgets.QTreeWidgetItem([c['name'], 'cid:' + str(c['cid']), memo])
child.setBackground(0, QBrush(QtGui.QColor(c['color']), Qt.SolidPattern))
child.setToolTip(2, c['memo'])
child.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
item.addChild(child)
c['catid'] = -1 # Make unmatchable
it += 1
item = it.value()
count += 1
self.ui.treeWidget.expandAll()
self.fill_code_counts_in_tree()
def fill_code_counts_in_tree(self):
""" Count instances of each code for current coder and in the selected file.
Called by:
"""
if self.filename is None:
return
cur = self.app.conn.cursor()
sql = "select count(cid) from code_text where cid=? and fid=? and owner=?"
it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget)
item = it.value()
count = 0
while item and count < 10000:
#print(item.text(0), item.text(1), item.text(2), item.text(3))
if item.text(1)[0:4] == "cid:":
cid = str(item.text(1)[4:])
#TODO add try except for TypeError list indices must be integers not str
try:
cur.execute(sql, [cid, self.filename['id'], self.app.settings['codername']])
result = cur.fetchone()
if result[0] > 0:
item.setText(3, str(result[0]))
item.setToolTip(3, self.app.settings['codername'])
else:
item.setText(3, "")
except Exception as e:
msg = "Fill code counts error\n" + str(e) + "\n"
msg += sql + "\n"
msg += "cid " + str(cid) + "\n"
msg += "self.filename['id'] " + str(self.filename['id']) + "\n"
logger.debug(msg)
item.setText(3, "")
it += 1
item = it.value()
count += 1
def get_codes_and_categories(self):
""" Called from init, delete category/code.
Also called on other coding dialogs in the dialog_list. """
self.codes, self.categories = self.app.get_data()
def search_for_text(self):
""" On text changed in lineEdit_search, find indices of matching text.
Only where text is two or more characters long.
Resets current search_index.
If all files is checked then searches for all matching text across all text files
and displays the file text and current position to user.
If case sensitive is checked then text searched is matched for case sensitivity.
"""
if self.filename is None:
return
if len(self.search_indices) == 0:
self.ui.pushButton_next.setEnabled(False)
self.ui.pushButton_previous.setEnabled(False)
self.search_indices = []
self.search_index = -1
search_term = self.ui.lineEdit_search.text()
self.ui.label_search_totals.setText("0 / 0")
if len(search_term) >= 2:
pattern = None
flags = 0
if not self.ui.checkBox_search_case.isChecked():
flags |= re.IGNORECASE
'''if self.ui.checkBox_search_escaped.isChecked():
pattern = re.compile(re.escape(search_term), flags)
else:
try:
pattern = re.compile(search_term, flags)
except:
logger.warning('Bad escape')'''
try:
pattern = re.compile(search_term, flags)
except:
logger.warning('Bad escape')
if pattern is not None:
self.search_indices = []
if self.ui.checkBox_search_all_files.isChecked():
""" Search for this text across all files. Show each file in textEdit
"""
for filedata in self.app.get_file_texts():
try:
text = filedata['fulltext']
for match in pattern.finditer(text):
self.search_indices.append((filedata,match.start(),len(match.group(0))))
except:
logger.exception('Failed searching text %s for %s',filedata['name'],search_term)
else:
try:
if self.sourceText:
for match in pattern.finditer(self.sourceText):
# Get result as first dictionary item
filedata = self.app.get_file_texts([self.filename['id'], ])[0]
self.search_indices.append((filedata,match.start(), len(match.group(0))))
except:
logger.exception('Failed searching current file for %s',search_term)
if len(self.search_indices) > 0:
self.ui.pushButton_next.setEnabled(True)
self.ui.pushButton_previous.setEnabled(True)
self.ui.label_search_totals.setText("0 / " + str(len(self.search_indices)))
def move_to_previous_search_text(self):
""" Push button pressed to move to previous search text position. """
self.search_index -= 1
if self.search_index == -1:
self.search_index = len(self.search_indices) - 1
cur = self.ui.textEdit.textCursor()
prev_result = self.search_indices[self.search_index]
# prev_result is a tuple containing a dictonary of {name, id, fullltext, memo, owner, date} and char position and search string length
if self.filename is None or self.filename['id'] != prev_result[0]['id']:
self.load_file(prev_result[0])
cur.setPosition(prev_result[1])
cur.setPosition(cur.position() + prev_result[2], QtGui.QTextCursor.KeepAnchor)
self.ui.textEdit.setTextCursor(cur)
self.ui.label_search_totals.setText(str(self.search_index + 1) + " / " + str(len(self.search_indices)))
def move_to_next_search_text(self):
""" Push button pressed to move to next search text position. """
self.search_index += 1
if self.search_index == len(self.search_indices):
self.search_index = 0
cur = self.ui.textEdit.textCursor()
next_result = self.search_indices[self.search_index]
# next_result is a tuple containing a dictonary of {name, id, fullltext, memo, owner, date} and char position and search string length
if self.filename is None or self.filename['id'] != next_result[0]['id']:
self.load_file(next_result[0])
cur.setPosition(next_result[1])
cur.setPosition(cur.position() + next_result[2], QtGui.QTextCursor.KeepAnchor)
self.ui.textEdit.setTextCursor(cur)
self.ui.label_search_totals.setText(str(self.search_index + 1) + " / " + str(len(self.search_indices)))
def textEdit_menu(self, position):
""" Context menu for textEdit. Mark, unmark, annotate, copy. """
if self.ui.textEdit.toPlainText() == "":
return
cursor = self.ui.textEdit.cursorForPosition(position)
selectedText = self.ui.textEdit.textCursor().selectedText()
menu = QtWidgets.QMenu()
menu.setStyleSheet("QMenu {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
action_unmark = None
action_start_pos = None
action_end_pos = None
for item in self.code_text:
if cursor.position() >= item['pos0'] and cursor.position() <= item['pos1']:
action_unmark = menu.addAction(_("Unmark"))
action_start_pos = menu.addAction(_("Change start position"))
action_end_pos = menu.addAction(_("Change end position"))
break
if selectedText != "":
if self.ui.treeWidget.currentItem() is not None:
action_mark = menu.addAction(_("Mark"))
action_annotate = menu.addAction(_("Annotate"))
action_copy = menu.addAction(_("Copy to clipboard"))
action_set_bookmark = menu.addAction(_("Set bookmark"))
action = menu.exec_(self.ui.textEdit.mapToGlobal(position))
if action is None:
return
if selectedText != "" and action == action_copy:
self.copy_selected_text_to_clipboard()
if selectedText != "" and self.ui.treeWidget.currentItem() is not None and action == action_mark:
self.mark()
cursor = self.ui.textEdit.cursorForPosition(position)
if selectedText != "" and action == action_annotate:
self.annotate(cursor.position())
if action == action_unmark:
self.unmark(cursor.position())
if action == action_start_pos:
self.change_code_pos(cursor.position(), "start")
if action == action_end_pos:
self.change_code_pos(cursor.position(), "end")
if action == action_set_bookmark:
self.app.settings['bookmark_file_id'] = str(self.filename['id'])
self.app.settings['bookmark_pos'] = str(cursor.position())
def change_code_pos(self, location, start_or_end):
if self.filename == {}:
return
code_list = []
for item in self.code_text:
if location >= item['pos0'] and location <= item['pos1'] and item['owner'] == self.app.settings['codername']:
code_list.append(item)
if code_list == []:
return
code_to_edit = None
if len(code_list) == 1:
code_to_edit = code_list[0]
# multiple codes to select from
if len(code_list) > 1:
ui = DialogSelectItems(self.app, code_list, _("Select code to unmark"), "single")
ok = ui.exec_()
if not ok:
return
code_to_edit = ui.get_selected()
if code_to_edit is None:
return
txt_len = len(self.ui.textEdit.toPlainText())
changed_start = 0
changed_end = 0
int_dialog = QtWidgets.QInputDialog()
int_dialog.setWindowFlags(int_dialog.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
if start_or_end == "start":
max = code_to_edit['pos1'] - code_to_edit['pos0'] - 1
min = -1 * code_to_edit['pos0']
#print("start", min, max)
changed_start, ok = int_dialog.getInt(self, _("Change start position"), _("Change start character position.\nPositive or negative number:"), 0,min,max,1)
if not ok:
return
if start_or_end == "end":
max = txt_len - code_to_edit['pos1']
min = code_to_edit['pos0'] - code_to_edit['pos1'] + 1
#print("end", min, max)
changed_end, ok = int_dialog.getInt(self, _("Change end position"), _("Change end character position.\nPositive or negative number:"), 0,min,max,1)
if not ok:
return
if changed_start == 0 and changed_end == 0:
return
# Update db, reload code_text and highlights
new_pos0 = code_to_edit['pos0'] + changed_start
new_pos1 = code_to_edit['pos1'] + changed_end
cur = self.app.conn.cursor()
sql = "update code_text set pos0=?, pos1=? where cid=? and fid=? and pos0=? and pos1=? and owner=?"
cur.execute(sql,
(new_pos0, new_pos1, code_to_edit['cid'], code_to_edit['fid'], code_to_edit['pos0'], code_to_edit['pos1'], self.app.settings['codername']))
self.app.conn.commit()
self.app.delete_backup = False
self.get_coded_text_update_eventfilter_tooltips()
def copy_selected_text_to_clipboard(self):
""" Copy text to clipboard for external use.
For example adding text to another document. """
selected_text = self.ui.textEdit.textCursor().selectedText()
cb = QtWidgets.QApplication.clipboard()
cb.clear(mode=cb.Clipboard)
cb.setText(selected_text, mode=cb.Clipboard)
def tree_menu(self, position):
""" Context menu for treewidget items.
Add, rename, memo, move or delete code or category. Change code color.
Assign selected text to current hovered code. """
selected_text = self.ui.textEdit.textCursor().selectedText()
menu = QtWidgets.QMenu()
menu.setStyleSheet("QMenu {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
selected = self.ui.treeWidget.currentItem()
#logger.debug("Selected parent: " + selected.parent())
#index = self.ui.treeWidget.currentIndex()
'''ActionAssignSelectedText = None
if selected_text != "" and selected is not None and selected.text(1)[0:3] == 'cid':
ActionAssignSelectedText = menu.addAction("Assign selected text")'''
ActionItemAddCode = menu.addAction(_("Add a new code"))
ActionItemAddCategory = menu.addAction(_("Add a new category"))
ActionItemRename = menu.addAction(_("Rename"))
ActionItemEditMemo = menu.addAction(_("View or edit memo"))
ActionItemDelete = menu.addAction(_("Delete"))
ActionItemChangeColor = None
ActionShowCodedMedia = None
if selected is not None and selected.text(1)[0:3] == 'cid':
ActionItemChangeColor = menu.addAction(_("Change code color"))
ActionShowCodedMedia = menu.addAction(_("Show coded text and media"))
ActionShowCodesLike = menu.addAction(_("Show codes like"))
action = menu.exec_(self.ui.treeWidget.mapToGlobal(position))
if action is not None:
if action == ActionShowCodesLike:
self.show_codes_like()
if selected is not None and action == ActionItemChangeColor:
self.change_code_color(selected)
elif action == ActionItemAddCategory:
self.add_category()
elif action == ActionItemAddCode:
self.add_code()
elif selected is not None and action == ActionItemRename:
self.rename_category_or_code(selected)
elif selected is not None and action == ActionItemEditMemo:
self.add_edit_memo(selected)
elif selected is not None and action == ActionItemDelete:
self.delete_category_or_code(selected)
elif selected is not None and action == ActionShowCodedMedia:
found = None
tofind = int(selected.text(1)[4:])
for code in self.codes:
if code['cid'] == tofind:
found = code
break
if found:
self.coded_media_dialog(found)
def show_codes_like(self):
""" Show all codes if text is empty.
Show selected codes that contain entered text. """
# Input dialog narrow, so code below
dialog = QtWidgets.QInputDialog(None)
dialog.setStyleSheet("* {font-size:" + str(self.app.settings['fontsize']) + "pt} ")
dialog.setWindowTitle(_("Show codes containing"))
dialog.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
dialog.setInputMode(QtWidgets.QInputDialog.TextInput)
dialog.setLabelText(_("Show codes containing text.\n(Blank for all)"))
dialog.resize(200, 20)
ok = dialog.exec_()
if not ok:
return
text = str(dialog.textValue())
root = self.ui.treeWidget.invisibleRootItem()
self.recursive_traverse(root, text)
def recursive_traverse(self, item, text):
""" Find all children codes of this item that match or not and hide or unhide based on 'text'.
Recurse through all child categories.
Called by: show_codes_like
param:
item: a QTreeWidgetItem
text: Text string for matching with code names
"""
#logger.debug("recurse this item:" + item.text(0) + "|" item.text(1))
child_count = item.childCount()
for i in range(child_count):
#print(item.child(i).text(0) + "|" + item.child(i).text(1))
if "cid:" in item.child(i).text(1) and len(text) > 0 and text not in item.child(i).text(0):
item.child(i).setHidden(True)
if "cid:" in item.child(i).text(1) and text == "":
item.child(i).setHidden(False)
self.recursive_traverse(item.child(i), text)
def eventFilter(self, object, event):
""" Using this event filter to identify treeWidgetItem drop events.
http://doc.qt.io/qt-5/qevent.html#Type-enum
QEvent::Drop 63 A drag and drop operation is completed (QDropEvent).
https://stackoverflow.com/questions/28994494/why-does-qtreeview-not-fire-a-drop-or-move-event-during-drag-and-drop
Also use it to detect key events in the textedit. These are used to extend or shrink a text coding.
Only works if clicked on a code (text cursor is in the coded text).
Shrink start and end code positions using alt arrow left and alt arrow right
Extend start and end code positions using shift arrow left, shift arrow right
"""
if object is self.ui.treeWidget.viewport():
if event.type() == QtCore.QEvent.Drop:
item = self.ui.treeWidget.currentItem()
parent = self.ui.treeWidget.itemAt(event.pos())
self.item_moved_update_data(item, parent)
return True
# change start and end code positions using alt arrow left and alt arrow right
# and shift arrow left, shift arrow right
# QtGui.QKeyEvent = 7
if event.type() == 7 and self.ui.textEdit.hasFocus():
key = event.key()
mod = event.modifiers()
cursor_pos = self.ui.textEdit.textCursor().position()
codes_here = []
for item in self.code_text:
if cursor_pos >= item['pos0'] and cursor_pos <= item['pos1'] and item['owner'] == self.app.settings['codername']:
codes_here.append(item)
if len(codes_here) == 1:
if key == QtCore.Qt.Key_Left and mod == QtCore.Qt.AltModifier:
self.shrink_to_left(codes_here[0])
if key == QtCore.Qt.Key_Right and mod == QtCore.Qt.AltModifier:
self.shrink_to_right(codes_here[0])
if key == QtCore.Qt.Key_Left and mod == QtCore.Qt.ShiftModifier:
self.extend_left(codes_here[0])
if key == QtCore.Qt.Key_Right and mod == QtCore.Qt.ShiftModifier:
self.extend_right(codes_here[0])
return False
def extend_left(self, code_):
""" Shift left arrow """
if code_['pos0'] < 1:
return
code_['pos0'] -= 1
cur = self.app.conn.cursor()
sql = "update code_text set pos0=? where cid=? and fid=? and pos0=? and pos1=? and owner=?"
cur.execute(sql,
(code_['pos0'], code_['cid'], code_['fid'], code_['pos0'] + 1, code_['pos1'], self.app.settings['codername']))
self.app.conn.commit()
self.app.delete_backup = False
self.get_coded_text_update_eventfilter_tooltips()
def extend_right(self, code_):
""" Shift right arrow """
if code_['pos1'] +1 >= len(self.ui.textEdit.toPlainText()):
return
code_['pos1'] += 1
cur = self.app.conn.cursor()
sql = "update code_text set pos1=? where cid=? and fid=? and pos0=? and pos1=? and owner=?"
cur.execute(sql,
(code_['pos1'], code_['cid'], code_['fid'], code_['pos0'], code_['pos1'] - 1, self.app.settings['codername']))
self.app.conn.commit()
self.app.delete_backup = False
self.get_coded_text_update_eventfilter_tooltips()
def shrink_to_left(self, code_):
""" Alt left arrow, shrinks code from the right end of the code """
if code_['pos1'] <= code_['pos0'] + 1:
return
code_['pos1'] -= 1
cur = self.app.conn.cursor()
sql = "update code_text set pos1=? where cid=? and fid=? and pos0=? and pos1=? and owner=?"
cur.execute(sql,
(code_['pos1'], code_['cid'], code_['fid'], code_['pos0'], code_['pos1'] + 1, self.app.settings['codername']))
self.app.conn.commit()
self.app.delete_backup = False
self.get_coded_text_update_eventfilter_tooltips()
def shrink_to_right(self, code_):
""" Alt right arrow shrinks code from the left end of the code """
if code_['pos0'] >= code_['pos1'] - 1:
return
code_['pos0'] += 1
cur = self.app.conn.cursor()
sql = "update code_text set pos0=? where cid=? and fid=? and pos0=? and pos1=? and owner=?"
cur.execute(sql,
(code_['pos0'], code_['cid'], code_['fid'], code_['pos0'] - 1, code_['pos1'], self.app.settings['codername']))
self.app.conn.commit()
self.app.delete_backup = False
self.get_coded_text_update_eventfilter_tooltips()
def coded_media_dialog(self, data):
""" Display all coded media for this code, in a separate modal dialog.
Coded media comes from ALL files and ALL coders.
Called from tree_menu
param:
data: code dictionary
"""
ui = DialogInformation(self.app, "Coded text : " + data['name'], " ")
cur = self.app.conn.cursor()
CODENAME = 0
COLOR = 1
SOURCE_NAME = 2
POS0 = 3
POS1 = 4
SELTEXT = 5
OWNER = 6
sql = "select code_name.name, color, source.name, pos0, pos1, seltext, code_text.owner from "
sql += "code_text "
sql += " join code_name on code_name.cid = code_text.cid join source on fid = source.id "
sql += " where code_name.cid =" + str(data['cid']) + " "
sql += " order by source.name, pos0, code_text.owner "
cur.execute(sql)
results = cur.fetchall()
# Text
for row in results:
title = '<span style=\"background-color:' + row[COLOR] + '\">'
title += " File: <em>" + row[SOURCE_NAME] + "</em></span>"
title += ", Coder: <em>" + row[OWNER] + "</em> "
title += ", " + str(row[POS0]) + " - " + str(row[POS1])
ui.ui.textEdit.insertHtml(title)
ui.ui.textEdit.append(row[SELTEXT] + "\n\n")
# Images
sql = "select code_name.name, color, source.name, x1, y1, width, height,"
sql += "code_image.owner, source.mediapath, source.id, code_image.memo "
sql += " from code_image join code_name "
sql += "on code_name.cid = code_image.cid join source on code_image.id = source.id "
sql += "where code_name.cid =" + str(data['cid']) + " "
sql += " order by source.name, code_image.owner "
cur.execute(sql)
results = cur.fetchall()
for counter, row in enumerate(results):
ui.ui.textEdit.insertHtml('<span style=\"background-color:' + row[COLOR] + '\">File: ' + row[8] + '</span>')
ui.ui.textEdit.insertHtml('<br />Coder: ' + row[7] + '<br />')
img = {'mediapath': row[8], 'x1': row[3], 'y1': row[4], 'width': row[5], 'height': row[6]}
self.put_image_into_textedit(img, counter, ui.ui.textEdit)
ui.ui.textEdit.append("Memo: " + row[10] + "\n\n")
# Media
sql = "select code_name.name, color, source.name, pos0, pos1, code_av.memo, "
sql += "code_av.owner, source.mediapath, source.id from code_av join code_name "
sql += "on code_name.cid = code_av.cid join source on code_av.id = source.id "
sql += "where code_name.cid = " + str(data['cid']) + " "
sql += " order by source.name, code_av.owner "
cur.execute(sql)
results = cur.fetchall()
for row in results:
ui.ui.textEdit.insertHtml('<span style=\"background-color:' + row[COLOR] + '\">File: ' + row[7] + '</span>')
start = msecs_to_mins_and_secs(row[3])
end = msecs_to_mins_and_secs(row[4])
ui.ui.textEdit.insertHtml('<br />[' + start + ' - ' + end + '] Coder: ' + row[6])
ui.ui.textEdit.append("Memo: " + row[5] + "\n\n")
ui.exec_()
def put_image_into_textedit(self, img, counter, text_edit):
""" Scale image, add resource to document, insert image.
A counter is important as each image slice needs a unique name, counter adds
the uniqueness to the name.
Called by: coded_media_dialog
param:
img: image data dictionary with file location and width, height, position data
counter: a changing counter is needed to make discrete different images
text_edit: the widget that shows the data
"""
path = self.app.project_path + img['mediapath']
document = text_edit.document()
image = QtGui.QImageReader(path).read()
image = image.copy(img['x1'], img['y1'], img['width'], img['height'])
# scale to max 300 wide or high. perhaps add option to change maximum limit?
scaler = 1.0
scaler_w = 1.0
scaler_h = 1.0
if image.width() > 300:
scaler_w = 300 / image.width()
if image.height() > 300:
scaler_h = 300 / image.height()
if scaler_w < scaler_h:
scaler = scaler_w
else:
scaler = scaler_h
# need unique image names or the same image from the same path is reproduced
imagename = self.app.project_path + '/images/' + str(counter) + '-' + img['mediapath']
url = QtCore.QUrl(imagename)
document.addResource(QtGui.QTextDocument.ImageResource, url, QtCore.QVariant(image))
cursor = text_edit.textCursor()
image_format = QtGui.QTextImageFormat()
image_format.setWidth(image.width() * scaler)
image_format.setHeight(image.height() * scaler)
image_format.setName(url.toString())
cursor.insertImage(image_format)
text_edit.insertHtml("<br />")
def item_moved_update_data(self, item, parent):
""" Called from drop event in treeWidget view port.
identify code or category to move.
Also merge codes if one code is dropped on another code. """
# find the category in the list
if item.text(1)[0:3] == 'cat':
found = -1
for i in range(0, len(self.categories)):
if self.categories[i]['catid'] == int(item.text(1)[6:]):
found = i
if found == -1:
return
if parent is None:
self.categories[found]['supercatid'] = None
else:
if parent.text(1).split(':')[0] == 'cid':
# parent is code (leaf) cannot add child
return
supercatid = int(parent.text(1).split(':')[1])
if supercatid == self.categories[found]['catid']:
# something went wrong
return
self.categories[found]['supercatid'] = supercatid
cur = self.app.conn.cursor()
cur.execute("update code_cat set supercatid=? where catid=?",
[self.categories[found]['supercatid'], self.categories[found]['catid']])
self.app.conn.commit()
self.update_dialog_codes_and_categories()
self.app.delete_backup = False
return
# find the code in the list
if item.text(1)[0:3] == 'cid':
found = -1
for i in range(0, len(self.codes)):
if self.codes[i]['cid'] == int(item.text(1)[4:]):
found = i
if found == -1:
return
if parent is None:
self.codes[found]['catid'] = None
else:
if parent.text(1).split(':')[0] == 'cid':
# parent is code (leaf) cannot add child, but can merge
self.merge_codes(self.codes[found], parent)
return
catid = int(parent.text(1).split(':')[1])
self.codes[found]['catid'] = catid
cur = self.app.conn.cursor()
cur.execute("update code_name set catid=? where cid=?",
[self.codes[found]['catid'], self.codes[found]['cid']])
self.app.conn.commit()
self.app.delete_backup = False
self.update_dialog_codes_and_categories()
def merge_codes(self, item, parent):
""" Merge code or category with another code or category.
Called by item_moved_update_data when a code is moved onto another code. """
msg = _("Merge code: ") + item['name'] + _(" into code: ") + parent.text(0)
reply = QtWidgets.QMessageBox.question(None, _('Merge codes'),
msg, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return
cur = self.app.conn.cursor()
old_cid = item['cid']
new_cid = int(parent.text(1).split(':')[1])
try:
cur.execute("update code_text set cid=? where cid=?", [new_cid, old_cid])
cur.execute("update code_av set cid=? where cid=?", [new_cid, old_cid])
cur.execute("update code_image set cid=? where cid=?", [new_cid, old_cid])
self.app.conn.commit()
except Exception as e:
e = str(e)
msg = _("Cannot merge codes, unmark overlapping text first. ") + "\n" + str(e)
QtWidgets.QMessageBox.information(None, _("Cannot merge"), msg)
return
cur.execute("delete from code_name where cid=?", [old_cid, ])
self.app.conn.commit()
self.app.delete_backup = False
msg = msg.replace("\n", " ")
self.parent_textEdit.append(msg)
self.update_dialog_codes_and_categories()
# update filter for tooltip
self.eventFilterTT.setCodes(self.code_text, self.codes)
def add_code(self):
""" Use add_item dialog to get new code text. Add_code_name dialog checks for
duplicate code name. A random color is selected for the code.
New code is added to data and database. """
ui = DialogAddItemName(self.app, self.codes, _("Add new code"), _("Code name"))
ui.exec_()
code_name = ui.get_new_name()
if code_name is None:
return
code_color = colors[randint(0, len(colors) - 1)]
item = {'name': code_name, 'memo': "", 'owner': self.app.settings['codername'],
'date': datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S"),'catid': None,
'color': code_color}
cur = self.app.conn.cursor()
cur.execute("insert into code_name (name,memo,owner,date,catid,color) values(?,?,?,?,?,?)"
, (item['name'], item['memo'], item['owner'], item['date'], item['catid'], item['color']))
self.app.conn.commit()
self.app.delete_backup = False
cur.execute("select last_insert_rowid()")
cid = cur.fetchone()[0]
item['cid'] = cid
self.parent_textEdit.append(_("New code: ") + item['name'])
self.update_dialog_codes_and_categories()
self.get_coded_text_update_eventfilter_tooltips()
def update_dialog_codes_and_categories(self):
""" Update code and category tree in DialogCodeImage, DialogCodeAV,
DialogCodeText, DialogReportCodes.
Not using isinstance for other classes as could not import the classes to test
against. There was an import error.
Using try except blocks for each instance, as instance may have been deleted. """
for d in self.dialog_list:
if isinstance(d, DialogCodeText):
try:
d.get_codes_and_categories()
d.fill_tree()
d.unlight()
d.highlight()
d.get_coded_text_update_eventfilter_tooltips()
except RuntimeError as e:
pass
if str(type(d)) == "<class 'view_av.DialogCodeAV'>":
try:
d.get_codes_and_categories()
d.fill_tree()
d.load_segments()
d.unlight()
d.highlight()
d.get_coded_text_update_eventfilter_tooltips()
except RuntimeError as e:
pass