-
Notifications
You must be signed in to change notification settings - Fork 80
/
balt.py
2292 lines (2045 loc) · 99 KB
/
balt.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 -*-
#
# GPL License and Copyright Notice ============================================
# This file is part of Wrye Bash.
#
# Wrye Bash 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, either version 3
# of the License, or (at your option) any later version.
#
# Wrye Bash is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wrye Bash. If not, see <https://www.gnu.org/licenses/>.
#
# Wrye Bash copyright (C) 2005-2009 Wrye, 2010-2024 Wrye Bash Team
# https://github.com/wrye-bash
#
# =============================================================================
"""Weird module that sits in-between basher and gui on the abstraction tree
now. See #190, its code should be refactored and land in basher and/or gui."""
from __future__ import annotations
import threading
import time
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass
from functools import partial, wraps
from itertools import islice
from typing import final
import wx
import wx.adv
from . import bass, wrye_text # bass for dirs - track
from . import bolt
from .bass import Store
from .bolt import FName, Path, deprint, readme_url, fast_cached_property
from .env import BTN_NO, BTN_YES, TASK_DIALOG_AVAILABLE
from .exception import CancelError, SkipError, StateError
from .gui import BusyCursor, Button, CheckListBox, Color, DialogWindow, \
DirOpen, EventResult, FileOpen, FileOpenMultiple, FileSave, Font, \
GlobalMenu, HLayout, LayoutOptions, ListBox, Links, LogDialog, LogFrame, \
PanelWin, TextArea, UIListCtrl, VLayout, bell, copy_files_to_clipboard, \
DeletionDialog, web_viewer_available, AutoSize, get_shift_down, \
ContinueDialog, askText, askNumber, askYes, askWarning, showOk, showError, \
showWarning, showInfo, TreeNodeFormat, DnDStatusBar, get_image, \
get_color_checks, ImageList
from .gui.base_components import _AComponent
# Print a notice if wx.html2 is missing
if not web_viewer_available():
deprint(u'wx.html2.WebView is missing, features utilizing HTML will be '
u'disabled')
class Resources(object):
#--Icon Bundles
bashRed = None
bashBlue = None
def load_app_icons():
"""Called early in boot, sets up the icon bundles we use as app icons."""
def _get_bundle(img_path):
bundle = wx.IconBundle()
# early boot get_image_dir not ready
bundle.AddIcon(bass.dirs['images'].join(img_path).s)
return bundle
Resources.bashRed = _get_bundle('bash_icons_red.ico')
Resources.bashBlue = _get_bundle('bash_icons_blue.ico')
# Settings --------------------------------------------------------------------
_settings: bolt.Settings = None # must be bound to bass.settings - smelly, #178
# Colors ----------------------------------------------------------------------
colors: dict[str, Color] = {}
# Images ----------------------------------------------------------------------
class ColorChecks(ImageList):
"""ColorChecks ImageList. Used by several UIList classes."""
_int_to_state = {0: 'off', 1: 'on', 2: 'inc', 3: 'imp'}
_statuses = ('purple', 'blue', 'green', 'orange', 'yellow', 'red')
def __init__(self, icons_dict):
super().__init__(16, 16)
self._images = list(icons_dict.items())
def img_dex(self, *args):
if len(args) == 1:
return super().img_dex(args[0])
status, on = args
if status <= -20: color_key = 'purple'
elif status <= -10: color_key = 'blue'
elif status <= 0: color_key = 'green'
elif status <= 10: color_key = 'yellow'
elif status <= 20: color_key = 'orange'
else: color_key = 'red'
return self._indices[f'{self._int_to_state[on]}.{color_key}']
def get_dv_bitmaps():
"""Returns the bitmaps needed for DocumentViewer."""
return tuple(map(get_image, ('back.16', 'forward.16', 'reload.16')))
# Modal Dialogs ---------------------------------------------------------------
#------------------------------------------------------------------------------
def askContinue(parent, message, continueKey=None, title=_('Warning'),
show_cancel=True):
"""Show a modal continue query if continueKey is provided and the value of
the corresponding setting is False. Return True to continue.
Also provides checkbox "Don't show this in the future." to set continueKey
to True. continueKey must end in '.continue' - should be enforced. If
continueKey is None however, it provides a "Don't show this for the rest of
operation." checkbox instead."""
#--ContinueKey set?
if continueKey and _settings.get(continueKey):
return True
#--Generate/show dialog
checkBoxTxt = _("Don't show this in the future.") if continueKey else _(
"Don't show this for the rest of operation.")
result, check = ContinueDialog.display_dialog(parent, message, title,
checkBoxTxt, show_cancel=show_cancel, sizes_dict=_settings)
if continueKey and result and check: # Don't store setting if user canceled
_settings[continueKey] = 1
return result if continueKey else ( # 2: checked 1: OK
(result + bool(check)) if result else False)
#------------------------------------------------------------------------------
def show_log(parent, logText: str | Path, title: str | Path, wrye_log=False,
asDialog=False):
"""Display text in a log window."""
kw = {}
if wrye_log:
kw['dv_bitmaps'] = get_dv_bitmaps() #tell _LogWin we want a wryelog
if not isinstance(logText, Path): # we only pass a Path in the BP log
# convert logText from wtxt to html, pass the path to the html file
##: shouldn't we create a tmp file below?
logPath = bass.dirs['saveBase'].join('WryeLogTemp.html')
css_dir = bass.dirs['mopy'].join('Docs')
wrye_text.convert_wtext_to_html(logPath, logText, css_dir)
logText = logPath
if asDialog:
LogDialog.display_dialog(parent, f'{title}', Resources.bashBlue,
_settings, logText=logText, **kw)
else:
LogFrame(parent, f'{title}', Resources.bashBlue, _settings,
logText=logText, **kw).show_frame()
def playSound(parent,sound):
if not sound: return
sound = wx.adv.Sound(sound)
if sound.IsOk():
sound.Play(wx.adv.SOUND_ASYNC)
else:
showError(parent, _('Invalid sound file %(sound_file)s.') % {
'sound_file': sound})
# Other Windows ---------------------------------------------------------------
#------------------------------------------------------------------------------
class ListEditorData(object):
"""Data capsule for ListEditor. [Abstract]
DEPRECATED: nest into ListEditor"""
def __init__(self,parent):
self.parent = parent #--Parent window.
self.showAdd = False
self.showRename = False
self.showRemove = False
self.showSave = False
self.showCancel = False
#--Editable?
self.showInfo = False
self.infoWeight = 1 #--Controls width of info pane
self.infoReadOnly = True #--Controls whether info pane is editable
#--List
def getItemList(self):
"""Returns item list in correct order."""
raise NotImplementedError # return []
def add(self):
"""Performs add operation. Return new item on success."""
raise NotImplementedError # return None
def rename(self,oldItem,newItem):
"""Renames oldItem to newItem. Return true on success."""
raise NotImplementedError # return False
def remove(self,item):
"""Removes item. Return true on success."""
raise NotImplementedError # return False
#--Info box
def getInfo(self,item):
"""Returns string info on specified item."""
return u''
def setInfo(self, item, info_text):
"""Sets string info on specified item."""
raise NotImplementedError
#--Save/Cancel
def save(self):
"""Handles save button."""
#------------------------------------------------------------------------------
class ListEditor(DialogWindow):
"""Dialog for editing lists."""
def __init__(self, parent, title, lid_data, orderedDict=None):
"""A gui list, with buttons that act on the list items.
Added kwargs to provide extra buttons - this class is built around a
ListEditorData instance which needlessly complicates things - mainly
a bunch of booleans to enable buttons but also the list of data that
corresponds to (read is duplicated by) ListEditor._list_items.
ListEditorData should be nested here.
:param orderedDict: orderedDict['ButtonLabel']=buttonAction
"""
#--Data
self._listEditorData: ListEditorData = lid_data
self._list_items = lid_data.getItemList()
#--GUI
self._size_key = self._listEditorData.__class__.__name__
super().__init__(parent, title, sizes_dict=_settings)
#--List Box
self.listBox = ListBox(self, choices=self._list_items,
onSelect=self.OnSelect)
self.listBox.set_min_size(125, 150)
#--Infobox
self.gInfoBox: TextArea | None = None
if lid_data.showInfo:
editable = not self._listEditorData.infoReadOnly
self.gInfoBox = TextArea(self, editable=editable)
if editable:
self.gInfoBox.on_text_changed.subscribe(self.OnInfoEdit)
# TODO(nycz): GUI size=(130, -1), SUNKEN_BORDER
#--Buttons
buttonSet = [
(lid_data.showAdd, _(u'Add'), self.DoAdd),
(lid_data.showRename, _(u'Rename'), self.DoRename),
(lid_data.showRemove, _(u'Remove'), self.DoRemove),
(lid_data.showSave, _(u'Save'), self.DoSave),
(lid_data.showCancel, _(u'Cancel'), self.DoCancel),
]
for k, v in (orderedDict or {}).items():
buttonSet.append((True, k, v))
if sum(bool(x[0]) for x in buttonSet):
def _btn(btn_label, btn_callback):
new_button = Button(self, btn_label)
new_button.on_clicked.subscribe(btn_callback)
return new_button
new_buttons = [_btn(defLabel, func) for def_flag, defLabel, func
in buttonSet if def_flag]
le_buttons = VLayout(spacing=4, items=new_buttons)
else:
le_buttons = None
#--Layout
layout = VLayout(border=4, spacing=4, items=[
(HLayout(spacing=4, item_expand=True, items=[
(self.listBox, LayoutOptions(weight=1)),
(self.gInfoBox, LayoutOptions(weight=self._listEditorData.infoWeight)),
le_buttons
]), LayoutOptions(weight=1, expand=True))])
#--Done
if self._size_key in _settings['bash.window.sizes']:
layout.apply_to(self)
self.component_position = _settings['bash.window.sizes'][
self._size_key]
else:
layout.apply_to(self, fit=True)
#--List Commands
def DoAdd(self):
"""Adds a new item."""
newItem = self._listEditorData.add()
if newItem and newItem not in self._list_items:
self._list_items = self._listEditorData.getItemList()
index = self._list_items.index(newItem)
self.listBox.lb_insert(newItem, index)
def DoRename(self):
"""Renames selected item."""
selections = self.listBox.lb_get_selections()
if not selections: return bell()
#--Rename it
itemDex = selections[0]
curName = self.listBox.lb_get_str_item_at_index(itemDex)
#--Dialog
newName = askText(self, _(u'Rename to:'), _(u'Rename'), curName)
if not newName or newName == curName:
return
elif newName in self._list_items:
showError(self, _('Name must be unique.'))
elif self._listEditorData.rename(curName,newName):
self._list_items[itemDex] = newName
self.listBox.lb_set_label_at_index(itemDex, newName)
def DoRemove(self):
"""Removes selected item."""
selections = self.listBox.lb_get_selections()
if not selections: return bell()
#--Data
itemDex = selections[0]
item = self._list_items[itemDex]
if not self._listEditorData.remove(item): return
#--GUI
del self._list_items[itemDex]
self.listBox.lb_delete_at_index(itemDex)
if self.gInfoBox:
self.gInfoBox.modified = False
self.gInfoBox.text_content = u''
#--Show Info
def OnSelect(self, _lb_selection_dex, lb_selection_str):
"""Handle show info (item select) event."""
# self._listEditorData.select(lb_selection_str)
if self.gInfoBox:
# self.gInfoBox.DiscardEdits()
self.gInfoBox.text_content = self._listEditorData.getInfo(
lb_selection_str)
def OnInfoEdit(self, new_text):
"""Info box text has been edited."""
selections = self.listBox.lb_get_selections()
if not selections: return bell()
item = self._list_items[selections[0]]
if self.gInfoBox.modified:
self._listEditorData.setInfo(item, new_text)
#--Save/Cancel
def DoSave(self):
"""Handle save button."""
self._listEditorData.save()
_settings['bash.window.sizes'][self._size_key] = self.component_size
self.accept_modal()
def DoCancel(self):
"""Handle cancel button."""
_settings['bash.window.sizes'][self._size_key] = self.component_size
self.cancel_modal()
#------------------------------------------------------------------------------
##: Is there even a good reason for having this as a mixin? AFAICT, the only
# thing this accomplishes is causing pycharm to spit out tons of warnings
class TabDragMixin(object):
"""Mixin for the wx.Notebook class. Enables draggable Tabs.
Events:
EVT_NB_TAB_DRAGGED: Called after a tab has been dragged
event.oldIdex = old tab position (of tab that was moved
event.newIdex = new tab position (of tab that was moved
"""
# PY3: These slots cause a crash on wx4
#__slots__ = ('__dragX','__dragging','__justSwapped')
def __init__(self):
self.__dragX = 0
self.__dragging = wx.NOT_FOUND
self.__justSwapped = wx.NOT_FOUND
# TODO(inf) Test in wx3
if wx.Platform == '__WXMSW__': # CaptureMouse works badly in wxGTK/OSX
self.Bind(wx.EVT_LEFT_DOWN, self.__OnDragStart)
self.Bind(wx.EVT_LEFT_UP, self.__OnDragEnd)
self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.__OnDragEndForced)
self.Bind(wx.EVT_MOTION, self.__OnDragging)
def __OnDragStart(self, event):
if not self.HasCapture(): # or blow up on CaptureMouse()
pos = event.GetPosition()
self.__dragging = self.HitTest(pos)
if self.__dragging != wx.NOT_FOUND:
self.__dragX = pos[0]
self.__justSwapped = wx.NOT_FOUND
self.CaptureMouse()
event.Skip()
def __OnDragEndForced(self, _event):
self.__dragging = wx.NOT_FOUND
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
def __OnDragEnd(self, event):
if self.__dragging != wx.NOT_FOUND:
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
self.__dragging = wx.NOT_FOUND
try:
self.ReleaseMouse()
except AssertionError:
# PyAssertionError: C++ assertion "GetCapture() == this"
# failed at ..\..\src\common\wincmn.cpp(2536) in
# wxWindowBase::ReleaseMouse(): attempt to release mouse,
# but this window hasn't captured it
pass
event.Skip()
def __OnDragging(self, event):
if self.__dragging != wx.NOT_FOUND:
pos = event.GetPosition()
if abs(pos[0] - self.__dragX) > 5:
self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
tabId = self.HitTest(pos)
if tabId == wx.NOT_FOUND or tabId[0] in (wx.NOT_FOUND,self.__dragging[0]):
self.__justSwapped = wx.NOT_FOUND
else:
if self.__justSwapped == tabId[0]:
return
# We'll do the swapping by removing all pages in the way,
# then readding them in the right place. Do this because
# it makes the tab we're dragging not have to refresh, whereas
# if we just removed the current page and reinserted it in the
# correct position, there would be refresh artifacts
newPos = tabId[0]
oldPos = self.__dragging[0]
self.__justSwapped = oldPos
self.__dragging = tabId[:]
if newPos < oldPos:
left,right,step = newPos,oldPos,1
else:
left,right,step = oldPos+1,newPos+1,-1
insert = left+step
addPages = [(self.GetPage(x),self.GetPageText(x)) for x in range(left,right)]
addPages.reverse()
num = right - left
for i in range(num):
self.RemovePage(left)
for page,title in addPages:
self.InsertPage(insert,page,title)
self.drag_tab(newPos)
event.Skip()
#------------------------------------------------------------------------------
class Progress(bolt.Progress):
"""Progress as progress dialog."""
_style = wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_SMOOTH
def __init__(self, title=_('Progress'), message=f'\n{" " * 60}',
parent=None, abort=False, elapsed=True, __style=_style):
if abort: __style |= wx.PD_CAN_ABORT
if elapsed: __style |= wx.PD_ELAPSED_TIME
# TODO(inf) de-wx? Or maybe stop using None as parent for Progress?
parent = _AComponent._resolve(parent) if parent else None
self.dialog = wx.GenericProgressDialog(title, message, 100, parent,
__style)
bolt.Progress.__init__(self)
self.message = message
self.isDestroyed = False
self.prevMessage = u''
self.prevState = -1
self.prevTime = 0
# __enter__ and __exit__ for use with the 'with' statement
def __exit__(self, exc_type, exc_value, exc_traceback): self.Destroy()
def getParent(self): return self.dialog.GetParent()
def setCancel(self, enabled=True, new_message=u''):
# TODO(inf) Hacky, we need to rewrite this class for wx3
new_title = self.dialog.GetTitle()
new_parent = self.dialog.GetParent()
new_style = self.dialog.GetWindowStyle()
if enabled:
new_style |= wx.PD_CAN_ABORT
else:
new_style &= ~wx.PD_CAN_ABORT
self.dialog.Destroy()
self.dialog = wx.GenericProgressDialog(new_title, new_message, 100,
new_parent, new_style)
def _do_progress(self, state, message):
if not self.dialog:
raise StateError(u'Dialog already destroyed.')
elif (state == 0 or state == 1 or (state - self.prevState) > 0.05 or (
time.time() - self.prevTime) > 0.5):
if message != self.prevMessage:
ret = self.dialog.Update(int(state * 100), u'\n'.join(
[self._ellipsize(msg) for msg in message.split(u'\n')]))
else:
ret = self.dialog.Update(int(state*100))
if not ret[0]:
raise CancelError
self.prevMessage = message
self.prevState = state
self.prevTime = time.time()
@staticmethod
def _ellipsize(message):
"""A really ugly way to ellipsize messages that would cause the
progress dialog to resize itself when displaying them. wx2.8's
ProgressDialog had this built in, but wx3.0's is native, and doesn't
have this feature, so we emulate it here. 50 characters was chosen as
the cutoff point, since that produced a reasonably good-looking
progress dialog at 1080p during testing.
:param message: The message to ellipsize.
:return: The ellipsized message."""
if len(message) > 50:
first = message[:24]
second = message[-26:]
return f'{first}…{second}'
return message
def Destroy(self):
if self.dialog:
# self._do_progress(self.full, _(u'Done'))
self.dialog.Destroy()
self.dialog = None
#------------------------------------------------------------------------------
_depth = 0
_lock = threading.Lock() # threading not needed (I just can't omit it)
def conversation(func):
"""Decorator to temporarily unbind RefreshData Link.Frame callback."""
@wraps(func)
def _conversation_wrapper(*args, **kwargs):
global _depth
try:
with _lock: _depth += 1 # hack: allow nested conversations
refresh_bound = Link.Frame.bind_refresh(bind=False)
return func(*args, **kwargs)
finally:
with _lock: # atomic
_depth -= 1
if not _depth and refresh_bound:
Link.Frame.bind_refresh(bind=True)
return _conversation_wrapper
#------------------------------------------------------------------------------
@dataclass(slots=True)
class _ListItemFormat:
icon_key: tuple[str | None, ...] = (None,)
bold: bool = False
italics: bool = False
underline: bool = False
_text_key: str = 'default.text'
_back_key: str = 'default.bkgd'
_back_key_priority = {k: j for j, k in enumerate([
# Plugins -------------------------------------------------------------
'default.bkgd', 'mods.bkgd.size_mismatch', 'mods.bkgd.ghosted',
'mods.bkgd.doubleTime.exists', 'mods.bkgd.doubleTime.load',
# INIs ----------------------------------------------------------------
'ini.bkgd.invalid',
# Installers ----------------------------------------------------------
'installers.bkgd.skipped', 'installers.bkgd.outOfOrder',
'installers.bkgd.dirty'])}
_text_key_priority = {k: j for j, k in enumerate([
# Plugins -------------------------------------------------------------
'default.text',
*(f'mods.text.es{suff}' for suff in ('l', 'o', 'm', 'lm', 'om')),
'mods.text.mergeable', 'mods.text.noMerge', 'mods.text.bashedPatch',
# Installers ----------------------------------------------------------
'installers.text.invalid', 'installers.text.marker',
'installers.text.complex',
])}
def to_tree_node_format(self, parent_uil: UIList):
"""Convert this list item format to an equivalent tree node format,
relative to the specified parent UIList."""
return TreeNodeFormat(
icon_idx=parent_uil.icons.img_dex(*self.icon_key),
back_color=parent_uil.lookup_back_key(self.back_key),
text_color=parent_uil.lookup_text_key(self.text_key),
bold=self.bold, italics=self.italics, underline=self.underline)
@property
def back_key(self) -> str:
return self._back_key
@back_key.setter
def back_key(self, val: str):
self._back_key = max(val, self._back_key,
key=self._back_key_priority.__getitem__)
@property
def text_key(self) -> str:
return self._text_key
@text_key.setter
def text_key(self, val: str):
self._text_key = max(val, self._text_key,
key=self._text_key_priority.__getitem__)
DecoratedTreeDict = dict[FName, tuple[TreeNodeFormat | None,
list[tuple[FName, TreeNodeFormat | None]]]]
class UIList(PanelWin):
"""Offspring of basher.List and balt.Tank, ate its parents."""
# optional menus
column_links = None # A list of all links to show in the column menu
context_links = None # A list of all links to show in item context menus
# A dict mapping category names to a Links instance that will be displayed
# when the corresponding category is clicked on in the global menu. The
# order in which categories are added will also be the display order.
global_links = None
# If set to True, ignore the bash.global_menu setting when determining
# whether to show a column menu or not
_bypass_gm_setting = False
max_items_open = 7 # max number of items one can open without prompt
#--Cols
_min_column_width = 24
# Set of columns that exist, but will never be visible and can't be
# interacted with
banned_columns = set()
#--Style params
_editLabels = False # allow editing the labels - also enables F2 shortcut
_sunkenBorder = True
_singleCell = False # allow only single selections (no ctrl/shift+click)
#--Sorting
nonReversibleCols = {u'Load Order', u'Current Order'}
_default_sort_col = u'File' # override as needed
_sort_keys = {} # sort_keys[col] provides the sort key for this col
_extra_sortings = [] #extra self.methods for fancy sortings - order matters
# Labels, map the (permanent) order of columns to the label generating code
labels = {}
#--DnD
_dndFiles = _dndList = False
_dndColumns = ()
_target_ini = False # pass the target_ini settings on PopulateItem
_copy_paths = False # enable the Ctrl+C shortcut
def __init__(self, parent, keyPrefix, listData=None, panel=None):
super().__init__(parent, wants_chars=True, no_border=False)
self.data_store = listData # never use as local variable name !
try:
Link.Frame.all_uilists[self.data_store.unique_store_key] = self
except AttributeError:
pass # not one of the singleton DataStores
self.panel = panel
#--Settings key
self.keyPrefix = keyPrefix
#--Columns
self.__class__.persistent_columns = {self._default_sort_col}
self._col_index = {} # used in setting column sort indicator
#--gList
self.__gList = UIListCtrl(self, self.__class__._editLabels,
self.__class__._sunkenBorder,
self.__class__._singleCell, self.dndAllow,
dndFiles=self.__class__._dndFiles,
dndList=self.__class__._dndList,
fnDropFiles=self.OnDropFiles,
fnDropIndexes=self.OnDropIndexes)
# Image List: Column sorting order indicators
# explorer style ^ == ascending
self.icons.native_init(recreate=False)
self.sm_up = self.icons.img_dex('arrow.up.16')
self.sm_dn = self.icons.img_dex('arrow.down.16')
self.__gList.set_image_list(self.icons)
if self.__class__._editLabels:
self.__gList.on_edit_label_begin.subscribe(self.OnBeginEditLabel)
self.__gList.on_edit_label_end.subscribe(self.OnLabelEdited)
# gList callbacks
self.__gList.on_lst_col_rclick.subscribe(self.DoColumnMenu)
self.__gList.on_context_menu.subscribe(self.DoItemMenu)
self.__gList.on_lst_col_click.subscribe(self._on_column_click)
self.__gList.on_key_up.subscribe(self._handle_key_up)
self.__gList.on_key_down.subscribe(self._handle_key_down)
#--Events: Columns
self.__gList.on_lst_col_end_drag.subscribe(self._on_column_resize)
#--Events: Items
self.__gList.on_mouse_left_dclick.subscribe(self.OnDClick)
self.__gList.on_item_selected.subscribe(self._handle_select)
self.__gList.on_mouse_left_down.subscribe(self._handle_left_down)
#--Mouse movement
self.mouse_index = None
self.mouseTexts = {} # dictionary item->mouse text
self.mouseTextPrev = u''
self.__gList.on_mouse_motion.subscribe(self._handle_mouse_motion)
self.__gList.on_mouse_leaving.subscribe(self._handle_mouse_leaving)
#--Layout
VLayout(item_expand=True, item_weight=1,
items=[self.__gList]).apply_to(self)
# Columns
self._clean_column_settings()
self.PopulateColumns()
#--Items
self._defaultTextBackground = Color.from_wx(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
self.populate_items()
@fast_cached_property
def icons(self):
return ColorChecks(get_color_checks())
# Column properties
@property
def allCols(self): return list(self.labels)
@property
def all_allowed_cols(self):
return [c for c in self.allCols if c not in self.banned_columns]
@property
def colWidths(self): return _settings[f'{self.keyPrefix}.colWidths']
@property
def colReverse(self):
"""Dictionary column->isReversed."""
return _settings[f'{self.keyPrefix}.colReverse']
@property
def cols(self): return _settings[f'{self.keyPrefix}.cols']
@property
def allowed_cols(self):
"""Version of cols that filters out banned_columns."""
return [c for c in self.cols if c not in self.banned_columns]
@property
def auto_col_widths(self):
return _settings.get(f'{self.keyPrefix}.auto_size_columns',
AutoSize.FIT_MANUAL)
@auto_col_widths.setter
def auto_col_widths(self, val):
_settings[f'{self.keyPrefix}.auto_size_columns'] = val
# the current sort column
@property
def sort_column(self):
return _settings.get(f'{self.keyPrefix}.sort', self._default_sort_col)
@sort_column.setter
def sort_column(self, val): _settings[f'{self.keyPrefix}.sort'] = val
@property
def data_store_key(self) -> str:
"""The unique string key that establishes a correspondence between this
UIList and its data store. Used when information is passed along
between the backend and the GUI (e.g. for refreshing)."""
return self.data_store.unique_store_key
def _handle_select(self, item_key):
self._select(item_key)
def _select(self, item): self.panel.SetDetails(item)
# properties to encapsulate access to the list control
@property
def item_count(self): return self.__gList.lc_item_count()
#--Items ----------------------------------------------
def PopulateItem(self, itemDex=-1, item=None, target_ini_setts=None):
"""Populate ListCtrl for specified item. Either item or itemDex must be
specified.
:param itemDex: the index of the item in the list - must be given if
item is None
:param item: an FName or an int (Masters), the key in self.data
:param target_ini_setts: Cached information about the INI settings.
Used on the INI Edits tab"""
insert = False
allow_cols = self.allowed_cols # property, calculate once
if not allow_cols:
return # No visible columns, nothing to do
if item is not None:
try:
itemDex = self._get_uil_index(item)
except KeyError: # item is not present, so inserting
itemDex = self.item_count # insert at the end
insert = True
else: # no way we're inserting with a None item
item = self.GetItem(itemDex)
str_label = self.labels[allow_cols[0]](self, item)
if insert:
# We're inserting a new item, so we need special handling for the
# first SetItem call - see InsertListCtrlItem
self.__gList.InsertListCtrlItem(
itemDex, str_label, item,
decorate_cb=partial(self.__setUI, item, target_ini_setts))
else:
# The item is already in the UIList, so we only need to redecorate
# and set text for all labels
gItem = self.__gList.get_item_data(itemDex)
self.__setUI(item, target_ini_setts, gItem)
# Piggyback off the SetItem call we need for __setUI to also set
# the first column's text
gItem.SetText(str_label)
self.__gList.set_item_data(gItem)
for col_dex, col in enumerate(allow_cols[1:], start=1):
self.__gList.set_item_data(itemDex, col_dex,
self.labels[col](self, item))
def populate_items(self):
"""Sort items and populate entire list."""
# Make sure to freeze/thaw, all the InsertListCtrlItem calls make the
# GUI lag
with self.pause_drawing():
self.mouseTexts.clear()
items = set(self.data_store)
if self.__class__._target_ini:
# hack for avoiding the syscall in get_ci_settings
t_setts = self.data_store.ini.get_ci_settings()
else:
t_setts = None
#--Update existing items.
index = 0
while index < self.item_count:
item = self.GetItem(index)
if item not in items: self.__gList.RemoveItemAt(index)
else:
self.PopulateItem(itemDex=index, target_ini_setts=t_setts)
items.remove(item)
index += 1
#--Add remaining new items
for item in items:
self.PopulateItem(item=item, target_ini_setts=t_setts)
#--Sort
self.SortItems()
self.autosizeColumns()
__all = ()
_same_item = object()
@final
def RefreshUI(self, *, redraw=__all, to_del=__all,
detail_item=_same_item, focus_list=True,
refresh_others: defaultdict[str, bool] | None = None):
"""Populate specified files or ALL files, sort, set status bar count,
etc. See parameter docs below.
:param redraw: If specified, refresh only these UIList items.
:param to_del: If specified, delete only these UIList items. If both
this and redraw are kept at the default, entirely repopulate this
UIList.
:param focus_list: If True, focus this UIList.
:param refresh_others: A dict mapping unique data store keys (see
bass.Store) to booleans that indicate whether or not to refresh
that tab. If None, no other tab will be refreshed."""
if redraw is to_del is self.__all:
self.populate_items()
else: #--Iterable
# Make sure to freeze/thaw, all the InsertListCtrlItem calls make
# the GUI lag
with self.pause_drawing():
for d in to_del:
self.__gList.RemoveItemAt(self._get_uil_index(d))
for upd in redraw:
self.PopulateItem(item=upd)
#--Sort
self.SortItems()
self.autosizeColumns()
self._refresh_details(redraw, detail_item)
if Link.Frame.notebook.currentPage is self.panel:
# we need to check if our Panel is currently shown because we may
# call Refresh UI of other tabs too - this results for instance in
# mods count flickering when deleting a save in saves tab
Link.Frame.set_status_info(self.panel.sb_count_str(), 2)
if focus_list: self.Focus()
if refresh_others:
if refresh_others[self.data_store_key]:
deprint(f"A tab's {self.data_store_key=} got passed to "
f"refresh_others")
del refresh_others[self.data_store_key]
Link.Frame.distribute_ui_refresh(refresh_others)
def issue_warnings(self,
warn_others: defaultdict[str, bool] | None = None):
"""Show warnings for this tab and any others that are specified."""
final_warn_dict = defaultdict(bool, {self.data_store_key: True})
if warn_others:
final_warn_dict |= warn_others
Link.Frame.distribute_warnings(final_warn_dict)
def _refresh_details(self, redraw, detail_item):
if detail_item is None:
self.panel.ClearDetails()
elif detail_item is not self._same_item:
self.SelectAndShowItem(detail_item)
else: # if it was a single item, refresh details for it
if len(redraw) == 1:
self.SelectAndShowItem(next(iter(redraw)))
else:
self.panel.SetDetails()
def Focus(self):
self.__gList.set_focus()
#--Decorating -------------------------------------------------------------
def set_item_format(self, item, item_format, target_ini_setts):
"""Populate item_format attributes for text and background colors
and set icon, font and mouse text. Responsible (applicable if the
data_store is a FileInfo subclass) for calling getStatus (or
tweak_status in Inis) to update respective info's status."""
pass # screens, bsas
def __setUI(self, fileName, target_ini_setts, gItem):
"""Set font, status icon, background text etc."""
df = _ListItemFormat()
self.set_item_format(fileName, df, target_ini_setts=target_ini_setts)
icon_index = self.icons.img_dex(*df.icon_key)
if icon_index is not None:
gItem.SetImage(icon_index)
gItem.SetTextColour(self.lookup_text_key(df.text_key).to_rgba_tuple())
gItem.SetBackgroundColour(
self.lookup_back_key(df.back_key).to_rgba_tuple())
gItem.SetFont(Font.Style(gItem.GetFont(), strong=df.bold,
slant=df.italics, underline=df.underline))
def lookup_text_key(self, target_text_color: str):
"""Helper method to look up a text color from a list item format."""
if target_text_color:
return colors[target_text_color]
else:
return self.__gList.get_text_color()
def lookup_back_key(self, target_back_color: str):
"""Helper method to look up a background color from a list item
format."""
if target_back_color:
return colors[target_back_color]
else:
return self._defaultTextBackground
def decorate_tree_dict(self, tree_dict: dict[FName, list[FName]],
target_ini_setts=None) -> DecoratedTreeDict:
"""Add appropriate TreeNodeFormat instances to the specified dict
mapping items in this UIList to lists of items in this UIList."""
def _decorate(i):
lif = _ListItemFormat()
# Only run set_item_format when the item is actually present,
# otherwise just use the default settings (we do still have to use
# those since the default text/background colors may have been
# changed from the OS default)
if i in self.data_store:
self.set_item_format(i, lif, target_ini_setts=target_ini_setts)
return lif.to_tree_node_format(self)
return {i: (_decorate(i), [(c, _decorate(c)) for c in i_children])
for i, i_children in tree_dict.items()}
#--Right Click Menus ------------------------------------------------------
def DoColumnMenu(self, evt_col: int):
"""Show column menu.
:param evt_col: The index of the column that the user clicked on."""
if self._pop_menu():
self.column_links.popup_menu(self, evt_col)
return EventResult.FINISH
def _pop_menu(self):
"""Decide if we should pop the columns menu - must be set for one."""
return (self.column_links and not # column menu must be set
self.__gList.ec_rename_prompt_opened() and # See DoItemMenu below
# bash.global_menu == 1 -> Global Menu Only
(self._bypass_gm_setting or _settings['bash.global_menu'] != 1))
def DoItemMenu(self):
"""Show item menu."""
# Don't allow this if we are in the process of renaming because
# various operations in the menus would make the rename prompt lose
# focus, which would leave WB's data stores out of sync with the file
# system, resulting in errors when we go to access the file
if not self.__gList.ec_rename_prompt_opened():
selected = self.GetSelected()
if not selected:
self.DoColumnMenu(0)
elif self.context_links:
self.context_links.popup_menu(self, selected)
return EventResult.FINISH
#--Callbacks --------------------------------------------------------------
def _handle_mouse_motion(self, wrapped_evt, lb_dex_and_flags):
"""Handle mouse entered item by showing tip or similar."""
if wrapped_evt.is_moving:
(itemDex, mouseHitFlag) = lb_dex_and_flags
if itemDex != self.mouse_index:
self.mouse_index = itemDex
if itemDex >= 0:
item = self.GetItem(itemDex) # get the item for this index
item_txt = self.mouseTexts.get(item, u'')
if item_txt != self.mouseTextPrev:
Link.Frame.set_status_info(item_txt)
self.mouseTextPrev = item_txt
def _handle_mouse_leaving(self):
if self.mouse_index is not None:
self.mouse_index = None
Link.Frame.set_status_info(u'')
def _handle_key_up(self, wrapped_evt):
"""Char event: select all items, delete selected items, rename."""
kcode = wrapped_evt.key_code
cmd_down = wrapped_evt.is_cmd_down
if cmd_down and kcode == ord(u'A'): # Ctrl+A - (de)select all
if wrapped_evt.is_shift_down: # deselect all
self.ClearSelected(clear_details=True)
else: # select all
with self.__gList.on_item_selected.pause_subscription(
self._handle_select):
# omit below to leave displayed details
self.panel.ClearDetails()
self.__gList.lc_select_item_at_index(-1) # -1 indicates 'all items'
elif self.__class__._editLabels and kcode == wx.WXK_F2: # F2 - rename
self.Rename()
elif kcode in _wx_delete: # Del - delete selected file(s)
with BusyCursor(): self.DeleteItems(wrapped_evt=wrapped_evt)
elif cmd_down and kcode == ord(u'O'): # Ctrl+O - open data folder
self.open_data_store()
elif cmd_down and kcode == ord('S'): # Ctrl+S - save data
with BusyCursor():
Link.Frame.SaveSettings()
# Ctrl+Num + - auto-size columns to fit contents
elif cmd_down and kcode == wx.WXK_NUMPAD_ADD:
self.auto_col_widths = AutoSize.FIT_CONTENTS
# On Windows, this happens automatically (due to the native widget
# handling it), so all we have to do there is update our internal
# state to match. On all (?, only tested on wxGTK) other platforms
# we have to implement it ourselves
if wx.Platform != '__WXMSW__':
self.autosizeColumns()
# Ctrl+C - copy file(s) to clipboard
elif self.__class__._copy_paths and cmd_down and kcode == ord(u'C'):
copy_files_to_clipboard(
[x.abs_path.s for x in self.GetSelectedInfos()])
else:
return EventResult.CONTINUE