forked from TreeNote/TreeNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtreenote.py
More file actions
executable file
·2003 lines (1737 loc) · 108 KB
/
treenote.py
File metadata and controls
executable file
·2003 lines (1737 loc) · 108 KB
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/env python3
# -*- coding: utf-8 -*-
#################################################################################
## TreeNote
## A collaboratively usable outliner for personal knowledge and task management.
##
## Copyright (C) 2015 Jan Korte (jan.korte@uni-oldenburg.de)
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, version 3 of the License.
#################################################################################
import json
import logging
import os
import re
import socket
import subprocess
import sys
import textwrap
import time
import traceback
from functools import partial
#
import couchdb
import requests
import sip # needed for pyinstaller, get's removed with 'optimize imports'!
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from resources import qrc_resources # get's removed with 'optimize imports'!
#
import model
import server_model
import tag_model
import version
HIDE_SHOW_THE_SIDEBARS = 'Hide / show the sidebars'
if __debug__:
from pprint import pprint
COLUMNS_HIDDEN = 'columns_hidden'
EDIT_BOOKMARK = 'Edit bookmark'
EDIT_QUICKLINK = 'Edit quick link shortcut'
EXPANDED_ITEMS = 'EXPANDED_ITEMS'
EXPANDED_QUICKLINKS = 'EXPANDED_QUICKLINKS'
SELECTED_ID = 'SELECTED_ID'
CREATE_DB = 'Create bookmark to a database server'
EDIT_DB = 'Edit selected database bookmark'
DEL_DB = 'Delete selected database bookmark'
IMPORT_DB = 'Import JSON file into a new database'
APP_FONT_SIZE = 17 if sys.platform == "darwin" else 14
INITIAL_SIDEBAR_WIDTH = 200
RESOURCE_FOLDER = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'resources' + os.sep
logging.basicConfig(filename=os.path.dirname(os.path.realpath(__file__)) + os.sep + 'treenote.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
def git_tag_to_versionnr(git_tag):
return int(re.sub(r'\.|v', '', git_tag))
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
try: # catch db connect errors
app.focusChanged.connect(self.update_actions)
app.setStyle("Fusion")
self.light_palette = app.palette()
self.light_palette.setColor(QPalette.Highlight, model.SELECTION_LIGHT_BLUE)
self.light_palette.setColor(QPalette.AlternateBase, model.ALTERNATE_BACKGROUND_GRAY_LIGHT)
self.dark_palette = QPalette()
self.dark_palette.setColor(QPalette.Window, model.FOREGROUND_GRAY)
self.dark_palette.setColor(QPalette.WindowText, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.Base, model.BACKGROUND_GRAY)
self.dark_palette.setColor(QPalette.AlternateBase, model.ALTERNATE_BACKGROUND_GRAY)
self.dark_palette.setColor(QPalette.ToolTipBase, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.ToolTipText, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.Text, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.Button, model.FOREGROUND_GRAY)
self.dark_palette.setColor(QPalette.ButtonText, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.BrightText, Qt.red)
self.dark_palette.setColor(QPalette.Link, QColor('#8A9ADD')) # light blue
self.dark_palette.setColor(QPalette.Highlight, model.SELECTION_GRAY)
self.dark_palette.setColor(QPalette.HighlightedText, model.TEXT_GRAY)
self.dark_palette.setColor(QPalette.ToolTipBase, model.FOREGROUND_GRAY)
self.dark_palette.setColor(QPalette.ToolTipText, model.TEXT_GRAY)
self.expanded_ids_list_dict = {} # for restoring the expanded state after a search
self.expanded_quicklink_ids_list_dict = {}
self.removed_id_expanded_state_dict = {} # remember expanded state when moving horizontally (removing then adding at other place)
self.old_search_text = '' # used to detect if user leaves "just focused" state. when that's the case, expanded states are saved
self.server_model = server_model.ServerModel()
self.flatten = False
# load databases
settings = self.getQSettings()
servers = settings.value('databases')
def add_db(bookmark_name, url, db_name, db):
new_server = server_model.Server(bookmark_name, url, db_name, db)
new_server.model.db_change_signal[dict, QAbstractItemModel].connect(self.db_change_signal)
self.server_model.add_server(new_server)
if servers is None:
def load_db_from_file(bookmark_name, db_name):
db = self.get_db('', db_name, create_root=False)
with open(RESOURCE_FOLDER + 'default_databases' + os.sep + db_name + '.json', 'r') as file:
doc_list = json.load(file)
db.update(doc_list)
add_db(bookmark_name, '', db_name, db)
load_db_from_file('Anleitung', 'anleitung')
load_db_from_file('Leere Datenbank', 'leere_datenbank')
load_db_from_file('Gefüllte Vorlage', 'gefuellte_vorlage')
load_db_from_file('Leere Vorlage', 'leere_vorlage')
db = self.get_db('', 'bookmarks', create_root=False)
with open(RESOURCE_FOLDER + 'default_databases' + os.sep + 'bookmarks.json', 'r') as file:
doc_list = json.load(file)
db.update(doc_list)
else:
servers = json.loads(servers)
for bookmark_name, url, db_name in servers:
add_db(bookmark_name, url, db_name, self.get_db(url, db_name, db_name))
# set font-size and padding
self.interface_fontsize = int(settings.value('interface_fontsize', APP_FONT_SIZE)) # second value is loaded, if nothing was saved before in the settings
app.setFont(QFont(model.FONT, self.interface_fontsize))
self.fontsize = int(settings.value('fontsize', APP_FONT_SIZE)) # second value is loaded, if nothing was saved before in the settings
self.padding = int(settings.value('padding', 2))
self.item_model = self.server_model.servers[0].model
self.bookmark_model = model.TreeModel(self.get_db('', 'bookmarks'), header_list=['Bookmarks'])
self.bookmark_model.db_change_signal[dict, QAbstractItemModel].connect(self.db_change_signal)
self.mainSplitter = QSplitter(Qt.Horizontal)
self.mainSplitter.setHandleWidth(0) # thing to grab the splitter
# first column
self.quicklinks_view = QTreeView()
self.quicklinks_view.setModel(self.item_model)
self.quicklinks_view.setItemDelegate(model.BookmarkDelegate(self, self.item_model))
self.quicklinks_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.quicklinks_view.customContextMenuRequested.connect(self.open_edit_shortcut_contextmenu)
self.quicklinks_view.clicked.connect(self.focus_index)
self.quicklinks_view.setHeader(CustomHeaderView('Quick links'))
self.quicklinks_view.header().setToolTip('Focus on the clicked row')
self.quicklinks_view.hideColumn(1)
self.quicklinks_view.hideColumn(2)
self.quicklinks_view.setUniformRowHeights(True) # improves performance
self.quicklinks_view.setAnimated(True)
self.bookmarks_view = QTreeView()
self.bookmarks_view.setModel(self.bookmark_model)
self.bookmarks_view.setItemDelegate(model.BookmarkDelegate(self, self.bookmark_model))
self.bookmarks_view.clicked.connect(self.filter_bookmark_click)
self.bookmarks_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.bookmarks_view.customContextMenuRequested.connect(self.open_edit_bookmark_contextmenu)
self.bookmarks_view.hideColumn(1)
self.bookmarks_view.hideColumn(2)
self.bookmarks_view.setUniformRowHeights(True) # improves performance
filtersHolder = QWidget() # needed to add space
layout = QVBoxLayout()
layout.setContentsMargins(0, 11, 0, 0) # left, top, right, bottom
layout.addWidget(self.bookmarks_view)
filtersHolder.setLayout(layout)
self.servers_view = QTreeView()
self.servers_view.setModel(self.server_model)
self.servers_view.selectionModel().currentChanged.connect(self.change_active_database)
self.servers_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.servers_view.customContextMenuRequested.connect(self.open_edit_server_contextmenu)
self.servers_view.setUniformRowHeights(True) # improves performance
self.servers_view.setStyleSheet('QTreeView:item { padding: ' + str(model.SIDEBARS_PADDING + model.SIDEBARS_PADDING_EXTRA_SPACE) + 'px; }')
servers_view_holder = QWidget() # needed to add space
layout = QVBoxLayout()
layout.setContentsMargins(0, 11, 0, 0) # left, top, right, bottom
layout.addWidget(self.servers_view)
servers_view_holder.setLayout(layout)
self.first_column_splitter = QSplitter(Qt.Vertical)
self.first_column_splitter.setHandleWidth(0)
self.first_column_splitter.setChildrenCollapsible(False)
self.first_column_splitter.addWidget(self.quicklinks_view)
self.first_column_splitter.addWidget(filtersHolder)
self.first_column_splitter.addWidget(servers_view_holder)
self.first_column_splitter.setContentsMargins(0, 11, 6, 0) # left, top, right, bottom
self.first_column_splitter.setStretchFactor(0, 6) # when the window is resized, only quick links shall grow
self.first_column_splitter.setStretchFactor(1, 0)
self.first_column_splitter.setStretchFactor(2, 0)
self.first_column_splitter.setSizes([315, 200, 200])
# second column
self.item_views_splitter = QSplitter(Qt.Horizontal)
self.item_views_splitter.setHandleWidth(0) # thing to grab the splitter
# third column
filter_label = QLabel(self.tr('ADD FILTERS'))
def init_dropdown(key, *item_names):
comboBox = QComboBox()
comboBox.addItems(item_names)
comboBox.currentIndexChanged[str].connect(lambda: self.filter(key, comboBox.currentText()))
return comboBox
self.task_dropdown = init_dropdown('t=', self.tr('all'), model.NOTE, model.TASK, model.DONE_TASK)
self.estimate_dropdown = init_dropdown('e', self.tr('all'), self.tr('<20'), self.tr('=60'), self.tr('>60'))
self.color_dropdown = init_dropdown('c=', self.tr('all'), self.tr('green'), self.tr('yellow'), self.tr('blue'), self.tr('red'), self.tr('orange'), self.tr('no color'))
self.flattenViewCheckBox = QCheckBox('Flatten view')
self.flattenViewCheckBox.clicked.connect(self.filter_flatten_view)
self.hideTagsCheckBox = QCheckBox('Hide rows with a tag')
self.hideTagsCheckBox.clicked.connect(self.filter_hide_tags)
self.hideFutureStartdateCheckBox = QCheckBox('Hide rows with future start date')
self.hideFutureStartdateCheckBox.clicked.connect(self.filter_hide_future_startdate)
self.showOnlyStartdateCheckBox = QCheckBox('Show only rows with a start date')
self.showOnlyStartdateCheckBox.clicked.connect(self.filter_show_only_startdate)
filtersHolder = QWidget() # needed to add space
layout = QGridLayout()
layout.setContentsMargins(0, 4, 6, 0) # left, top, right, bottom
layout.addWidget(filter_label, 0, 0, 1, 2) # fromRow, fromColumn, rowSpan, columnSpan
layout.addWidget(QLabel('Tasks:'), 1, 0, 1, 1)
layout.addWidget(self.task_dropdown, 1, 1, 1, 1)
layout.addWidget(QLabel('Estimate:'), 2, 0, 1, 1)
layout.addWidget(self.estimate_dropdown, 2, 1, 1, 1)
layout.addWidget(QLabel('Color:'), 3, 0, 1, 1)
layout.addWidget(self.color_dropdown, 3, 1, 1, 1)
layout.addWidget(self.flattenViewCheckBox, 4, 0, 1, 2)
layout.addWidget(self.hideTagsCheckBox, 5, 0, 1, 2)
layout.addWidget(self.hideFutureStartdateCheckBox, 6, 0, 1, 2)
layout.addWidget(self.showOnlyStartdateCheckBox, 7, 0, 1, 2)
layout.setColumnStretch(1, 10)
filtersHolder.setLayout(layout)
self.tag_view = QTreeView()
self.tag_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.tag_view.customContextMenuRequested.connect(self.open_rename_tag_contextmenu)
self.tag_view.setModel(tag_model.TagModel())
self.tag_view.selectionModel().selectionChanged.connect(self.filter_tag)
self.tag_view.setUniformRowHeights(True) # improves performance
self.tag_view.setStyleSheet('QTreeView:item { padding: ' + str(model.SIDEBARS_PADDING + model.SIDEBARS_PADDING_EXTRA_SPACE) + 'px; }')
self.tag_view.setAnimated(True)
third_column = QWidget()
layout = QVBoxLayout()
layout.setContentsMargins(6, 6, 0, 0) # left, top, right, bottom
layout.addWidget(filtersHolder)
layout.addWidget(self.tag_view)
third_column.setLayout(layout)
# add columns to main
self.mainSplitter.addWidget(self.first_column_splitter)
self.mainSplitter.addWidget(self.item_views_splitter)
self.mainSplitter.addWidget(third_column)
self.mainSplitter.setStretchFactor(0, 0) # first column has a share of 2
self.mainSplitter.setStretchFactor(1, 6)
self.mainSplitter.setStretchFactor(2, 0)
self.mainSplitter.setSizes([INITIAL_SIDEBAR_WIDTH, 500, 1])
self.setCentralWidget(self.mainSplitter)
# list of actions which depend on a specific view
self.item_view_actions = []
self.item_view_not_editing_actions = []
self.tag_view_actions = []
self.bookmark_view_actions = []
self.quick_links_view_actions = []
self.all_actions = []
def add_action(name, qaction, list=None):
setattr(self, name, qaction)
self.all_actions.append(qaction)
if list is not None:
list.append(qaction)
add_action('addDatabaseAct', QAction(self.tr(CREATE_DB), self, triggered=lambda: DatabaseDialog(self).exec_()))
add_action('deleteDatabaseAct', QAction(self.tr(DEL_DB), self, triggered=self.delete_database))
add_action('editDatabaseAct', QAction(self.tr(EDIT_DB), self, triggered=lambda: DatabaseDialog(self, index=self.servers_view.selectionModel().currentIndex()).exec_()))
add_action('exportDatabaseAct', QAction(self.tr('as JSON file'), self, triggered=self.export_db))
add_action('importDatabaseAct', QAction(self.tr(IMPORT_DB), self, triggered=self.import_db))
add_action('settingsAct', QAction(self.tr('Preferences'), self, shortcut='Ctrl+,', triggered=lambda: SettingsDialog(self).exec_()))
add_action('aboutAct', QAction(self.tr('About'), self, triggered=lambda: AboutBox(self).exec()))
# add_action('unsplitWindowAct', QAction(self.tr('Unsplit window'), self, shortcut='Ctrl+Shift+S', triggered=self.unsplit_window))
# add_action('splitWindowAct', QAction(self.tr('Split window'), self, shortcut='Ctrl+S', triggered=self.split_window))
add_action('editRowAction', QAction(self.tr('Edit row'), self, shortcut='Tab', triggered=self.edit_row), list=self.item_view_actions)
add_action('deleteSelectedRowsAction', QAction(self.tr('Delete selected rows'), self, shortcut='delete', triggered=self.remove_selection), list=self.item_view_actions)
add_action('insertRowAction', QAction(self.tr('Insert row'), self, shortcut='Return', triggered=self.insert_row))
add_action('insertChildAction', QAction(self.tr('Insert child'), self, shortcut='Shift+Return', triggered=self.insert_child), list=self.item_view_actions)
add_action('moveUpAction', QAction(self.tr('Up'), self, shortcut='W', triggered=self.move_up), list=self.item_view_actions)
add_action('moveDownAction', QAction(self.tr('Down'), self, shortcut='S', triggered=self.move_down), list=self.item_view_actions)
add_action('moveLeftAction', QAction(self.tr('Left'), self, shortcut='A', triggered=self.move_left), list=self.item_view_actions)
add_action('moveRightAction', QAction(self.tr('Right'), self, shortcut='D', triggered=self.move_right), list=self.item_view_actions)
add_action('expandAllChildrenAction', QAction(self.tr('Expand all children'), self, shortcut='Alt+Right', triggered=lambda: self.expand_or_collapse_children_selected(True)), list=self.item_view_not_editing_actions)
add_action('collapseAllChildrenAction', QAction(self.tr('Collapse all children'), self, shortcut='Alt+Left', triggered=lambda: self.expand_or_collapse_children_selected(False)), list=self.item_view_not_editing_actions)
add_action('focusSearchBarAction', QAction(self.tr('Focus search bar'), self, shortcut='Ctrl+F', triggered=lambda: self.focused_column().search_bar.setFocus()))
add_action('colorGreenAction', QAction('Green', self, shortcut='G', triggered=lambda: self.color_row('g')), list=self.item_view_actions)
add_action('colorYellowAction', QAction('Yellow', self, shortcut='Y', triggered=lambda: self.color_row('y')), list=self.item_view_actions)
add_action('colorBlueAction', QAction('Blue', self, shortcut='B', triggered=lambda: self.color_row('b')), list=self.item_view_actions)
add_action('colorRedAction', QAction('Red', self, shortcut='R', triggered=lambda: self.color_row('r')), list=self.item_view_actions)
add_action('colorOrangeAction', QAction('Orange', self, shortcut='O', triggered=lambda: self.color_row('o')), list=self.item_view_actions)
add_action('colorNoColorAction', QAction('No color', self, shortcut='N', triggered=lambda: self.color_row('n')), list=self.item_view_actions)
add_action('toggleTaskAction', QAction(self.tr('Toggle: note, todo, done'), self, shortcut='Space', triggered=self.toggle_task), list=self.item_view_actions)
add_action('openLinkAction', QAction(self.tr('Open selected rows containing URLs'), self, shortcut='L', triggered=self.open_links), list=self.item_view_actions)
add_action('renameTagAction', QAction(self.tr('Rename tag'), self, triggered=lambda: RenameTagDialog(self, self.tag_view.currentIndex().data()).exec_()), list=self.tag_view_actions)
add_action('editBookmarkAction', QAction(self.tr(EDIT_BOOKMARK), self, triggered=lambda: BookmarkDialog(self, index=self.bookmarks_view.selectionModel().currentIndex()).exec_()), list=self.bookmark_view_actions)
add_action('moveBookmarkUpAction', QAction(self.tr('Move bookmark up'), self, triggered=self.move_bookmark_up), list=self.bookmark_view_actions)
add_action('moveBookmarkDownAction', QAction(self.tr('Move bookmark down'), self, triggered=self.move_bookmark_down), list=self.bookmark_view_actions)
add_action('deleteBookmarkAction', QAction(self.tr('Delete selected bookmark'), self, triggered=self.remove_bookmark_selection), list=self.bookmark_view_actions)
add_action('editShortcutAction', QAction(self.tr(EDIT_QUICKLINK), self, triggered=lambda: ShortcutDialog(self, self.quicklinks_view.selectionModel().currentIndex()).exec_()), list=self.quick_links_view_actions)
add_action('resetViewAction', QAction(self.tr('Reset search filter'), self, shortcut='esc', triggered=self.reset_view))
add_action('toggleSideBarsAction', QAction(HIDE_SHOW_THE_SIDEBARS, self, shortcut='Ctrl+S', triggered=self.toggle_sidebars))
add_action('toggleProjectAction', QAction(self.tr('Toggle: note, sequential project, parallel project, paused project'), self, shortcut='P', triggered=self.toggle_project), list=self.item_view_actions)
add_action('appendRepeatAction', QAction(self.tr('Repeat'), self, shortcut='Ctrl+R', triggered=self.append_repeat), list=self.item_view_actions)
add_action('goDownAction', QAction(self.tr('Set selected row as root'), self, shortcut='Ctrl+Down', triggered=lambda: self.focus_index(self.current_index())), list=self.item_view_actions)
add_action('goUpAction', QAction(self.tr('Set parent of current root as root'), self, shortcut='Ctrl+Up', triggered=self.focus_parent_of_focused), list=self.item_view_actions)
add_action('increaseInterFaceFontAction', QAction(self.tr('Increase interface font-size'), self, shortcut=QKeySequence(Qt.ALT + Qt.Key_Plus), triggered=lambda: self.change_interface_font_size(+1)))
add_action('decreaseInterFaceFontAction', QAction(self.tr('Decrease interface font-size'), self, shortcut=QKeySequence(Qt.ALT + Qt.Key_Minus), triggered=lambda: self.change_interface_font_size(-1)))
add_action('increaseFontAction', QAction(self.tr('Increase font-size'), self, shortcut='Ctrl++', triggered=lambda: self.change_font_size(+1)))
add_action('decreaseFontAction', QAction(self.tr('Decrease font-size'), self, shortcut='Ctrl+-', triggered=lambda: self.change_font_size(-1)))
add_action('increasePaddingAction', QAction(self.tr('Increase padding'), self, shortcut='Ctrl+Shift++', triggered=lambda: self.change_padding(+1)))
add_action('decreasePaddingAction', QAction(self.tr('Decrease padding'), self, shortcut='Ctrl+Shift+-', triggered=lambda: self.change_padding(-1)))
add_action('cutAction', QAction(self.tr('Cut'), self, shortcut='Ctrl+X', triggered=self.cut), list=self.item_view_actions)
add_action('copyAction', QAction(self.tr('Copy'), self, shortcut='Ctrl+C', triggered=self.copy), list=self.item_view_actions)
add_action('pasteAction', QAction(self.tr('Paste'), self, shortcut='Ctrl+V', triggered=self.paste), list=self.item_view_actions)
add_action('exportPlainTextAction', QAction(self.tr('as a plain text file'), self, triggered=self.export_plain_text))
add_action('expandAction', QAction('Expand selected rows / add children to selection', self, shortcut='Right', triggered=self.expand), list=self.item_view_not_editing_actions)
add_action('collapseAction', QAction('Collapse selected rows / jump to parent', self, shortcut='Left', triggered=self.collapse), list=self.item_view_not_editing_actions)
add_action('quitAction', QAction(self.tr('Quit TreeNote'), self, triggered=lambda: self.close()))
self.databasesMenu = self.menuBar().addMenu(self.tr('Databases list'))
self.databasesMenu.addAction(self.addDatabaseAct)
self.databasesMenu.addAction(self.deleteDatabaseAct)
self.databasesMenu.addAction(self.editDatabaseAct)
self.databasesMenu.addSeparator()
self.exportMenu = self.databasesMenu.addMenu(self.tr('Export selected database'))
self.exportMenu.addAction(self.exportDatabaseAct)
self.exportMenu.addAction(self.exportPlainTextAction)
self.databasesMenu.addAction(self.importDatabaseAct)
self.databasesMenu.addAction(self.settingsAct)
if sys.platform != "darwin":
self.databasesMenu.addSeparator()
self.databasesMenu.addAction(self.quitAction)
self.fileMenu = self.menuBar().addMenu(self.tr('Current database'))
self.fileMenu.addAction(self.editShortcutAction)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.editBookmarkAction)
self.fileMenu.addAction(self.deleteBookmarkAction)
self.fileMenu.addAction(self.moveBookmarkUpAction)
self.fileMenu.addAction(self.moveBookmarkDownAction)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.renameTagAction)
self.structureMenu = self.menuBar().addMenu(self.tr('Edit structure'))
self.structureMenu.addAction(self.insertRowAction)
self.structureMenu.addAction(self.insertChildAction)
self.structureMenu.addAction(self.deleteSelectedRowsAction)
self.structureMenu.addSeparator()
self.structureMenu.addAction(self.cutAction)
self.structureMenu.addAction(self.copyAction)
self.structureMenu.addAction(self.pasteAction)
self.moveMenu = self.structureMenu.addMenu(self.tr('Move selected rows'))
self.moveMenu.addAction(self.moveUpAction)
self.moveMenu.addAction(self.moveDownAction)
self.moveMenu.addAction(self.moveLeftAction)
self.moveMenu.addAction(self.moveRightAction)
self.editRowMenu = self.menuBar().addMenu(self.tr('Edit row'))
self.editRowMenu.addAction(self.editRowAction)
self.editRowMenu.addAction(self.toggleTaskAction)
self.editRowMenu.addAction(self.toggleProjectAction)
self.editRowMenu.addAction(self.appendRepeatAction)
self.colorMenu = self.editRowMenu.addMenu(self.tr('Color selected rows'))
self.colorMenu.addAction(self.colorGreenAction)
self.colorMenu.addAction(self.colorYellowAction)
self.colorMenu.addAction(self.colorBlueAction)
self.colorMenu.addAction(self.colorRedAction)
self.colorMenu.addAction(self.colorOrangeAction)
self.colorMenu.addAction(self.colorNoColorAction)
self.viewMenu = self.menuBar().addMenu(self.tr('View'))
self.viewMenu.addAction(self.goDownAction)
self.viewMenu.addAction(self.goUpAction)
self.viewMenu.addAction(self.resetViewAction)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.expandAction)
self.viewMenu.addAction(self.collapseAction)
self.viewMenu.addAction(self.expandAllChildrenAction)
self.viewMenu.addAction(self.collapseAllChildrenAction)
self.viewMenu.addSeparator()
# self.viewMenu.addAction(self.splitWindowAct)
# self.viewMenu.addAction(self.unsplitWindowAct)
self.viewMenu.addAction(self.openLinkAction)
self.viewMenu.addAction(self.focusSearchBarAction)
self.viewMenu.addAction(self.toggleSideBarsAction)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.increaseFontAction)
self.viewMenu.addAction(self.decreaseFontAction)
self.viewMenu.addAction(self.increasePaddingAction)
self.viewMenu.addAction(self.decreasePaddingAction)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.increaseInterFaceFontAction)
self.viewMenu.addAction(self.decreaseInterFaceFontAction)
self.bookmarkShortcutsMenu = self.menuBar().addMenu(self.tr('Filter shortcuts'))
self.fill_bookmarkShortcutsMenu()
self.helpMenu = self.menuBar().addMenu(self.tr('Help'))
self.helpMenu.addAction(self.aboutAct)
self.make_single_key_menu_shortcuts_work_on_mac(self.all_actions)
self.split_window()
# restore previous position
size = settings.value('size')
if size is not None:
self.resize(size)
self.move(settings.value('pos'))
else:
self.showMaximized()
mainSplitter_state = settings.value('mainSplitter')
if mainSplitter_state is not None:
self.mainSplitter.restoreState(mainSplitter_state)
first_column_splitter_state = settings.value('first_column_splitter')
if first_column_splitter_state is not None:
self.first_column_splitter.restoreState(first_column_splitter_state)
# first (do this before the labels 'second' and 'third')
# restore selected database
last_db_name = settings.value('database')
if last_db_name is not None:
for idx, server in enumerate(self.server_model.servers):
if server.bookmark_name == last_db_name:
server_index = self.server_model.index(idx, 0, QModelIndex())
break
else:
server_index = self.server_model.index(0, 0, QModelIndex()) # top_most_index
self.servers_view.selectionModel().setCurrentIndex(server_index, QItemSelectionModel.ClearAndSelect)
self.change_active_database(server_index)
# second
# restore expanded item states
self.expanded_ids_list_dict = settings.value(EXPANDED_ITEMS, {})
self.expand_saved()
# restore expanded quick link states
self.expanded_quicklink_ids_list_dict = settings.value(EXPANDED_QUICKLINKS, {})
self.expand_saved_quicklinks()
self.reset_view() # inits checkboxes
self.focused_column().view.setFocus()
self.update_actions()
# third
# restore selection
selection_item_id = settings.value(SELECTED_ID, None) # second value is loaded, if nothing was saved before in the settings
if selection_item_id is not None and selection_item_id in self.item_model.id_index_dict:
index = QModelIndex(self.item_model.id_index_dict[selection_item_id])
self.set_selection(index, index)
# restore palette
palette = settings.value('theme')
if palette is not None:
palette = self.light_palette if palette == 'light' else self.dark_palette
else: # set standard theme
palette = self.light_palette
self.set_palette(palette)
# restore splitters
splitter_sizes = settings.value('splitter_sizes')
if splitter_sizes is not None:
self.mainSplitter.restoreState(splitter_sizes)
else:
self.toggle_sidebars()
# restore columns
columns_hidden = settings.value(COLUMNS_HIDDEN)
if columns_hidden or columns_hidden is None:
self.toggle_columns()
self.check_for_software_update()
except Exception as e: # exception handling is in get_db
traceback.print_exc()
logger.exception(e)
def check_for_software_update(self):
self.new_version_data = requests.get('https://api.github.com/repos/treenote/treenote/releases/latest').json()
skip_this_version = self.getQSettings().value('skip_version') is not None and self.getQSettings().value('skip_version') == self.new_version_data['tag_name']
is_newer_version = git_tag_to_versionnr(version.version_nr) < git_tag_to_versionnr(self.new_version_data['tag_name'])
if not skip_this_version and is_newer_version:
UpdateDialog(self).exec_()
return is_newer_version
def make_single_key_menu_shortcuts_work_on_mac(self, actions):
# source: http://thebreakfastpost.com/2014/06/03/single-key-menu-shortcuts-with-qt5-on-osx/
if sys.platform == "darwin":
self.signalMapper = QSignalMapper(self) # This class collects a set of parameterless signals, and re-emits them with a string corresponding to the object that sent the signal.
self.signalMapper.mapped[str].connect(self.evoke_singlekey_action)
for action in actions:
if action is self.moveBookmarkUpAction or \
action is self.moveBookmarkDownAction or \
action is self.deleteBookmarkAction: # the shortcuts of these are already used
continue
keySequence = action.shortcut()
if keySequence.count() == 1:
shortcut = QShortcut(keySequence, self)
shortcut.activated.connect(self.signalMapper.map)
self.signalMapper.setMapping(shortcut, action.text()) # pass the action's name
action.shortcut = QKeySequence() # disable the old shortcut
def expand_saved(self):
current_server_name = self.get_current_server().bookmark_name
if current_server_name in self.expanded_ids_list_dict:
for item_id in self.expanded_ids_list_dict[current_server_name]:
if item_id in self.item_model.id_index_dict:
index = self.item_model.id_index_dict[item_id]
proxy_index = self.filter_proxy_index_from_model_index(QModelIndex(index))
self.focused_column().view.expand(proxy_index)
def expand_saved_quicklinks(self):
current_server_name = self.get_current_server().bookmark_name
if current_server_name in self.expanded_quicklink_ids_list_dict:
for item_id in self.expanded_quicklink_ids_list_dict[current_server_name]:
if item_id in self.item_model.id_index_dict:
index = self.item_model.id_index_dict[item_id]
self.quicklinks_view.expand(QModelIndex(index))
def get_widgets(self):
return [QApplication,
self.focused_column().toggle_sidebars_button,
self.focused_column().toggle_columns_button,
self.focused_column().bookmark_button,
self.focused_column().search_bar,
self.focused_column().view,
self.focused_column().view.verticalScrollBar(),
self.focused_column().view.header(),
self.servers_view,
self.servers_view.header(),
self.tag_view,
self.tag_view.header()]
def set_palette(self, new_palette):
for widget in self.get_widgets():
widget.setPalette(new_palette)
def fill_bookmarkShortcutsMenu(self):
self.bookmarkShortcutsMenu.clear()
map = "function(doc) { \
if (doc." + model.SHORTCUT + " != '' && doc." + model.DELETED + " == '') \
emit(doc, null); \
}"
res = self.bookmark_model.db.query(map)
for row in res:
db_item = self.bookmark_model.db[row.id]
self.bookmarkShortcutsMenu.addAction(QAction(db_item[model.TEXT], self, shortcut=db_item[model.SHORTCUT],
triggered=partial(self.filter_bookmark, row.id)))
for server in self.server_model.servers:
qtmodel = server.model
res = qtmodel.db.query(map)
for row in res:
db_item = qtmodel.db[row.id]
self.bookmarkShortcutsMenu.addAction(QAction(db_item[model.TEXT], self, shortcut=db_item[model.SHORTCUT],
triggered=partial(self.open_quicklink_shortcut, row.id)))
def open_quicklink_shortcut(self, item_id):
index = QModelIndex(self.item_model.id_index_dict[item_id])
self.focus_index(index)
# select row for visual highlight
self.quicklinks_view.selectionModel().select(QItemSelection(index, index), QItemSelectionModel.ClearAndSelect)
def focused_column(self): # returns focused item view holder
for i in range(0, self.item_views_splitter.count()):
if self.item_views_splitter.widget(i).hasFocus():
return self.item_views_splitter.widget(i)
return self.item_views_splitter.widget(0)
def setup_tag_model(self):
self.tag_view.model().setupModelData(self.item_model.get_tags_set())
def expand_node(parent_index, bool_expand):
self.tag_view.setExpanded(parent_index, bool_expand)
for row_num in range(self.tag_view.model().rowCount(parent_index)):
child_index = self.tag_view.model().index(row_num, 0, parent_index)
self.tag_view.setExpanded(parent_index, bool_expand)
expand_node(child_index, bool_expand)
expand_node(self.tag_view.selectionModel().currentIndex(), True)
def export_db(self):
with open(self.filename_from_dialog('.json'), 'w', encoding='utf-8') as file:
row_list = []
map = "function(doc) { \
if (doc." + model.DELETED + " == '') \
emit(doc, null); }"
res = self.item_model.db.query(map, include_docs=True)
file.write(json.dumps([row.doc for row in res], indent=4))
def filename_from_dialog(self, file_type):
proposed_file_name = self.get_current_server().database_name + '_' + QDate.currentDate().toString('yyyy-MM-dd')
file_name = QFileDialog.getSaveFileName(self, "Save", proposed_file_name + file_type, "*" + file_type)
return file_name[0]
def export_plain_text(self):
with open(self.filename_from_dialog('.txt'), 'w', encoding='utf-8') as file:
def tree_as_string(index=QModelIndex(), rows_string=''):
indention_string = (model.indention_level(index) - 1) * '\t'
if index.data() is not None:
rows_string += indention_string + '- ' + index.data().replace('\n', '\n' + indention_string + '\t') + '\n'
for child_nr in range(self.item_model.rowCount(index)):
rows_string = tree_as_string(self.item_model.index(child_nr, 0, index), rows_string)
return rows_string
file.write(tree_as_string())
def import_db(self):
self.file_name = QFileDialog.getOpenFileName(self, "Open", "", "*.json")
if self.file_name[0] != '':
DatabaseDialog(self, import_file_name=self.file_name[0]).exec_()
def get_db(self, url, database_name, create_root=True):
def get_create_db(self, url, new_db_name, connection_attempts=0):
if url != '':
server = couchdb.Server(url)
else: # local db
server = couchdb.Server()
try:
return server, server[new_db_name]
except couchdb.http.ResourceNotFound:
new_db = server.create(new_db_name)
if create_root:
new_db[model.ROOT_ID] = (model.NEW_DB_ITEM.copy())
print("Database does not exist. Created the database.")
return server, new_db
except couchdb.http.Unauthorized as err:
QMessageBox.warning(self, 'Unauthorized', '')
except couchdb.http.ServerError as err:
QMessageBox.warning(self, 'ServerError', '')
except ConnectionRefusedError:
print('couchdb ist not started yet, so wait and try to connect again')
connection_attempts += 1
if connection_attempts < 9:
time.sleep(0.3)
return get_create_db(self, url, new_db_name, connection_attempts=connection_attempts)
else:
QMessageBox.warning(self, '', 'Could not connect to the server. Is the url correct?')
except OSError:
QMessageBox.warning(self, '', 'Could not connect to the server. Synchronisation is disabled. Local changes will be merged when you go online again.')
except Exception as err:
QMessageBox.warning(self, '', 'Unknown Error: Contact the developer.')
local_server, local_db = get_create_db(self, '', database_name)
# if new db is also on a server: enable replication
if url != '':
success = get_create_db(self, url, database_name)
if success:
local_server.replicate(database_name, url + database_name, continuous=True)
local_server.replicate(url + database_name, database_name, continuous=True)
return local_db
def change_active_database(self, new_index, old_index=None):
self.save_expanded_state(old_index)
self.save_expanded_quicklinks_state(old_index)
self.item_model = self.server_model.get_server(new_index).model
self.focused_column().flat_proxy.setSourceModel(self.item_model)
self.focused_column().filter_proxy.setSourceModel(self.item_model)
self.quicklinks_view.setModel(self.item_model)
self.quicklinks_view.setItemDelegate(model.BookmarkDelegate(self, self.item_model))
self.set_undo_actions()
self.old_search_text = 'dont save expanded states of next db when switching to next db'
self.setup_tag_model()
self.expand_saved_quicklinks()
self.reset_view()
def set_undo_actions(self):
if hasattr(self, 'undoAction'):
self.fileMenu.removeAction(self.undoAction)
self.fileMenu.removeAction(self.redoAction)
self.undoAction = self.item_model.undoStack.createUndoAction(self)
self.undoAction.setShortcut('CTRL+Z')
self.redoAction = self.item_model.undoStack.createRedoAction(self)
self.redoAction.setShortcut('CTRL+Shift+Z')
self.make_single_key_menu_shortcuts_work_on_mac([self.undoAction, self.redoAction])
self.fileMenu.insertAction(self.editShortcutAction, self.undoAction)
self.fileMenu.insertAction(self.editShortcutAction, self.redoAction)
self.fileMenu.insertAction(self.editShortcutAction, self.fileMenu.addSeparator())
def closeEvent(self, event):
settings = self.getQSettings()
settings.setValue('pos', self.pos())
settings.setValue('size', self.size())
settings.setValue('mainSplitter', self.mainSplitter.saveState())
settings.setValue('first_column_splitter', self.first_column_splitter.saveState())
settings.setValue('fontsize', self.fontsize)
settings.setValue('interface_fontsize', self.interface_fontsize)
settings.setValue('padding', self.padding)
settings.setValue('splitter_sizes', self.mainSplitter.saveState())
settings.setValue(COLUMNS_HIDDEN, self.focused_column().view.isHeaderHidden())
# save databases
server_list = []
for server in self.server_model.servers:
server_list.append((server.bookmark_name, server.url, server.database_name))
settings.setValue('databases', json.dumps(server_list))
# save expanded items
self.save_expanded_state()
settings.setValue(EXPANDED_ITEMS, self.expanded_ids_list_dict)
# save expanded quicklinks
self.save_expanded_quicklinks_state()
settings.setValue(EXPANDED_QUICKLINKS, self.expanded_quicklink_ids_list_dict)
# save selection
current_index = self.current_index()
settings.setValue(SELECTED_ID, self.focused_column().filter_proxy.getItem(current_index).id)
# save theme
theme = 'light' if app.palette() == self.light_palette else 'dark'
settings.setValue('theme', theme)
# save selected database
settings.setValue('database', self.get_current_server().bookmark_name)
self.item_model.updater.terminate()
if not __debug__: # This constant is true if Python was not started with an -O option. -O turns on basic optimizations.
if sys.platform == "darwin":
subprocess.call(['osascript', '-e', 'tell application "Apache CouchDB" to quit'])
def getQSettings(self):
settings_file = 'treenote_settings.ini'
if __debug__:
settings_file = 'treenote_settings_for_developing.ini' # use fast, small database
return QSettings(os.path.dirname(os.path.realpath(__file__)) + os.sep + settings_file, QSettings.IniFormat)
def get_current_server(self, index=None):
if index is None:
index = self.servers_view.selectionModel().currentIndex()
return self.server_model.get_server(index)
def evoke_singlekey_action(self, action_name): # fix shortcuts for mac
for action in self.all_actions:
if action.text() == action_name and action.isEnabled():
action.trigger()
break
def update_actions(self): # enable / disable menu items whether they are doable right now
def toggle_actions(bool_focused, actions_list):
for action in actions_list:
action.setEnabled(bool_focused)
toggle_actions(len(self.bookmarks_view.selectedIndexes()) > 0, self.bookmark_view_actions)
toggle_actions(len(self.tag_view.selectedIndexes()) > 0, self.tag_view_actions)
toggle_actions(len(self.quicklinks_view.selectedIndexes()) > 0, self.quick_links_view_actions)
# focus is either in a dialog, in item_view or in the search bar
# item actions should be enabled while editing a row, so:
toggle_actions(not self.focused_column().search_bar.hasFocus(), self.item_view_actions)
toggle_actions(self.focused_column().view.state() != QAbstractItemView.EditingState, self.item_view_not_editing_actions)
def toggle_sorting(self, column):
if column == 0: # order manually
self.filter(model.SORT, 'all')
elif column == 1: # order by start date
order = model.DESC # toggle between ASC and DESC
if model.DESC in self.focused_column().search_bar.text():
order = model.ASC
self.append_replace_to_searchbar(model.SORT, model.STARTDATE + order)
elif column == 2: # order by estimate
order = model.DESC
if model.DESC in self.focused_column().search_bar.text():
order = model.ASC
self.append_replace_to_searchbar(model.SORT, model.ESTIMATE + order)
def append_replace_to_searchbar(self, key, value):
search_bar_text = self.focused_column().search_bar.text()
new_text = re.sub(key + r'(\w|=)* ', key + '=' + value + ' ', search_bar_text)
if key not in search_bar_text:
new_text += ' ' + key + '=' + value + ' '
self.set_searchbar_text_and_search(new_text)
@pyqtSlot(bool)
def filter_show_only_startdate(self, only_startdate):
if only_startdate:
self.append_replace_to_searchbar(model.ONLY_START_DATE, 'yes')
else:
self.filter(model.ONLY_START_DATE, 'all')
@pyqtSlot(bool)
def filter_hide_tags(self, filter_hide_tags):
if filter_hide_tags:
self.append_replace_to_searchbar(model.HIDE_TAGS, 'no')
else:
self.filter(model.HIDE_TAGS, 'all')
@pyqtSlot(bool)
def filter_hide_future_startdate(self, hide_future_startdate):
if hide_future_startdate:
self.append_replace_to_searchbar(model.HIDE_FUTURE_START_DATE, 'yes')
else:
self.filter(model.HIDE_FUTURE_START_DATE, 'all')
@pyqtSlot(bool)
def filter_flatten_view(self, flatten):
self.flatten = flatten
if flatten:
self.append_replace_to_searchbar(model.FLATTEN, 'yes')
else:
self.filter(model.FLATTEN, 'all')
def filter_tag(self):
current_index = self.tag_view.selectionModel().currentIndex()
current_tag = self.tag_view.model().data(current_index, tag_model.FULL_PATH)
if current_tag is not None:
search_bar_text = self.focused_column().search_bar.text()
new_text = re.sub(r':\S* ', current_tag + ' ', search_bar_text) # matches a tag
if ':' not in search_bar_text:
new_text += ' ' + current_tag + ' '
self.set_searchbar_text_and_search(new_text)
# set the search bar text according to the selected bookmark
def filter_bookmark(self, item_id):
new_search_bar_text = self.bookmark_model.db[item_id][model.SEARCH_TEXT]
self.set_searchbar_text_and_search(new_search_bar_text)
# if shortcut was used: select bookmarks row for visual highlight
index = self.bookmark_model.id_index_dict[item_id]
self.set_selection(index, index)
@pyqtSlot(QModelIndex)
def filter_bookmark_click(self, index):
item_id = self.bookmark_model.getItem(index).id
self.filter_bookmark(item_id)
# just for one character filters
def filter(self, key, value):
character = value[0]
search_bar_text = self.focused_column().search_bar.text()
# 'all' selected: remove existing same filter
if value == 'all':
search_bar_text = re.sub(' ' + key + r'(<|>|=|\w|\d)* ', '', search_bar_text)
else:
# key is a compare operator. estimate parameters are 'e' and '<20' instead of 't=' and 'n'
if len(key) == 1:
key += value[0]
value = value[1:]
# filter is already in the search bar: replace existing same filter
if re.search(key[0] + r'(<|>|=)', search_bar_text):
search_bar_text = re.sub(key[0] + r'(<|>|=|\w|\d)* ', key + value + ' ', search_bar_text)
else:
# add filter
search_bar_text += ' ' + key + value + ' '
self.set_searchbar_text_and_search(search_bar_text)
def set_searchbar_text_and_search(self, search_bar_text):
self.focused_column().search_bar.setText(search_bar_text)
self.search(search_bar_text)
def filter_proxy_index_from_model_index(self, model_index):
if self.focused_column().filter_proxy.sourceModel() == self.focused_column().flat_proxy:
model_index = self.focused_column().flat_proxy.mapFromSource(model_index)
return self.focused_column().filter_proxy.mapFromSource(model_index)
@pyqtSlot(dict, QAbstractItemModel)
def db_change_signal(self, db_item, source_model):
try:
change_dict = db_item['change']
my_edit = change_dict['user'] == socket.gethostname()
method = change_dict['method']
position = change_dict.get('position')
count = change_dict.get('count')
item_id = db_item['_id']
# ignore cases when the 'update delete marker' change comes before the corresponding item is created
if item_id not in source_model.id_index_dict:
return
index = QModelIndex(source_model.id_index_dict[item_id])
item = source_model.getItem(index)
if method == 'updated':
item.update_attributes(db_item)
if my_edit:
self.set_selection(index, index)
self.setup_tag_model()
source_model.dataChanged.emit(index, index)
# update next available task in a sequential project
project_index = source_model.parent(index)
project_parent_index = source_model.parent(project_index)
available_index = source_model.get_next_available_task(project_index.row(), project_parent_index)
if isinstance(available_index, QModelIndex):
source_model.dataChanged.emit(available_index, available_index)
# update the sort by changing the ordering
sorted_column = self.focused_column().view.header().sortIndicatorSection()
if sorted_column == 1 or sorted_column == 2:
order = self.focused_column().view.header().sortIndicatorOrder()
self.focused_column().view.sortByColumn(sorted_column, 1 - order)
self.focused_column().view.sortByColumn(sorted_column, order)
elif method == 'added':
id_list = change_dict['id_list']
if id_list[0] in [child.id for child in item.childItems]:
return # when pasting parent and children, the children gets automatically loaded, so don't load it manually additionally
source_model.beginInsertRows(index, position, position + len(id_list) - 1)
for i, added_item_id in enumerate(id_list):
item.add_child(position + i, added_item_id, index)
source_model.endInsertRows()
if my_edit:
index_first_added = source_model.index(position, 0, index)
index_last_added = source_model.index(position + len(id_list) - 1, 0, index)
if not change_dict['set_edit_focus']:
self.set_selection(index_first_added, index_last_added)
else: # update selection_and_edit
if index_first_added.model() is self.item_model:
index_first_added = self.filter_proxy_index_from_model_index(index_first_added)
self.focusWidget().selectionModel().setCurrentIndex(index_first_added, QItemSelectionModel.ClearAndSelect)
self.focusWidget().edit(index_first_added)
else: # bookmark
self.bookmarks_view.selectionModel().setCurrentIndex(index_first_added, QItemSelectionModel.ClearAndSelect)
# restore horizontally moved items expanded states + expanded states of their childrens
self.focused_column().view.setAnimated(False)
for child_id in self.removed_id_expanded_state_dict:
child_index = QModelIndex(source_model.id_index_dict[child_id])
proxy_index = self.filter_proxy_index_from_model_index(child_index)
expanded_state = self.removed_id_expanded_state_dict[child_id]
self.focused_column().view.setExpanded(proxy_index, expanded_state)
self.removed_id_expanded_state_dict = {}
self.focused_column().view.setAnimated(True)
elif method == 'removed':
# for move horizontally: save expanded states of moved + children of moved
if source_model is self.item_model: # not for bookmarks
self.removed_id_expanded_state_dict = {}
# save and restore expanded state
def save_children(parent, from_child, to_child):
for child_item in parent.childItems[from_child:to_child]:
child_item_index = QModelIndex(source_model.id_index_dict[child_item.id])
proxy_index = self.filter_proxy_index_from_model_index(child_item_index)
self.removed_id_expanded_state_dict[child_item.id] = self.focused_column().view.isExpanded(proxy_index)
save_children(source_model.getItem(child_item_index), None, None) # save expanded state of all children
save_children(item, position, position + count)
source_model.beginRemoveRows(index, position, position + count - 1)
item.childItems[position:position + count] = []
source_model.endRemoveRows()
self.fill_bookmarkShortcutsMenu()
if my_edit:
# select the item below
if position == len(item.childItems): # there is no item below, so select the one above
position -= 1
if len(item.childItems) > 0:
index_next_child = source_model.index(position, 0, index)
self.set_selection(index_next_child, index_next_child)
else: # all children deleted, select parent
self.set_selection(index, index)
elif method == 'moved_vertical':
if my_edit: # save expanded states
bool_moved_bookmark = source_model is self.bookmark_model # but not for bookmarks
id_expanded_state_dict = {}
if not bool_moved_bookmark:
for child_position, child_item in enumerate(item.childItems):
child_item_index = QModelIndex(source_model.id_index_dict[child_item.id])
proxy_index = self.filter_proxy_index_from_model_index(child_item_index)
id_expanded_state_dict[child_item.id] = self.focused_column().view.isExpanded(proxy_index)
source_model.layoutAboutToBeChanged.emit([QPersistentModelIndex(index)])
up_or_down = change_dict['up_or_down']
if up_or_down == -1:
# if we want to move several items up, we can move the item-above below the selection instead:
item.childItems.insert(position + count - 1, item.childItems.pop(position - 1))
elif up_or_down == +1:
item.childItems.insert(position, item.childItems.pop(position + count))
index_first_moved_item = source_model.index(position + up_or_down, 0, index)
index_last_moved_item = source_model.index(position + up_or_down + count - 1, 0, index)