forked from bpbible/bpbible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manage_topics_frame.py
1279 lines (1067 loc) · 43.6 KB
/
manage_topics_frame.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
import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
import guiconfig
import events
from passage_list import (get_primary_passage_list_manager,
lookup_passage_entry, PassageList, PassageEntry)
from xrc.manage_topics_xrc import (xrcManageTopicsFrame,
xrcPassageDetailsPanel, xrcTopicDetailsPanel)
from xrc.xrc_util import attach_unknown_control
from gui import guiutil
from manage_topics_operations import (ManageTopicsOperations,
CircularDataException, BaseOperationsContext)
from topic_selector import TopicSelector
from swlib.pysw import VerseList
from util.i18n import N_
from util import osutils
from util.observerlist import ObserverList
class ManageTopicsFrame(xrcManageTopicsFrame):
def __init__(self, parent):
super(ManageTopicsFrame, self).__init__(parent)
attach_unknown_control("topic_tree", lambda parent: TopicTree(self, parent), self)
attach_unknown_control("topic_selector", TopicSelector, self)
attach_unknown_control("passage_list_ctrl", lambda parent: PassageListCtrl(self, parent), self)
self.SetIcons(guiconfig.icons)
self._manager = get_primary_passage_list_manager()
self._operations_context = OperationsContext(self)
self._operations_manager = ManageTopicsOperations(
passage_list_manager=self._manager,
context=self._operations_context
)
self._operations_manager.undo_available_changed_observers \
+= self._undo_available_changed
self._operations_manager.paste_available_changed_observers \
+= self._paste_available_changed
self._paste_available_changed()
self._undo_available_changed()
self._selected_topic = None
# The topic that currently has passages displayed in the passage list
# control.
self._passage_list_topic = None
self.is_passage_selected = False
self.selected_passages = []
self.topic_selector.topic_changed_observers.add_observer(self._set_selected_topic)
self._setup_item_details_panel()
self._init_passage_list_ctrl_headers()
self._setup_passage_list_ctrl()
self._setup_topic_tree()
self._bind_events()
self.Size = (725, 590)
self.passage_list_splitter.SashGravity = 1.0
wx.CallAfter(self.passage_list_splitter.SetSashPosition, 340)
self._set_selected_topic(self._manager)
def _bind_events(self):
self.Bind(wx.EVT_CLOSE, self._on_close)
guiutil.add_close_window_esc_accelerator(self, self.Close)
self.topic_tree.on_selection_changed += self._selected_topic_changed
self.topic_tree.Bind(wx.EVT_TREE_ITEM_GETTOOLTIP, self._get_topic_tool_tip)
self.topic_tree.Bind(wx.EVT_TREE_END_LABEL_EDIT, self._end_topic_label_edit)
self.topic_tree.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self._begin_topic_label_edit)
self.topic_tree.Bind(wx.EVT_TREE_ITEM_MENU, self._show_topic_context_menu)
self.passage_list_ctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self._passage_selection_changed)
self.passage_list_ctrl.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._passage_selection_changed)
self.passage_list_ctrl.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._passage_activated)
self.passage_list_ctrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._show_passage_context_menu)
# Trap the events with the topic tree and the passage list when they
# get focus, so that we can know which one last got focus for our
# copy and paste operations.
self.topic_tree.Bind(wx.EVT_SET_FOCUS, self._topic_tree_got_focus)
self.passage_list_ctrl.Bind(wx.EVT_SET_FOCUS, self._passage_list_got_focus)
self.passage_list_ctrl.Bind(wx.EVT_KEY_UP, self._on_char)
self.topic_tree.Bind(wx.EVT_KEY_UP, self._on_char)
for tool in ("add_topic_tool", "add_passage_tool", "cut_tool",
"copy_tool", "copy_text_tool", "paste_tool", "delete_tool",
"undo_tool", "redo_tool", "sort_order_toggle_tool"):
handler = lambda event, tool=tool: self._perform_toolbar_action(event, tool)
self.toolbar.Bind(wx.EVT_TOOL, handler, id=wx.xrc.XRCID(tool))
def _setup_topic_tree(self):
root = self.topic_tree.AddRoot(_("Topics"))
self.topic_tree.SetPyData(root, self._manager)
self._add_sub_topics(self._manager, root)
self.topic_tree.Expand(root)
def select_topic_and_passage(self, topic, passage_entry):
"""Selects the given topic in the tree, and the given passage entry
in the passage list.
This allows the correct topic and passage to be displayed when a tag
is clicked on.
This assumes that the passage entry is one of the passages in the
topic.
"""
self._set_selected_topic(topic)
if passage_entry not in topic.passages:
return
index = topic.passages.index(passage_entry)
self._select_list_entry_by_index(index)
self.passage_list_ctrl.SetFocus()
wx.CallAfter(lambda: self.passage_list_ctrl.EnsureVisible(index))
def _get_tree_selected_topic(self):
selection = self.topic_tree.GetSelection()
if not selection.IsOk():
return None
return self.topic_tree.GetPyData(selection)
def _set_selected_topic(self, topic):
if topic is self.selected_topic:
return
tree_item = self._find_topic(self.topic_tree.GetRootItem(), topic)
if tree_item is None:
tree_item = self.topic_tree.GetRootItem()
self.topic_tree.SelectItem(tree_item)
self.topic_tree.EnsureVisible(tree_item)
return tree_item
def _selected_topic_changed(self, item):
# Topic nodes are selected as they are dragged past, but we shouldn't
# change the selected topic and passage list until the dragging has
# been finished.
if self.topic_tree._dragging:
return
selected_topic = self._get_tree_selected_topic()
if selected_topic is None:
return
self.selected_topic = selected_topic
self._setup_passage_list_ctrl()
self._setup_order_passages_by()
self.Title = self._get_title()
def get_selected_topic(self):
return self._selected_topic
def set_selected_topic(self, new_topic):
if new_topic is not None:
new_topic.order_passages_by_observers += self._setup_order_passages_by
if self._selected_topic is not None:
self._selected_topic.order_passages_by_observers -= self._setup_order_passages_by
self._selected_topic = new_topic
self.selected_passages = []
self._change_topic_details(new_topic)
self.topic_selector.selected_topic = new_topic
selected_topic = property(get_selected_topic, set_selected_topic)
def _find_topic(self, tree_item, topic):
if self.topic_tree.GetPyData(tree_item) is topic:
return tree_item
id, cookie = self.topic_tree.GetFirstChild(tree_item)
while id.IsOk():
node = self._find_topic(id, topic)
if node is not None:
return node
id, cookie = self.topic_tree.GetNextChild(tree_item, cookie)
def _get_title(self):
"""Gets a title for the frame, based on the currently selected topic."""
topic = self.selected_topic
title = _("Manage Topics")
if topic is not self._manager:
title = "%s - %s" % (topic.full_name, title)
return title
def _setup_order_passages_by(self):
self.toolbar.ToggleTool(
wx.xrc.XRCID("sort_order_toggle_tool"),
bool(TOPIC_ORDER_BACKEND_OPTIONS.index(self.selected_topic.order_passages_by))
)
def _add_sub_topics(self, parent_list, parent_node):
parent_list.add_subtopic_observers.add_observer(
self._add_new_topic_node,
(parent_node,))
parent_list.remove_subtopic_observers.add_observer(
self._remove_topic_node,
(parent_node,))
parent_list.name_changed_observers.add_observer(
self._rename_topic_node,
(parent_node,))
for subtopic in parent_list.subtopics:
self._add_topic_node(subtopic, parent_node)
def _add_topic_node(self, passage_list, parent_node):
if passage_list.is_special_topic:
return
node = self.topic_tree.AppendItem(parent_node, passage_list.name)
self.topic_tree.SetPyData(node, passage_list)
self._add_sub_topics(passage_list, node)
def _add_new_topic_node(self, parent_node, topic):
self._add_topic_node(topic, parent_node)
def _remove_topic_node(self, parent_node, topic):
topic_node = self._find_topic(parent_node, topic)
self.topic_tree.Delete(topic_node)
self._remove_observers(topic)
def _rename_topic_node(self, parent_node, new_name):
self.topic_tree.SetItemText(parent_node, new_name)
def _get_topic_tool_tip(self, event):
"""Gets the description for a topic.
Note that this is Windows only, but it doesn't appear that there is
any way for us to make our own tool tips without tracking the
underlying window's mouse movements.
"""
event.SetToolTip(self.topic_tree.GetPyData(event.GetItem()).description)
def _begin_topic_label_edit(self, event):
"""This event is used to stop us editing the root node."""
if event.GetItem() == self.topic_tree.RootItem:
event.Veto()
def _end_topic_label_edit(self, event):
"""This event is used to update the names of topics.
Any topic node can be edited, and its name will then be set based on
the new label text.
"""
if not event.IsEditCancelled():
topic = self.topic_tree.GetPyData(event.GetItem())
self._operations_manager.set_topic_name(topic, event.GetLabel())
def _on_char(self, event):
"""Handles all keyboard shortcuts."""
guiutil.dispatch_keypress(self._get_actions(), event)
def _get_actions(self):
"""Returns a list of actions to be used when handling keyboard
shortcuts.
"""
actions = {
(ord("C"), wx.MOD_CMD): self._operations_manager.copy,
(ord("X"), wx.MOD_CMD): self._operations_manager.cut,
(ord("V"), wx.MOD_CMD): self._safe_paste,
wx.WXK_DELETE: self._delete,
(ord("Z"), wx.MOD_CMD): self._operations_manager.undo,
(ord("Y"), wx.MOD_CMD): self._operations_manager.redo,
(ord("A"), wx.MOD_CMD): self._select_all_passages,
}
if not self._operations_manager.can_undo:
del actions[(ord("Z"), wx.MOD_CMD)]
if not self._operations_manager.can_redo:
del actions[(ord("Y"), wx.MOD_CMD)]
return actions
def _perform_toolbar_action(self, event, tool_id):
"""Performs the action requested from the toolbar."""
event.Skip()
if self.selected_topic is None:
return
actions = {
"add_topic_tool": lambda: self._create_topic(self.selected_topic),
"add_passage_tool":
lambda: self._create_passage(self.selected_topic),
"copy_tool": self._operations_manager.copy,
"copy_text_tool": self._copy_as_text,
"cut_tool": self._operations_manager.cut,
"paste_tool": self._safe_paste,
"delete_tool": self._delete,
"undo_tool": self._operations_manager.undo,
"redo_tool": self._operations_manager.redo,
"sort_order_toggle_tool": self._sort_order_toggled,
}
actions[tool_id]()
def _undo_available_changed(self):
"""Enables or disables the undo and redo toolbar buttons,
based on whether these actions are available.
"""
self.toolbar.EnableTool(wx.xrc.XRCID("undo_tool"),
self._operations_manager.can_undo)
self.toolbar.EnableTool(wx.xrc.XRCID("redo_tool"),
self._operations_manager.can_redo)
def _paste_available_changed(self):
"""Enables or disables the paste toolbar button."""
self.toolbar.EnableTool(wx.xrc.XRCID("paste_tool"),
self._operations_manager.can_paste)
def _show_topic_context_menu(self, event):
"""Shows the context menu for a topic in the topic tree."""
if not event.Item:
event.Skip()
return
self.selected_topic = self.topic_tree.GetPyData(event.Item)
menu = wx.Menu()
item = menu.Append(wx.ID_ANY, _("&New Topic"))
self.Bind(wx.EVT_MENU,
lambda e: self._create_topic(self.selected_topic),
id=item.Id)
item = menu.Append(wx.ID_ANY, _("Add &Passage"))
self.Bind(wx.EVT_MENU,
lambda e: self._create_passage(self.selected_topic),
id=item.Id)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY, _("Cu&t"))
self.Bind(wx.EVT_MENU,
lambda e: self._operations_manager.cut(),
id=item.Id)
item = menu.Append(wx.ID_ANY, _("&Copy"))
self.Bind(wx.EVT_MENU,
lambda e: self._operations_manager.copy(),
id=item.Id)
item = menu.Append(wx.ID_ANY, _("&Paste"))
self.Bind(wx.EVT_MENU,
lambda e: self._safe_paste(),
id=item.Id)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY, _("Delete &Topic"))
self.Bind(wx.EVT_MENU,
lambda e: self._delete(),
id=item.Id)
self.topic_tree.PopupMenu(menu)
menu.Destroy()
def _copy_as_text(self):
guiconfig.mainfrm.copy(self._get_current_topic_text())
def _get_current_topic_text(self):
if self.selected_topic is None:
return u""
text = self.selected_topic.full_name
if self.selected_topic.description:
text += u"\n" + self.selected_topic.description.strip()
passage_text = u"\n".join(self._passage_entry_text(passage_entry)
for passage_entry in self.selected_topic.passages)
if passage_text:
text += u"\n\n" + passage_text
return text.strip()
def _passage_entry_text(self, passage_entry):
"""Gets the text for the given passage entry with its comment."""
text = passage_entry.passage.GetBestRange(userOutput=True)
if passage_entry.comment:
text = u"%s: %s" % (text, passage_entry.comment.strip())
return text
@guiutil.frozen
def _safe_paste(self, operation=None):
"""A wrapper around the operations manager paste operation that
catches the CircularDataException and displays an error message.
"""
if operation is None:
operation = self._operations_manager.paste
try:
operation()
except CircularDataException:
wx.MessageBox(_("Cannot copy the topic to one of its children."),
_("Copy Topic"), wx.OK | wx.ICON_ERROR, self)
@guiutil.frozen
def _delete(self):
"""Deletes the currently selected item while keeping the GUI frozen."""
if not self.is_passage_selected and self.selected_topic is self._manager:
wx.MessageBox(_("Cannot delete the base topic."),
_("Delete Topic"), wx.OK | wx.ICON_ERROR, self)
return
self._operations_manager.delete()
@guiutil.frozen
def _sort_order_toggled(self):
is_ordered = self.toolbar.GetToolState(wx.xrc.XRCID("sort_order_toggle_tool"))
order_passages_by = TOPIC_ORDER_BACKEND_OPTIONS[int(is_ordered)]
self._operations_manager.set_order_passages_by(
self.selected_topic,
order_passages_by
)
def _create_topic(self, topic, creation_function=None):
new_topic = self._operations_manager.add_new_topic(creation_function)
self._set_selected_topic(new_topic)
self.topic_details_panel.focus()
self.topic_details_panel.combine_action = True
def save_search_results(self, search_string, search_results):
assert search_string
self.topic_tree.SetFocus()
name = _(u"Search: %s") % search_string
description = _(u"Results from the search `%s'.") % search_string
# Tags are not displayed by default for saved search results because
# they are not really user created and it looks dubious having tags
# "Search: My search" littering the screen.
self._create_topic(self._manager,
lambda: PassageList.create_from_verse_list(name, search_results, description, display_tag=False)
)
def _create_passage(self, topic):
self._set_selected_topic(topic)
passage = PassageEntry(None)
self._change_passage_details([passage])
self.passage_details_panel.begin_create_passage(topic, passage)
def _on_close(self, event):
self._remove_observers(self._manager)
self._remove_passage_list_observers()
self._manager.save()
event.Skip()
def _remove_observers(self, parent_topic):
if parent_topic.is_special_topic:
return
parent_topic.add_subtopic_observers.remove(self._add_new_topic_node)
parent_topic.remove_subtopic_observers.remove(self._remove_topic_node)
parent_topic.name_changed_observers.remove(self._rename_topic_node)
for subtopic in parent_topic.subtopics:
self._remove_observers(subtopic)
def _init_passage_list_ctrl_headers(self):
self.passage_list_ctrl.InsertColumn(0, _("Passage"))
self.passage_list_ctrl.InsertColumn(1, _("Comment"))
@guiutil.frozen
def _setup_passage_list_ctrl(self):
self._remove_passage_list_observers()
self.passage_list_ctrl.DeleteAllItems()
self._passage_list_topic = self.selected_topic
if self._passage_list_topic is None:
return
self._add_passage_list_observers()
for index, passage_entry in enumerate(self.selected_topic.passages):
self._insert_topic_passage(passage_entry, index)
# No longer needed, since we allow multiple selection.
#if self.selected_topic.passages:
# self._select_list_entry_by_index(0)
def _add_passage_list_observers(self):
self._passage_list_topic.add_passage_observers += self._insert_topic_passage
self._passage_list_topic.remove_passage_observers += self._remove_topic_passage
self._passage_list_topic.passage_order_changed_observers += self._passage_order_changed
def _remove_passage_list_observers(self):
if self._passage_list_topic is None:
return
self._passage_list_topic.add_passage_observers -= self._insert_topic_passage
self._passage_list_topic.remove_passage_observers -= self._remove_topic_passage
self._passage_list_topic.passage_order_changed_observers -= self._passage_order_changed
for passage in self._passage_list_topic.passages:
self._remove_passage_list_passage_observers(passage)
def _insert_topic_passage(self, passage_entry, index=None):
if index is None:
index = self._passage_list_topic.passages.index(passage_entry)
self._add_passage_list_passage_observers(passage_entry)
self.passage_list_ctrl.InsertStringItem(index, _passage_str(passage_entry, short=True))
self.passage_list_ctrl.SetStringItem(index, 1, passage_entry.comment[:300].replace("\n", " "))
def _remove_topic_passage(self, passage_entry, index):
self.passage_list_ctrl.DeleteItem(index)
self._remove_passage_list_passage_observers(passage_entry)
# XXX: This means the whole selection is being rebuilt every time
# selection changes (e.g. when an item is deleted). Though we freeze
# the GUI this can't be efficient.
# This is the last passage to be removed.
if not self.selected_passages:
if not self._passage_list_topic.passages:
self.selected_passages = []
else:
if len(self._passage_list_topic.passages) == index:
index -= 1
self._select_list_entry_by_index(index)
def _passage_order_changed(self, order_passages_by):
self._setup_passage_list_ctrl()
# Preserve the selection.
pass
def _add_passage_list_passage_observers(self, passage_entry):
passage_entry.passage_changed_observers.add_observer(self._change_passage_passage, (passage_entry,))
passage_entry.comment_changed_observers.add_observer(self._change_passage_comment, (passage_entry,))
def _remove_passage_list_passage_observers(self, passage_entry):
passage_entry.passage_changed_observers -= self._change_passage_passage
passage_entry.comment_changed_observers -= self._change_passage_comment
def _change_passage_passage(self, passage_entry, new_passage):
index = self.selected_topic.passages.index(passage_entry)
self.passage_list_ctrl.SetStringItem(index, 0,
_passage_str(passage_entry, short=True))
def _change_passage_comment(self, passage_entry, new_comment):
index = self.selected_topic.passages.index(passage_entry)
self.passage_list_ctrl.SetStringItem(index, 1, passage_entry.comment[:300].replace("\n", " "))
def _passage_selection_changed(self, event):
self._change_selected_passages()
def _change_selected_passages(self):
self.passage_list_ctrl.SetFocus()
self.selected_passages = self._find_selected_passages()
self._change_passage_details(self.selected_passages)
def _find_selected_passages(self):
topic_passages = self._passage_list_topic.passages
selected_passages = []
index = -1
while 1:
index = self.passage_list_ctrl.GetNextItem(
index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED,
)
if index == -1:
break
try:
selected_passages.append(topic_passages[index])
# Sometimes (when deleting, etc.) it has indices that are valid
# list indices but not passage indices. Just ignore these.
except IndexError:
pass
return selected_passages
def _passage_activated(self, event):
passage_entry = self.selected_topic.passages[event.GetIndex()]
guiconfig.mainfrm.set_bible_ref(str(passage_entry), source=events.TOPIC_LIST)
guiconfig.mainfrm.Raise()
def select_passages(self, passages, focused_passage):
"""Selects the given passages in the passage list control.
Sets the given passage to be the passage on which keyboard focus is.
"""
topic_passages = self._passage_list_topic.passages
passage_indexes = [topic_passages.index(passage) for passage in passages]
focused_passage_index = topic_passages.index(focused_passage)
index = -1
while 1:
index = self.passage_list_ctrl.GetNextItem(index)
if index == -1:
break
current_state = self.passage_list_ctrl.GetItemState(index, wx.LIST_STATE_SELECTED)
if index in passage_indexes:
state = wx.LIST_STATE_SELECTED
if index == focused_passage_index:
state |= wx.LIST_STATE_FOCUSED
self.passage_list_ctrl.SetItemState(index, state, state)
elif current_state & wx.LIST_STATE_SELECTED:
self.passage_list_ctrl.SetItemState(index, 0, wx.LIST_STATE_SELECTED)
def _select_list_entry_by_index(self, index):
"""Selects the entry in the list control with the given index."""
state = wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED
self.passage_list_ctrl.SetItemState(index, state, state)
@guiutil.frozen
def _select_all_passages(self):
if self._passage_list_topic is None:
return
for index in range(len(self._passage_list_topic.passages)):
self._select_list_entry_by_index(index)
def _show_passage_context_menu(self, event):
"""Shows the context menu for a passage in the passage list."""
self._change_selected_passages()
sel = event.GetIndex() != -1
menu = wx.Menu()
item = menu.Append(wx.ID_ANY, _("&Open"))
self.Bind(wx.EVT_MENU,
lambda e: self._passage_activated(event),
id=item.Id)
item.Enable(sel)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY, _("Cu&t"))
self.Bind(wx.EVT_MENU,
lambda e: self._operations_manager.cut(),
id=item.Id)
item.Enable(sel)
item = menu.Append(wx.ID_ANY, _("&Copy"))
self.Bind(wx.EVT_MENU,
lambda e: self._operations_manager.copy(),
id=item.Id)
item.Enable(sel)
item = menu.Append(wx.ID_ANY, _("&Paste"))
self.Bind(wx.EVT_MENU,
lambda e: self._safe_paste(),
id=item.Id)
menu.AppendSeparator()
item = menu.Append(wx.ID_ANY, _("&Delete"))
self.Bind(wx.EVT_MENU,
lambda e: self._delete(),
id=item.Id)
item.Enable(sel)
self.passage_list_ctrl.PopupMenu(menu)
def _topic_tree_got_focus(self, event):
self.is_passage_selected = False
self._change_topic_details(self.selected_topic)
event.Skip()
def _passage_list_got_focus(self, event):
self.is_passage_selected = True
self._change_passage_details(self.selected_passages)
event.Skip()
def _setup_item_details_panel(self):
self.topic_details_panel = TopicDetailsPanel(
self.item_details_panel, self._operations_manager
)
self.topic_details_panel.Hide()
self.item_details_panel.Sizer.Add(self.topic_details_panel, 1, wx.GROW)
self.passage_details_panel = PassageDetailsPanel(
self.item_details_panel, self._operations_manager
)
self.passage_details_panel.Hide()
self.item_details_panel.Sizer.Add(self.passage_details_panel, 1, wx.GROW)
self.item_details_panel_text = wx.StaticText(self.item_details_panel)
self.item_details_panel.Sizer.Add(self.item_details_panel_text, 1, wx.ALIGN_CENTRE)
self.item_details_panel_text.Hide()
def _change_topic_details(self, new_topic):
if new_topic is None:
if self.topic_details_panel.IsShown():
self._display_no_items_selected()
return
if new_topic is self._manager:
self._display_text_in_panel(_("All topics."))
return
self.topic_details_panel.set_topic(new_topic)
self._switch_item_details_current_panel(self.topic_details_panel)
def _change_passage_details(self, selected_passages):
if not selected_passages:
if self.passage_details_panel.IsShown():
self._display_no_items_selected()
return
elif len(selected_passages) == 1:
self.passage_details_panel.set_passage(selected_passages[0])
self._switch_item_details_current_panel(self.passage_details_panel)
else:
self._display_text_in_panel(
_(u"%d passages selected.\n\nSelect a passage to view it.") % len(selected_passages)
)
def _display_no_items_selected(self):
"""When no items have been selected, display this to the user."""
self._display_text_in_panel(_("No items have been selected."))
def _display_text_in_panel(self, text):
"""Displays the given text in the panel instead of either the current
passage or the current topic.
"""
self.item_details_panel_text.Label = text
self._switch_item_details_current_panel(self.item_details_panel_text)
@guiutil.frozen
def _switch_item_details_current_panel(self, new_panel):
"""Makes the given panel the currently displayed item details panel."""
# Avoid dead object errors.
if not self:
return
assert new_panel in self.item_details_panel.Children
for window in self.item_details_panel.Children:
if window is not new_panel:
window.Hide()
new_panel.Show()
self.item_details_panel.Sizer.Layout()
def _passage_str(passage_entry, short=False):
"""Gets a string for the given passage for user output.
If the passage is invalid or not specified, then it will return
an empty string. This is needed when creating a new passage.
"""
if not passage_entry.passage:
return u""
return passage_entry.passage.GetBestRange(userOutput=True, short=short)
# Specifies what type of dragging is currently happening with the topic tree.
# This is needed since it has to select and unselect topics when dragging and
# after dragging differently depending on whether a passage or a topic is
# being dragged.
DRAGGING_NONE = 0
DRAGGING_TOPIC = 1
DRAGGING_PASSAGE = 2
class TopicTree(wx.TreeCtrl):
"""A tree control that handles dragging and dropping for topics.
This contains code taken from the DragAndDrop tree mixin, but adapted to
the topic tree (the DragAndDrop mixin doesn't work when you want to use
the root node), and it selected the nodes it was being dragged past,
meaning that the passage list kept changing.
"""
def __init__(self, topic_frame, *args, **kwargs):
style = wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS | wx.TR_LINES_AT_ROOT
kwargs["style"] = style
self._topic_frame = topic_frame
super(TopicTree, self).__init__(*args, **kwargs)
self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.on_begin_drag)
# bind to the tree selection changing, and then punt off from there
# we do this because non-msw platforms don't fire events for
# programmatic tree selection changed, and we want this uniformly to
# do it
self.Bind(wx.EVT_TREE_SEL_CHANGED, self._selection_changed)
self.on_selection_changed = ObserverList()
self._drag_item = None
self._dragging = DRAGGING_NONE
self.SetDropTarget(TopicPassageDropTarget(self))
def on_begin_drag(self, event):
# We allow only one item to be dragged at a time, to keep it simple
self._drag_item = event.GetItem()
if self._drag_item and self._drag_item != self.GetRootItem():
self.start_dragging_topic()
event.Allow()
else:
event.Veto()
def on_end_drag(self, event):
self.stop_dragging()
drop_target = event.GetItem()
if not drop_target:
drop_target = None
if self.is_valid_drop_target(drop_target):
self.UnselectAll()
if drop_target is not None:
self.SelectItem(drop_target)
self.on_drop_topic(drop_target, self._drag_item)
def on_motion_event(self, event):
if not event.Dragging():
self.stop_dragging()
return
self.on_dragging(event.GetX(), event.GetY())
event.Skip()
def on_dragging(self, x, y):
item, flags = self.HitTest(wx.Point(x, y))
if not item:
item = None
if self.is_valid_drop_target(item):
if self._dragging == DRAGGING_TOPIC:
self.set_cursor_to_dragging()
else:
self.set_cursor_to_dropping_impossible()
if flags & wx.TREE_HITTEST_ONITEMBUTTON:
self.Expand(item)
if self.GetSelections() != [item]:
self.UnselectAll()
if item:
self.SelectItem(item)
def start_dragging_topic(self):
self._dragging = DRAGGING_TOPIC
self.Bind(wx.EVT_MOTION, self.on_motion_event)
self.Bind(wx.EVT_TREE_END_DRAG, self.on_end_drag)
self.set_cursor_to_dragging()
def start_dragging_passage(self, x, y):
self._dragging = DRAGGING_PASSAGE
self._drag_item = self.GetSelection()
self.set_cursor_to_dragging()
self.on_dragging(x, y)
def stop_dragging(self):
self._dragging = DRAGGING_NONE
self.Unbind(wx.EVT_MOTION)
self.Unbind(wx.EVT_TREE_END_DRAG)
self.reset_cursor()
self.UnselectAll()
self.SelectItem(self._drag_item)
def set_cursor_to_dragging(self):
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
def set_cursor_to_dropping_impossible(self):
self.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY))
def reset_cursor(self):
self.SetCursor(wx.NullCursor)
def is_valid_drop_target(self, drop_target):
if not drop_target:
return False
elif self._dragging == DRAGGING_TOPIC:
all_children = self._get_item_children(self._drag_item, recursively=True)
parent = self.GetItemParent(self._drag_item)
return drop_target not in [self._drag_item, parent] + all_children
else:
return True
def on_drop_topic(self, drop_target, drag_target):
drag_topic = self.GetPyData(drag_target)
drop_topic = self.GetPyData(drop_target)
if drag_topic is drop_topic:
return
parent = self.GetParent()
self._topic_frame._safe_paste(
lambda: self._topic_frame._operations_manager.do_copy(
drag_topic, drop_topic, keep_original=False
)
)
def on_drop_passage(self, x, y, selected_passages, drag_result):
"""Drops the given passage onto the topic with the given x and y
coordinates in the tree.
The drag result specifies whether the passage should be copied or
moved.
"""
self.stop_dragging()
drop_target, flags = self.HitTest(wx.Point(x, y))
if not drop_target:
return
if drag_result not in (wx.DragCopy, wx.DragMove):
return
self.UnselectAll()
self.SelectItem(self._drag_item)
drop_topic = self.GetPyData(drop_target)
keep_original = (drag_result != wx.DragMove)
self._topic_frame._operations_manager.do_copy(
selected_passages, drop_topic, keep_original
)
def _get_item_children(self, item=None, recursively=False):
""" Return the children of item as a list. """
if not item:
item = self.GetRootItem()
if not item:
return []
children = []
child, cookie = self.GetFirstChild(item)
while child:
children.append(child)
if recursively:
children.extend(self._get_item_children(child, True))
child, cookie = self.GetNextChild(item, cookie)
return children
def SelectItem(self, item):
# we do this because non-msw platforms don't fire events for
# programmatic tree selection changed, and we want this uniformly to
# do it
res = super(TopicTree, self).SelectItem(item)
if not osutils.is_msw():
self.on_selection_changed(item)
return res
def _selection_changed(self, event):
event.Skip()
self.on_selection_changed(event.Item)
class PassageListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
"""A list control for the passage list in the topic manager.
This is included so that we can get the auto width mixin for the list
control, meaning that the comment will be resized to take all the
available space.
"""
def __init__(self, parent, topic_frame):
# Multiple selection list control.
wx.ListCtrl.__init__(self, parent,
style=wx.LC_REPORT,
)
ListCtrlAutoWidthMixin.__init__(self)
self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._start_drag)
self._drag_index = -1
self._topic_frame = topic_frame
self.SetDropTarget(PassageListDropTarget(self))
def _start_drag(self, event):
"""Starts the drag and registers a drop source for the passage."""
if event.GetIndex() == -1: return
self._drag_index = event.GetIndex()
self.dragged_passages = self._topic_frame.selected_passages
passage_entry = self._topic_frame.selected_topic.passages[self._drag_index]
self.drag_passage_entry = passage_entry
id = passage_entry.get_id()
data = wx.CustomDataObject("PassageEntry")
data.SetData(",".join(str(passage.get_id()) for passage in self.dragged_passages))
drop_source = wx.DropSource(self)
drop_source.SetData(data)
result = drop_source.DoDragDrop(wx.Drag_DefaultMove)
def _handle_drop(self, x, y, drag_result):
"""Handles moving the passage to the new location."""
# It doesn't make any sense reordering passages if it is not in
# natural order.
if self._topic_frame.selected_topic.order_passages_by != "NATURAL_ORDER":
return
index, flags = self.HitTest(wx.Point(x, y))
if index == wx.NOT_FOUND or index == self._drag_index:
return
selected_passages = self._topic_frame.selected_passages
# XXX: This does not handle copying the passage.
self._topic_frame._operations_manager.move_current_passage(new_index=index)
self._topic_frame.select_passages(selected_passages, self.drag_passage_entry)
# list goes blank under wxGTK when dragging and dropping if this is frozen
if not osutils.is_gtk():
_handle_drop = guiutil.frozen(_handle_drop)
class PassageListDropTarget(wx.PyDropTarget):
"""Allows passages to be reordered in the current topic.
XXX: This just displays an ordinary mouse cursor. It doesn't give any
indication whether the passage is going to be dropped above or below the
current topic.
"""
def __init__(self, list_ctrl):
wx.PyDropTarget.__init__(self)
self._list_ctrl = list_ctrl
self.data = wx.CustomDataObject("PassageEntry")
self.SetDataObject(self.data)
def OnData(self, x, y, result):
"""Handles a drop event by passing it back to the list control."""
if self.GetData():
self._list_ctrl._handle_drop(x, y, result)
return result
class TopicPassageDropTarget(wx.PyDropTarget):
"""This drop target allows passages to be moved to different topics in
the topic tree.
"""
def __init__(self, topic_tree):
wx.PyDropTarget.__init__(self)
self._topic_tree = topic_tree
self.data = wx.CustomDataObject("PassageEntry")
self.SetDataObject(self.data)
def OnEnter(self, x, y, result):
self._topic_tree.start_dragging_passage(x, y)
return result
def OnLeave(self):
self._topic_tree.stop_dragging()
def OnDragOver(self, x, y, result):
self._topic_tree.on_dragging(x, y)
return result
def OnData(self, x, y, result):
if self.GetData():
selected_passages = [lookup_passage_entry(int(id))
for id in self.data.GetData().split(",")
]