-
Notifications
You must be signed in to change notification settings - Fork 79
/
installer_links.py
1550 lines (1403 loc) · 71.2 KB
/
installer_links.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
#
# =============================================================================
"""Installer*: Menu items for the __item__ menu of the installer tab. Their
window attribute points to the InstallersList singleton. Check before using
IniList singleton - can be None (ini panel not shown).
Installer_Espm_*: Menu items for the Plugin Filter list in the installer tab.
Their window attribute points to the InstallersPanel singleton.
Installer_Subs_*: Menu items for the Sub-Packages list in the installer tab.
Their window attribute points to the InstallersPanel singleton.
"""
import io
import os
import re
import webbrowser
from collections import defaultdict
from functools import wraps
from itertools import chain
from . import BashFrame, INIList, Installers_Link, InstallersDetails
from .belt import InstallerWizard, generateTweakLines
from .dialogs import SyncFromDataEditor
from .frames import InstallerProject_OmodConfigDialog
from .gui_fomod import InstallerFomod
from .. import archives, balt, bass, bolt, bosh, bush, env
from ..balt import AppendableLink, CheckLink, EnabledLink, OneItemLink, \
UIList_Hide
from ..bass import Store
from ..bolt import FName, LogFile, SubProgress, deprint, round_size
from ..bosh import InstallerConverter, converters
from ..exception import CancelError, SkipError, StateError, XMLParsingError
from ..gui import BusyCursor, copy_text_to_clipboard
from ..wbtemp import cleanup_temp_dir
__all__ = ['Installer_Duplicate',
'Installer_OpenSearch', 'Installer_CaptureFomodOutput',
'Installer_OpenTESA', 'Installer_Hide',
u'Installer_Refresh', u'Installer_Move', u'Installer_HasExtraData',
u'Installer_OverrideSkips', u'Installer_SkipVoices',
u'Installer_SkipRefresh', u'Installer_Wizard',
u'Installer_EditWizard', u'Installer_OpenReadme',
u'Installer_Anneal', u'Installer_Install', u'Installer_Uninstall',
'Installer_ArchiveMenu', 'InstallerConverter_Create',
u'InstallerConverter_ConvertMenu', u'InstallerProject_Pack',
u'InstallerArchive_Unpack', u'InstallerProject_ReleasePack',
u'Installer_CopyConflicts', u'Installer_SyncFromData' ,
u'InstallerProject_OmodConfig', u'Installer_ListStructure',
u'Installer_Espm_SelectAll', u'Installer_Espm_DeselectAll',
u'Installer_Espm_List', u'Installer_Espm_Rename',
u'Installer_Espm_Reset', u'Installer_Espm_ResetAll',
u'Installer_Subs_SelectAll', u'Installer_Subs_DeselectAll',
u'Installer_Subs_ToggleSelection',
u'Installer_Subs_ListSubPackages', u'Installer_OpenNexus',
u'Installer_ExportAchlist', u'Installer_Espm_JumpToMod',
'Installer_RunFomod', 'Installer_InstallSmart',
'Installer_EditFomod', 'Installer_ProjectMenu',
'Installer_QuickRefresh']
#------------------------------------------------------------------------------
# Installer Links -------------------------------------------------------------
#------------------------------------------------------------------------------
class _InstallerLink(Installers_Link, EnabledLink):
"""Common methods for installer links."""
def _promptSolidBlockSize(self, title, default_size=0):
return self._askNumber('\n'.join([
_('Use what maximum size for each solid block?'),
_("Enter '0' to use 7z's default size.")]), prompt='MB',
title=title, initial_num=default_size, min_num=0, max_num=102400)
def _with_busy_cursor(func):
@wraps(func)
def _busy(*args, **kwargs):
with BusyCursor():
func(*args, **kwargs)
return _busy
class _SingleInstallable(OneItemLink, _InstallerLink):
def _enable(self):
return super()._enable() and not self._selected_info.is_marker
class _SingleProject(OneItemLink, _InstallerLink):
def _enable(self):
return super()._enable() and self._selected_info.is_project
class _ArchiveOnly(_InstallerLink):
"""_InstallerLink that is only enabled for archives."""
def _enable(self):
return all(inf.is_archive for inf in self.iselected_infos())
class _RefreshingLink(_SingleInstallable):
_overrides_skips = False
@balt.conversation
def Execute(self):
dest_src = self._selected_info.refreshDataSizeCrc()
with balt.Progress(title=_(u'Override Skips')) as progress:
if self._overrides_skips:
self.idata.update_for_overridden_skips(set(dest_src), progress)
self.idata.refresh_ns(progress=progress)
self.window.RefreshUI()
class _NoMarkerLink(_InstallerLink):
"""Installer link that does not accept any markers."""
def _enable(self):
self._installables = self.idata.filterInstallables(self.selected)
return bool(self._installables) and super()._enable()
#------------------------------------------------------------------------------
class _Installer_AWizardLink(_NoMarkerLink):
"""Base class for wizard links."""
def _perform_install(self, sel_package, ui_refresh):
if sel_package.is_active: # If it's currently installed, anneal
title = _('Annealing…')
do_it = self.idata.bain_anneal
else: # Install if it's not installed
title = _('Installing…')
do_it = self.idata.bain_install
with balt.Progress(title) as progress:
do_it([sel_package.fn_key], ui_refresh, progress)
class _Installer_AViewOrEditFile(_SingleInstallable):
"""Base class for View/Edit wizard/FOMOD links."""
def _run_on_archive(self):
"""Returns True if the single installable we've got selected is an
archive."""
return next(self.iselected_infos()).is_archive
class _Installer_AFomod(_InstallerLink):
"""Base class for FOMOD links."""
def _enable(self):
return super()._enable() and all(
i.has_fomod_conf for i in self.iselected_infos())
class Installer_EditFomod(_Installer_AFomod, _Installer_AViewOrEditFile):
"""View or edit the ModuleConfig.xml associated with this package."""
@property
def link_text(self):
return (_('View ModuleConfig…') if self._run_on_archive() else
_('Edit ModuleConfig…'))
@property
def link_help(self):
return (_('View the ModuleConfig.xml associated with this archive.')
if self._run_on_archive() else
_('Edit the ModuleConfig.xml associated with this project.'))
@_with_busy_cursor
def Execute(self): self._selected_info.open_fomod_conf()
class _Installer_ARunFomod(_Installer_AFomod):
"""Base class for FOMOD links that need to run the FOMOD wizard."""
_wants_install_checkbox: bool
@balt.conversation
def Execute(self):
ui_refresh = defaultdict(bool)
# Use list() since we're going to deselect packages
try:
for sel_package in list(self.iselected_infos()):
try:
with BusyCursor():
# Select the package we want to install - posts events
# to set details and update GUI
self.window.SelectItem(sel_package.fn_key)
if sel_package.is_archive: ##: yak identical code in Installer_Wizard
progress = balt.Progress(_('Extracting images…'),
abort=True)
else:
progress = None
try:
fm_wizard = InstallerFomod(self.window,
sel_package, self._wants_install_checkbox,
progress)
except CancelError:
continue
if not fm_wizard.validate_fomod():
# Validation failed and the user chose not to continue
return
fm_wizard.ensureDisplayed()
ret = fm_wizard.run_fomod()
if ret.canceled:
continue
# Now we're ready to execute the link's specific action
self._execute_action(sel_package, ret, ui_refresh)
except XMLParsingError:
deprint('Invalid FOMOD XML syntax:', traceback=True)
self._showError(
_("The ModuleConfig.xml file that comes with "
"%(package_name)s has invalid syntax. Please report "
"this to the mod author so it can be fixed "
"properly. The BashBugDump.log in Wrye Bash's Mopy "
"folder contains additional details, please include "
"it in your report.") % {
'package_name': sel_package.fn_key
}, title=_('Invalid FOMOD XML Syntax'))
finally:
self.window.RefreshUI(refresh_others=ui_refresh)
self.window.issue_warnings(warn_others=ui_refresh)
def _execute_action(self, sel_package, ret, ui_refresh):
raise NotImplementedError
class Installer_RunFomod(_Installer_AWizardLink, _Installer_ARunFomod):
"""Runs the FOMOD installer and installs the output via BAIN."""
_text = _('Run FOMOD…')
_help = _('Run the FOMOD installer and install the output.')
_wants_install_checkbox = True
def _execute_action(self, sel_package, ret, ui_refresh):
# Switch the GUI to FOMOD mode and pass selected files to BAIN
idetails = self.iPanel.detailsPanel
idetails.set_fomod_mode(fomod_enabled=True)
sel_package.extras_dict['fomod_dict_v2'] = ret.install_files
idetails.refreshCurrent(sel_package)
if ret.should_install:
self._perform_install(sel_package, ui_refresh)
class Installer_CaptureFomodOutput(_Installer_ARunFomod):
_text = _dialog_title = _('Capture FOMOD Output…')
_help = _('Run the FOMOD installer and create a new project from the '
'output.')
# There's no point in showing the 'Install this package' checkbox - it
# would have the same behavior as hitting 'Cancel' for this link
_wants_install_checkbox = False
def _execute_action(self, sel_package, ret, ui_refresh):
working_on_archive = sel_package.is_archive
proj_default = (sel_package.abs_path.sbody if working_on_archive
else sel_package.fn_key)
proj_name = self._askFilename(_('Project Name'), proj_default,
inst_type=bosh.InstallerProject, check_exists=False)
if not proj_name:
return
pr_path = bosh.InstallerProject.unique_name(proj_name)
if working_on_archive:
# This is an archive, so we have to use unpackToTemp first
with balt.Progress(_('Unpacking Archive…')) as prog:
src_folder = sel_package.unpackToTemp(
list(ret.install_files), prog)
else:
# This is a project, so we can directly copy the wanted
# files
src_folder = sel_package.abs_path
dst_folder = bass.dirs['installers'].join(pr_path)
dst_folder.makedirs()
srcs_dsts = {
src_folder.join(s): dst_folder.join(df)
for s, d in ret.install_files.items() for df in d
}
env.shellCopy(srcs_dsts, parent=self.window)
if working_on_archive:
# We no longer need the temp directory since we copied everything
# to the final project, so clean it up
cleanup_temp_dir(src_folder)
with balt.Progress(_('Creating Project…')) as prog:
self.idata.new_info(pr_path, prog,
install_order=sel_package.order + 1)
class Installer_EditWizard(_Installer_AViewOrEditFile):
"""View or edit the wizard.txt associated with this package."""
@property
def link_text(self):
return (_('View Wizard…') if self._run_on_archive() else
_('Edit Wizard…'))
@property
def link_help(self):
return (_('View the wizard.txt associated with this archive.')
if self._run_on_archive() else
_('Edit the wizard.txt associated with this project.'))
def _enable(self):
return super()._enable() and bool(self._selected_info.hasWizard)
@_with_busy_cursor
def Execute(self): self._selected_info.open_wizard()
class Installer_Wizard(_Installer_AWizardLink):
"""Runs the install wizard to select sub-packages and filter plugins."""
def __init__(self, *, auto_wizard):
super(Installer_Wizard, self).__init__()
self.bAuto = auto_wizard
self._text = (_('Auto Wizard…') if self.bAuto else
_('Manual Wizard…'))
self._help = (
_(u'Run the install wizard, selecting the default options.')
if self.bAuto else _(u'Run the install wizard.'))
def _enable(self):
return super(Installer_Wizard, self)._enable() and all(
i.hasWizard for i in self.iselected_infos())
@balt.conversation
def Execute(self):
##: Investigate why we have so many refreshCurrents in here.
# Installer_RunFomod has just one!
ui_refresh = defaultdict(bool)
idetails = self.iPanel.detailsPanel
try:
# Use list() since we're going to deselect packages
for sel_package in list(self.iselected_infos()):
with BusyCursor():
# Select the package we want to install - posts events to
# set details and update GUI
self.window.SelectItem(sel_package.fn_key)
# Switch away from FOMOD mode, the wizard may need plugin
# data from BAIN
idetails.set_fomod_mode(fomod_enabled=False)
idetails.refreshCurrent(sel_package)
try:
if sel_package.is_archive: ##: yak identical code in Installer_RunFomod
progress = balt.Progress(_('Extracting images…'),
abort=True)
else:
progress = None
wizard = InstallerWizard(self.window, sel_package,
self.bAuto, progress)
except CancelError:
return
wizard.ensureDisplayed()
ret = wizard.Run()
if ret.canceled:
if isinstance(ret.canceled, str):
self._showWarning(ret.canceled)
idetails.refreshCurrent(sel_package)
continue
sel_package.resetAllEspmNames()
for index in range(len(sel_package.subNames[1:])):
select = (sel_package.subNames[index + 1] in
ret.select_sub_packages)
idetails.gSubList.lb_check_at_index(index, select)
sel_package.subActives[index + 1] = select
idetails.refreshCurrent(sel_package)
# Check the plugins that were selected by the wizard
espm_fns = list(map(FName,
idetails.gEspmList.lb_get_str_items()))
sel_package.espmNots = set()
for index, espm in enumerate(idetails.espm_checklist_fns):
do_check = (espm_fns[index] in ret.select_plugins
or bool(sel_package.espmNots.add(espm)))
idetails.gEspmList.lb_check_at_index(index, do_check)
idetails.refreshCurrent(sel_package)
#Rename the plugins that need renaming
for oldName, renamed in ret.rename_plugins.items():
sel_package.setEspmName(oldName, renamed)
idetails.refreshCurrent(sel_package)
#Install if necessary
if ret.should_install:
self._perform_install(sel_package, ui_refresh)
self._apply_tweaks(sel_package, ret, ui_refresh)
finally:
self.window.RefreshUI(refresh_others=ui_refresh)
self.window.issue_warnings(warn_others=ui_refresh)
def _apply_tweaks(self, installer, ret, ui_refresh):
#Build any ini tweaks
manuallyApply = [] # List of tweaks the user needs to manually apply
lastApplied = None
new_targets = {}
for iniFile, wizardEdits in ret.ini_edits.items():
basen = os.path.basename(os.path.splitext(iniFile)[0])
outFile = bass.dirs[u'ini_tweaks'].join(
f'{installer} - Wizard Tweak [{basen}].ini')
# Use UTF-8 since this came from a wizard.txt which could have
# characters in it that are unencodable in cp1252 - plus this is
# just a tweak, won't be read by the game
with outFile.open(u'w', encoding=u'utf-8') as out:
out.write(u'\n'.join(generateTweakLines(wizardEdits, iniFile)))
out.write(u'\n')
inf = bosh.iniInfos.new_info(outFile.stail, owner=installer.fn_key)
# trigger refresh UI
ui_refresh |= Store.INIS.DO()
# We wont automatically apply tweaks to anything other than
# Oblivion.ini or an ini from this installer
game_ini = bosh.get_game_ini(iniFile, is_abs=False)
if game_ini:
target_path = game_ini.abs_path
target_ini_file = game_ini
else: # suppose that the target ini file is in the Data/ dir
target_path = bass.dirs[u'mods'].join(iniFile)
new_targets[target_path.stail] = target_path
if not (iniFile in installer.ci_dest_sizeCrc and
ret.should_install):
# Can only automatically apply ini tweaks if the ini was
# actually installed. Since BAIN is setup to not auto
# install after the wizard, we'll show a message telling
# the User what tweaks to apply manually.
manuallyApply.append((outFile.stail, iniFile))
continue
target_ini_file = bosh.BestIniFile(target_path)
if INIList.apply_tweaks([inf], target_ini_file):
lastApplied = FName(outFile.stail)
#--Refresh after all the tweaks are applied
if lastApplied is not None:
target_updated = bosh.INIInfos.update_targets(new_targets)
if (ini_uilist := BashFrame.all_uilists[Store.INIS]) is not None:
ini_uilist.panel.detailsPanel.set_choice(
target_path.stail, reset_choices=target_updated)
ini_uilist.panel.ShowPanel(focus_list=False,
detail_item=lastApplied)
ui_refresh[Store.INIS] = False # None or we refreshed in ShowPanel
if manuallyApply:
message = [_('The following INI Tweaks were not automatically '
'applied. Be sure to apply them after installing the '
'package.'), '', '']
message.extend(
f' * {x}\n {_("To: %(tweak_target)s") % {"tweak_target": y}}'
for x, y in manuallyApply)
self._showInfo('\n'.join(message))
class Installer_OpenReadme(_SingleInstallable):
"""Opens the installer's readme if BAIN can find one."""
_text = _(u'Open Readme')
_help = _(u"Open the installer's readme if BAIN can find one")
def _enable(self):
return super()._enable() and bool(self._selected_info.hasReadme)
@_with_busy_cursor
def Execute(self): self._selected_info.open_readme()
#------------------------------------------------------------------------------
class Installer_Anneal(_NoMarkerLink):
"""Anneal all packages."""
_text = _('Anneal')
_help = _('Install any missing files (for active packages) and update '
'the contents of the %(data_folder)s folder to account for '
'install order and configuration changes in the selected '
'packages.') % {'data_folder': bush.game.mods_dir}
def Execute(self):
ui_refresh = defaultdict(bool)
try:
with balt.Progress(_('Annealing…')) as progress:
self.idata.bain_anneal(self._installables, ui_refresh,
progress)
except (CancelError,SkipError):
pass
finally:
self.window.RefreshUI(refresh_others=ui_refresh)
self.window.issue_warnings(warn_others=ui_refresh)
class Installer_Duplicate(_SingleInstallable):
"""Duplicate selected Installer."""
_text = _dialog_title = _('Duplicate…')
@property
def link_help(self):
return _('Duplicate selected %(sel_pkg)s.') % (
{'sel_pkg': self._selected_item})
@balt.conversation
def Execute(self):
"""Duplicate selected Installer."""
is_arch = self._selected_info.is_archive
fn_inst = self._selected_item
r, e = (fn_inst.fn_body, fn_inst.fn_ext) if is_arch else (fn_inst, '')
newName = self._selected_info.unique_key(r, e, add_copy=True)
allowed_exts = {e} if is_arch else set()
msg = _('Duplicate %(target_package)s to:') % {
'target_package': fn_inst}
result = self._askFilename(msg, newName, no_dir=False, ##: True? False?
inst_type=type(self._selected_info), disallow_overwrite=True,
allowed_exts=allowed_exts, use_default_ext=False)
if not result: return
#--Duplicate
with BusyCursor():
self.idata.copy_installer(self._selected_info, result)
self.window.RefreshUI(detail_item=result)
class Installer_Hide(_InstallerLink, UIList_Hide):
"""Installers tab version of the Hide command."""
def _filter_unhideable(self, to_hide_items):
# Can't hide markers, so filter those out
return {h: v for h, v in super()._filter_unhideable(
to_hide_items).items() if not v.is_marker}
class Installer_HasExtraData(CheckLink, _RefreshingLink):
"""Toggle hasExtraData flag on installer."""
_text = _(u'Has Extra Directories')
_help = _(u'Allow installation of files in non-standard directories.')
def _check(self):
return self._enable() and self._selected_info.hasExtraData
def Execute(self):
"""Toggle hasExtraData installer attribute"""
self._selected_info.hasExtraData ^= True
super(Installer_HasExtraData, self).Execute()
class Installer_OverrideSkips(CheckLink, _RefreshingLink):
"""Toggle overrideSkips flag on installer."""
_text = _(u'Override Skips')
@property
def link_help(self):
return _('Override global file type skipping for '
'%(sel_pkg)s.') % {'sel_pkg': self._selected_item}
def _check(self):
return self._enable() and self._selected_info.overrideSkips
def Execute(self):
self._selected_info.overrideSkips ^= True
self._overrides_skips = self._selected_info.overrideSkips
super(Installer_OverrideSkips, self).Execute()
class Installer_SkipRefresh(CheckLink, _SingleProject):
"""Toggle skipRefresh flag on project."""
_text = _(u"Don't Refresh")
_help = _(u"Don't automatically refresh project.")
def _check(self): return self._enable() and self._selected_info.skipRefresh
def Execute(self):
"""Toggle skipRefresh project attribute and refresh the project if
skipRefresh is set to False."""
installer = self._selected_info
installer.skipRefresh ^= True
if installer.do_update(): # will return False if skipRefresh == True
installer.refreshStatus(self.idata)
self.idata.refresh_n()
self.window.RefreshUI()
class Installer_Install(_NoMarkerLink):
"""Install selected packages."""
mode_title = {'DEFAULT': _('Install Configured'),
'LAST': _('Install Last'),
'MISSING': _('Install Missing Files')}
mode_help = {'DEFAULT': _('Install all configured files from the selected '
'packages, overwriting mismatched files.'),
'LAST': _('Install all configured files from the selected '
'packages at the last position, overwriting '
'mismatched files.'),
'MISSING': _('Install all missing files from the selected '
'packages. Never overwrites files.')}
def __init__(self,mode=u'DEFAULT'):
super(Installer_Install, self).__init__()
self.mode = mode
self._text = self.mode_title[self.mode]
self._help = self.mode_help[self.mode]
@balt.conversation
def Execute(self):
ui_refresh = defaultdict(bool)
try:
with balt.Progress(_('Installing…')) as progress:
last = (self.mode == 'LAST')
override = (self.mode != 'MISSING')
try:
new_tweaks = self.idata.bain_install(self._installables,
ui_refresh, progress, last, override)
except (CancelError, SkipError):
return
except StateError as e:
self._showError(f'{e}')
return
finally:
self.window.RefreshUI(refresh_others=ui_refresh)
# No error occurred and we didn't cancel or skip, but let RefreshUI run
# first so it can update checkbox colors
self._warn_nothing_installed()
self._warn_mismatched_ini_tweaks_created(new_tweaks)
self.window.issue_warnings(warn_others=ui_refresh)
def _warn_mismatched_ini_tweaks_created(self, new_tweaks):
if new_tweaks:
msg = _('The following INI Tweaks were created, because the '
'existing INI was different than what BAIN installed:') + \
'\n' + '\n'.join([f' * {x.stail}\n' for (x, y) in new_tweaks])
self._showInfo(msg, title=_('INI Tweaks'))
def _warn_nothing_installed(self):
inst_packages = [self.idata[i] for i in self._installables]
# See set_subpackage_checkmarks for the off-by-one explanation
# Note also we have to skip active FOMODs, otherwise install commands
# will break on them since they often have sub-packages but will pretty
# much never have any active ones.
unconf_packages = [p for p in inst_packages if p.is_complex_package and
not any(p.subActives[1:]) and
not p.extras_dict.get('fomod_active', False)]
if unconf_packages:
up_title = _('Installed unconfigured packages')
up_msg2 = _(
'To remedy this, use the "Sub-Packages" and "Plugin '
'Filter" boxes to select game data to install for the '
'affected packages, then use "Anneal" to update the '
'installation. You can also identify this problem by the '
'white package checkbox.')
if len(unconf_packages) == len(inst_packages):
if len(unconf_packages) == 1:
up_msg1 = _(
'The package you installed (%(sel_pkg)s) is complex, '
'which means it has sub-packages. However, you did '
'not activate any sub-packages for it, which is '
'probably a mistake since it means no game data has '
'been installed for it.') % {
'sel_pkg': unconf_packages[0]}
up_msg2 = _(
'To remedy this, use the "Sub-Packages" and "Plugin '
'Filter" boxes to select game data to install for the '
'affected package, then use "Anneal" to update the '
'installation. You can also identify this problem by '
'the white package checkbox.')
up_title = _('Installed unconfigured package')
else:
up_msg1 = _(
'The packages you installed are complex, which means '
'they have sub-packages. However, you did not '
'activate any sub-packages for them, which is '
'probably a mistake since it means no game data has '
'been installed for them.')
else:
up_msg1 = _(
'One or more of the packages you installed are complex, '
'which means they have sub-packages. However, you did not '
'activate any sub-packages for them, which is probably a '
'mistake since it means no game data has been installed '
'for them.')
self._askContinue(f'{up_msg1}\n\n{up_msg2}',
'bash.installers.nothing_installed.continue',
title=up_title, show_cancel=False)
class Installer_InstallSmart(_NoMarkerLink):
"""A 'smart' installer for new users. Uses wizards and FOMODs if present,
then falls back to regular install if that isn't possible."""
_text = _('Install…')
_help = _('Installs the selected packages, preferring a visual method if '
'available.')
def _try_installer(self, sel_package, link_instance: EnabledLink):
"""Checks if the specified installer link is enabled and, if so, runs
it."""
link_instance._initData(self.window, [sel_package.fn_key])
if link_instance._enable():
link_instance.Execute()
return True
return False
def Execute(self):
##: Not the best implementation, pretty readable and obvious though
inst_wiz = Installer_Wizard(auto_wizard=False)
inst_fomod = Installer_RunFomod()
inst_regular = Installer_Install()
# Use list() since the interactive installers can change selection
for sel_package in list(self.iselected_infos()):
# Look for a BAIN wizard first, best integration with BAIN (duh)
if self._try_installer(sel_package, inst_wiz): continue
# Skip FOMODs here if the Ignore FOMODs option is checked
if not bass.settings[u'bash.installers.ignore_fomods']:
# Next, look for an FOMOD wizard - not quite as good, but at
# least it's visual
if self._try_installer(sel_package, inst_fomod): continue
# Finally, fall back to the regular 'Install Configured' method
self._try_installer(sel_package, inst_regular)
class Installer_ListStructure(_SingleInstallable):
"""Copies folder structure of installer to clipboard."""
_text = _('List Structure…')
_help = _(u'Displays the folder structure of the selected installer (and '
u'copies it to the system clipboard).')
@balt.conversation ##: no use ! _showLog returns immediately
def Execute(self):
source_list_txt = self._selected_info.listSource()
#--Get masters list
copy_text_to_clipboard(source_list_txt)
self._showLog(source_list_txt, title=_('Package Structure'))
class Installer_ExportAchlist(_SingleInstallable):
"""Write an achlist file with all the destinations files for this
installer in this configuration."""
_text = _('Export Achlist')
_mode_info_dir = 'Mod Info Exports'
_help = (_('Create achlist file for use by the %(ck_name)s.') % {
'ck_name': bush.game.Ck.long_name})
def Execute(self):
out_dir = bass.dirs['app'].join(self.__class__._mode_info_dir)
achlist = out_dir.join(f'{self._selected_info.fn_key}.achlist')
##: Windows-1252 is a guess. The CK is able to decode non-ASCII
# characters encoded with it correctly, at the very least (UTF-8/UTF-16
# both fail), but the encoding might depend on the game language?
with BusyCursor(), achlist.open(u'w', encoding=u'cp1252') as out:
out.write(u'[\n\t"')
lines = u'",\n\t"'.join(
u'\\'.join((bush.game.mods_dir, d)).replace(u'\\', u'\\\\')
for d in bolt.sortFiles(self._selected_info.ci_dest_sizeCrc)
# exclude top level files and docs - last one monkey patched
if os.path.split(d)[0] and not d.lower().startswith(u'docs'))
out.write(lines)
out.write(u'"\n]')
class Installer_Move(_InstallerLink):
"""Moves selected installers to desired spot."""
_text = _('Move To…')
_help = _('Move the selected packages to a position of your choice.')
@balt.conversation
def Execute(self):
curPos = min(inf.order for inf in self.iselected_infos())
last_key, first_of_last_key, semi_last_key = -1, -2, -3
message = '\n\n'.join([
_('Move selected packages to what position?'),
_('Last: %(last_key)s; First of Last: %(first_of_last_key)s; '
'Semi-Last: %(semi_last_key)s.') % {
'last_key': last_key, 'first_of_last_key': first_of_last_key,
'semi_last_key': semi_last_key,
}])
newPos = self._askNumber(message, initial_num=curPos,
min_num=semi_last_key)
if newPos is None: return
if newPos == semi_last_key:
newPos = self.idata[self.idata.lastKey].order
elif newPos == first_of_last_key:
newPos = self.idata[self.idata.lastKey].order + 1
elif newPos == last_key:
newPos = len(self.idata)
self.idata.moveArchives(self.selected, newPos)
self.idata.refresh_n()
self.window.RefreshUI(
detail_item=self.iPanel.detailsPanel.displayed_item)
#------------------------------------------------------------------------------
class _Installer_OpenAt(_InstallerLink):
_open_at_key: str
_open_at_message: str
_open_at_title: str
def _url(self):
raise NotImplementedError
def Execute(self):
if self._askContinue(self._open_at_message, self._open_at_key,
self._open_at_title):
webbrowser.open(self._url())
class _Installer_OpenAt_Regex(_Installer_OpenAt):
_regex_pattern: re.Pattern
_regex_group: int
_base_url: str
def _enable(self):
# The menu won't even be enabled if >1 plugin is selected
x = self.__class__._regex_pattern.search(self.selected[0])
self._mod_url_id = x and x.group(self.__class__._regex_group)
return bool(self._mod_url_id)
def _url(self):
return self.__class__._base_url + self._mod_url_id
class Installer_OpenNexus(AppendableLink, _Installer_OpenAt_Regex):
_text = f'{bush.game.nexusName}…'
_help = _("Opens this mod's page at the %(nexusName)s.") % {
'nexusName': bush.game.nexusName}
_open_at_key = bush.game.nexusKey
_open_at_message = _(
u'Attempt to open this as a mod at %(nexusName)s? This assumes that '
u"the trailing digits in the package's name are actually the id "
u'number of the mod at %(nexusName)s. If this assumption is wrong, '
u"you'll just get a random mod page (or error notice) at %("
u'nexusName)s.') % {u'nexusName': bush.game.nexusName}
_open_at_title = _('Open at %(nexusName)s') % {
'nexusName': bush.game.nexusName}
_regex_pattern = bosh.reTesNexus
_regex_group = 2
_base_url = bush.game.nexusUrl + 'mods/'
def _append(self, window): return bool(bush.game.nexusUrl)
class Installer_OpenSearch(_Installer_OpenAt):
_text = 'Google…'
_help = _(u"Searches for this mod's title on Google.")
_open_at_key = 'bash.installers.opensearch.continue'
_open_at_message = _('Open a search for this on Google?')
_open_at_title = _('Open at Google')
def _url(self):
def _mk_google_param(m):
"""Helper method to create a google search query for the specified
mod name."""
return '+'.join(re.split(r'\W+|_+', m))
search_base = 'https://www.google.com/search?q='
sel_inst_name = self.selected[0]
# First, try extracting the mod name via the Nexus regex
ma_nexus = bosh.reTesNexus.search(sel_inst_name)
if ma_nexus and ma_nexus.group(1):
return search_base + _mk_google_param(ma_nexus.group(1))
# If that fails, try extracting the mod name via the TESAlliance regex
ma_tesa = bosh.reTESA.search(sel_inst_name)
if ma_tesa and ma_tesa.group(1):
return search_base + _mk_google_param(ma_tesa.group(1))
# If even that fails, just use the whole string (except the file
# extension)
return search_base + sel_inst_name.fn_body
class Installer_OpenTESA(_Installer_OpenAt_Regex):
_text = 'TES Alliance…'
_help = _(u"Opens this mod's page at TES Alliance.")
_open_at_key = 'bash.installers.openTESA.continue'
_open_at_message = _(
u'Attempt to open this as a mod at TES Alliance? This assumes that '
u"the trailing digits in the package's name are actually the id "
u'number of the mod at TES Alliance. If this assumption is wrong, '
u"you'll just get a random mod page (or error notice) at TES "
u'Alliance.')
_open_at_title = _('Open at TES Alliance')
_regex_pattern = bosh.reTESA
_regex_group = 2
_base_url = 'http://tesalliance.org/forums/index.php?app=downloads&showfile='
#------------------------------------------------------------------------------
class Installer_Refresh(_InstallerLink):
"""Rescans selected Installers."""
_text = _('Refresh')
_help = _('Rescan selected packages. Ignores "Don\'t Refresh" flag on '
'projects. Will forcibly recalculate the CRCs of all files in '
'any selected projects.')
_force_recalc_projects = True
def _enable(self):
return bool(list(self.idata.ipackages(self.selected)))
@balt.conversation
def Execute(self):
self.window.rescanInstallers(self.selected, abort=True,
calculate_projects_crc=self._force_recalc_projects)
class Installer_QuickRefresh(Installer_Refresh):
_text = _('Quick Refresh')
_help = _('Rescan selected packages. Ignores "Don\'t Refresh" flag on '
'projects.')
_force_recalc_projects = False
class Installer_SkipVoices(CheckLink, _RefreshingLink):
"""Toggle skipVoices flag on installer."""
_text = _(u'Skip Voices')
@property
def link_help(self):
return _('Skip over any voice files in %(sel_pkg)s') % (
{'sel_pkg': self._selected_item})
def _check(self): return self._enable() and self._selected_info.skipVoices
def Execute(self):
self._selected_info.skipVoices ^= True
super(Installer_SkipVoices, self).Execute()
class Installer_Uninstall(_NoMarkerLink):
"""Uninstall selected Installers."""
_text = _('Uninstall')
_help = _('Uninstall the selected packages, removing all their matched '
'files from the %(data_folder)s folder.') % {
'data_folder': bush.game.mods_dir}
@balt.conversation
def Execute(self):
"""Uninstall selected Installers."""
ui_refresh = defaultdict(bool)
try:
with balt.Progress(_('Uninstalling…')) as progress:
self.idata.bain_uninstall(self._installables, ui_refresh,
progress)
except (CancelError,SkipError): # now where could this be raised from ?
pass
finally:
self.window.RefreshUI(refresh_others=ui_refresh)
class Installer_CopyConflicts(_SingleInstallable):
"""For Modders only - copy conflicts to a new project."""
_text = _('Copy Conflicts to Project')
_help = _('Copy all files that conflict with the selected package into a '
'new project. Conflicts with inactive packages are included.')
@balt.conversation
def Execute(self):
"""Copy files that conflict with this installer from all other
installers to a project."""
srcConflicts = set()
packConflicts = []
src_sizeCrc = self._selected_info.ci_dest_sizeCrc # CIstr -> (int, int)
if not src_sizeCrc:
self._showOk(_('No files to install for %(sel_pkg)s.') % {
'sel_pkg': self._selected_item})
return
src_order = self._selected_info.order
with balt.Progress(_('Scanning Packages…')) as progress:
progress.setFull(len(self.idata))
numFiles = 0
fn_conflicts_dir = FName(f'Conflicts - {src_order:03d}')
for i,(package, installer) in enumerate(self.idata.sorted_pairs()):
curConflicts = set()
progress(i, _('Scanning Packages…') + f'\n{package}')
for z, y in installer.refreshDataSizeCrc().items():
if z in src_sizeCrc and installer.ci_dest_sizeCrc[z] != \
src_sizeCrc[z]:
curConflicts.add(y)
srcConflicts.add(src_sizeCrc[z])
numFiles += len(curConflicts)
if curConflicts: packConflicts.append(
(installer.order, package, curConflicts))
srcConflicts = { # we need the paths rel to the archive not Data
src for src, siz, crc in self._selected_info.fileSizeCrcs if
(siz, crc) in srcConflicts}
numFiles += len(srcConflicts)
if not numFiles:
self._showOk(_('No conflicts detected for %(sel_pkg)s') % {
'sel_pkg': self._selected_item})
return
ijoin = self.idata.store_dir.join
def _copy_conflicts(curFile):
inst = self.idata[package]
if inst.is_project:
for src in curConflicts:
srcFull = ijoin(package, src)
destFull = ijoin(fn_conflicts_dir, g_path, src)
if srcFull.exists():
progress(curFile, f'{self._selected_item}\n' + _(
'Copying files…') + '\n' + src)
srcFull.copyTo(destFull)
curFile += 1
else:
unpack_dir = inst.unpackToTemp(curConflicts,
SubProgress(progress, curFile, curFile + len(curConflicts),
len(curConflicts)))
unpack_dir.moveTo(ijoin(fn_conflicts_dir, g_path))
cleanup_temp_dir(unpack_dir) # Mark as cleaned up internally
curFile += len(curConflicts)
return curFile
with balt.Progress(_('Copying Conflicts…')) as progress:
progress.setFull(numFiles)
curFile = 0
g_path = package = self._selected_item
curConflicts = srcConflicts
curFile = _copy_conflicts(curFile)
for order,package,curConflicts in packConflicts:
g_path = (f'{order if order < src_order else order + 1:03d} '
f'- {package}')
curFile = _copy_conflicts(curFile)
self.idata.new_info(fn_conflicts_dir, install_order=src_order + 1)
self.window.RefreshUI(detail_item=fn_conflicts_dir)
#------------------------------------------------------------------------------
# InstallerDetails Plugin Filter Links ----------------------------------------
#------------------------------------------------------------------------------
class _Installer_Details_Link(EnabledLink):
window: InstallersDetails
selected: int
def _enable(self): return len(self.window.espm_checklist_fns) != 0
@property
def _installer(self):
return self.window.file_info
class Installer_Espm_SelectAll(_Installer_Details_Link):
"""Select all plugins in installer for installation."""
_text = _(u'Select All')
_help = _(u'Selects all plugin files in the selected sub-packages.')
def Execute(self):
self._installer.espmNots = set()
self.window.gEspmList.set_all_checkmarks(checked=True)
self.window.refreshCurrent(self._installer)
class Installer_Espm_DeselectAll(_Installer_Details_Link):
"""Deselect all plugins in installer for installation."""
_text = _(u'Deselect All')
_help = _(u'Deselects all plugin files in the selected sub-packages.')
def Execute(self):
self._installer.espmNots = set(self.window.espm_checklist_fns)
self.window.gEspmList.set_all_checkmarks(checked=False)
self.window.refreshCurrent(self._installer)