-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBindControl.py
More file actions
executable file
·782 lines (631 loc) · 34.3 KB
/
BindControl.py
File metadata and controls
executable file
·782 lines (631 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
#!/usr/bin/env python3
import sys
import wx
import re
import os
import platform
from pathlib import Path
from pubsub import pub
import wx.lib.mixins.inspection
import wx.adv
from bcLogging import bcLogging
from bcVersion import current_version
from Help import ShowHelpWindow
from Icon import GetIcon
from Profile import Profile
from UI.BindDirsWindow import BindDirsWindow
from UI.CGControls import cgTextCtrl, cgButton
from UI.PrefsDialog import PrefsDialog
from Util.DefaultProfile import DefaultProfile
import Util.Paths
import Util.BuildFiles
MIN_PYTHON = (3, 13)
if sys.version_info < MIN_PYTHON:
sys.exit("Python {}.{} or later is required.\n".format(*MIN_PYTHON))
MIN_WX = (4, 2, 2)
if wx.VERSION < MIN_WX:
sys.exit("wxPython {}.{}.{} or later is required.\n".format(*MIN_WX))
###################
# Main Window Class
###################
class Main(wx.Frame):
def __init__(self, guiLogging = True):
super().__init__(None, title = "BindControl")
self.Profile = None
self.StartupPanel = None
self.Logger : bcLogging|None = None
self.about_info = None
stdpaths = wx.StandardPaths.Get()
config = wx.ConfigBase.Get()
self.Config = config
# Check each config bit for existence and set to default if no
if not config.Exists('GamePath'):
if platform.system() == 'Windows':
gamepath = "C:\\Games\\Homecoming\\"
else:
gamepath = str(Path.home() / '.wine' / 'drive_c' / 'Games' / 'Homecoming')
config.Write('GamePath', gamepath)
if not config.Exists('GameLang'): config.Write('GameLang', 'English')
# if we're first starting up without the "RelativeBindsDir", set it to True, *IF*
# and *ONLY IF* we don't already have a BindPath set up. This means new installs
# will get RelativeBindsDir True; existing ones will default to False
if not config.Exists('RelativeBindsDir') : config.WriteBool('RelativeBindsDir', not config.Exists('BindPath'))
if not config.Exists('BindPath'):
if platform.system() == 'Windows':
bindpath = "C:\\coh\\"
else:
bindpath = str(Path.home() / '.wine' / 'drive_c' / 'coh')
config.Write('BindPath', bindpath)
if not config.Exists('BindTextPath') : config.Write('BindTextPath', 'kb')
if not config.Exists('GameBindPath'):
if platform.system() != 'Windows':
config.Write('GameBindPath', "c:\\coh\\")
if not config.Exists('ResetKey') : config.Write('ResetKey', 'CTRL+R')
if not config.Exists('UseSplitModKeys') : config.WriteBool('UseSplitModKeys', False)
if not config.Exists('FlushAllBinds') : config.WriteBool('FlushAllBinds', True)
if not config.Exists('ProfilePath') : config.Write('ProfilePath', str(Path(stdpaths.GetDocumentsDir()) / "bindcontrol"))
if not config.Exists('StartWithLastProfile'): config.WriteBool('StartWithLastProfile', True)
if not config.Exists('SaveSizeAndPosition') : config.WriteBool('SaveSizeAndPosition', True)
if not config.Exists('VerboseBLF') : config.WriteBool('VerboseBLF', False)
if not config.Exists('CrashOnProfileError') : config.WriteBool('CrashOnProfileError', False)
if not config.Exists('CrashOnBindError') : config.WriteBool('CrashOnBindError', False)
if not config.Exists('ShowInspector') : config.WriteBool('ShowInspector', False)
if not config.Exists('ShowDebugMessages') : config.WriteBool('ShowDebugMessages', False)
if not config.Exists('WinH') : config.WriteInt('WinH', 1000)
if not config.Exists('WinW') : config.WriteInt('WinW', 1000)
if not config.Exists('DefaultProfile') : config.Write('DefaultProfile', DefaultProfile)
# migrate old "start with" preference. Maybe remove this someday
if config.Exists('StartWith'):
config.WriteBool('StartWithLastProfile', config.Read('StartWith') == "Last Profile")
config.DeleteEntry('StartWith')
config.Flush()
# set up the custom logger with the infobar
if guiLogging:
self.Logger = bcLogging(self)
if config.ReadBool('ShowDebugMessage'):
wx.Log.SetLogLevel(wx.LOG_Debug)
else:
wx.Log.SetLogLevel(wx.LOG_Status)
self.Sizer = wx.BoxSizer(wx.VERTICAL)
# "Profile" Menu
ProfMenu = wx.Menu()
Profile_new = ProfMenu.Append(wx.ID_NEW , "&New Profile\tCTRL-N")
Profile_load = ProfMenu.Append(wx.ID_OPEN , "&Load Profile...\tCTRL-L")
self.Profile_import = ProfMenu.Append(wx.ID_ADD , "&Import Saved Build...\tCTRL-I")
self.Profile_save = ProfMenu.Append(wx.ID_SAVE , "&Save Profile\tCTRL-S")
self.Profile_saveas = ProfMenu.Append(wx.ID_SAVEAS , "Save Profile As...")
self.Profile_close = ProfMenu.Append(wx.ID_CLOSE , "Close Profile")
ProfMenu.AppendSeparator()
self.Profile_savedefault = ProfMenu.Append(wx.ID_ANY , "Save Profile As Default")
self.Profile_editdefault = ProfMenu.Append(wx.ID_ANY , "Edit Default Profile")
ProfMenu.AppendSeparator()
Profile_preferences = ProfMenu.Append(wx.ID_PREFERENCES, "&Preferences")
Profile_exit = ProfMenu.Append(wx.ID_EXIT , "&Quit BindControl\tCTRL-Q")
# "Help" Menu
HelpMenu = wx.Menu()
Help_guide = HelpMenu.Append(wx.ID_ANY, "Getting Started")
Help_files = HelpMenu.Append(wx.ID_ANY, "Output Files")
#Help_bindDirs = HelpMenu.Append(wx.ID_ANY, "Bind Directories")
Help_license = HelpMenu.Append(wx.ID_ANY, "License Info")
Help_bugs = HelpMenu.Append(wx.ID_ANY, "Reporting Bugs")
Help_about = HelpMenu.Append(wx.ID_ABOUT)
LogMenu = wx.Menu()
Log_window = LogMenu.Append(wx.ID_ANY, "Log Window")
# cram the separate menus into a menubar
MenuBar = wx.MenuBar()
MenuBar.Append(ProfMenu, 'Profile')
MenuBar.Append(HelpMenu, 'Help')
MenuBar.Append(LogMenu, 'Log')
# glue the menubar into the main window
self.SetMenuBar(MenuBar)
# MENUBAR EVENTS
self.Bind(wx.EVT_MENU, self.OnProfileNew , Profile_new)
self.Bind(wx.EVT_MENU, self.OnProfileLoad , Profile_load)
self.Bind(wx.EVT_MENU, self.OnProfileImport , self.Profile_import)
self.Bind(wx.EVT_MENU, self.OnProfileSave , self.Profile_save)
self.Bind(wx.EVT_MENU, self.OnProfileSaveAs , self.Profile_saveas)
self.Bind(wx.EVT_MENU, self.OnProfileSaveDefault , self.Profile_savedefault)
self.Bind(wx.EVT_MENU, self.OnProfileEditDefault , self.Profile_editdefault)
self.Bind(wx.EVT_MENU, self.OnProfileClose , self.Profile_close)
self.Bind(wx.EVT_MENU, self.OnMenuPrefsDialog , Profile_preferences)
self.Bind(wx.EVT_MENU, self.OnMenuExitApplication, Profile_exit)
self.Bind(wx.EVT_MENU, self.OnHelpGettingStarted, Help_guide)
self.Bind(wx.EVT_MENU, self.OnHelpFiles , Help_files)
#self.Bind(wx.EVT_MENU, self.OnHelpBindDirs , Help_bindDirs)
self.Bind(wx.EVT_MENU, self.OnHelpLicense , Help_license)
self.Bind(wx.EVT_MENU, self.OnHelpBugs , Help_bugs)
self.Bind(wx.EVT_MENU, self.OnMenuAboutBox , Help_about)
self.Bind(wx.EVT_MENU, self.OnMenuLogWindow, Log_window)
# APPLICATION ICON
AppIcon = wx.IconBundle()
base_path = Util.Paths.GetRootDirPath()
filename = base_path / 'icons' / 'BindControl.ico'
AppIcon.AddIcon(f"{filename}", wx.BITMAP_TYPE_ANY)
self.SetIcons(AppIcon)
# Infobar for showing errors and other messages
if guiLogging and self.Logger:
self.Sizer.Add(self.Logger.InfoBar, 0, wx.EXPAND)
# Bottom Buttons
self.BottomButtonPanel = wx.Panel(self)
self.ProfDirButton = cgButton(self.BottomButtonPanel, label = "Set Binds Directory")
self.ProfDirButton.SetToolTip("Configure the directory where this Profile will write bindfiles")
self.ProfDirButton.DefaultToolTip = "Configure the directory where this Profile will write bindfiles"
self.WriteButton = wx.Button(self.BottomButtonPanel, label = "Write Binds")
self.WriteButton.SetToolTip("Write out the bindfiles to the configured binds directory")
self.DeleteButton = wx.Button(self.BottomButtonPanel, label = "Delete All Binds")
self.DeleteButton.SetToolTip("Delete all BindControl-managed files in the configured binds directory")
BottomButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
self.BottomButtonPanel.SetSizer(BottomButtonSizer)
BottomButtonSizer.Add(self.ProfDirButton, 0, wx.EXPAND)
BottomButtonSizer.Add(self.WriteButton , 1, wx.EXPAND)
BottomButtonSizer.Add(self.DeleteButton , 0, wx.EXPAND)
self.ProfDirButton.Bind(wx.EVT_BUTTON, self.OnProfDirButton)
self.WriteButton .Bind(wx.EVT_BUTTON, self.OnWriteBindsButton)
self.DeleteButton .Bind(wx.EVT_BUTTON, self.OnDeleteBindsButton)
self.Sizer.Add(self.BottomButtonPanel, 0, wx.EXPAND | wx.ALL, 10)
# Do not SetSizerAndFit() - Fit() is poison
self.SetSizer(self.Sizer)
self.Bind(wx.EVT_CLOSE, self.OnWindowClosing)
pub.subscribe(self.OnMenuPrefsDialog, 'showprefsdialog')
pub.subscribe(self.OnProfileModified, 'checkprofilemodified')
def OnProfileModified(self):
if self.Profile:
self.SetTitle(self.Profile.ProfileName() + (" (*)" if self.Profile.IsModified() else ''))
def SetupInitialProfile(self, input_profile = None):
config = wx.ConfigBase.Get()
filename = None
if input_profile:
filename = input_profile
elif (config.Read('StartWith') == 'Last Profile' or config.ReadBool('StartWithLastProfile')):
filename = config.Read('LastProfile')
if filename:
try:
self.Profile = Profile(self, filename)
self.Profile.buildUIFromData()
self.Sizer.Insert(0, self.Profile, 1, wx.EXPAND)
self.CheckProfDirButtonErrors()
except Exception:
if self.Profile:
self.Profile.DestroyLater()
self.Profile = None
self.StartupPanel = self.MakeStartupPanel()
self.Sizer.Insert(0, self.StartupPanel, 1, wx.EXPAND)
# otherwise show the big buttons
else:
self.StartupPanel = self.MakeStartupPanel()
self.Sizer.Insert(0, self.StartupPanel, 1, wx.EXPAND)
self.BindDirsWindow = None
self.SetupProfileUI()
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
# This is the two-button "start new profile" vs "load existing profile" panel
def MakeStartupPanel(self) -> wx.Panel:
StartupPanel = wx.Panel(self)
StartupSizer = wx.BoxSizer(wx.VERTICAL)
ButtonSizer = wx.GridSizer(3, 10, 10)
newButton = wx.Button(StartupPanel, label = "Start New Profile")
newButton.SetBitmap(GetIcon('UI', 'new_profile'))
newButton.SetBitmapPosition(wx.TOP)
newButton.SetToolTip('Start a brand new profile from scratch')
loadButton = wx.Button(StartupPanel, label = "Load Existing Profile")
loadButton.SetBitmap(GetIcon('UI', 'load_profile'))
loadButton.SetBitmapPosition(wx.TOP)
loadButton.SetToolTip('Load an existing BindControl Profile file')
importButton = wx.Button(StartupPanel, label = "Import Build File")
importButton.SetBitmap(GetIcon('UI', 'import_build'))
importButton.SetBitmapPosition(wx.TOP)
importButton.SetToolTip('Import a build file exported from City of Heroes')
ButtonSizer.Add(newButton, 1, wx.EXPAND)
ButtonSizer.Add(loadButton, 1, wx.EXPAND)
ButtonSizer.Add(importButton, 1, wx.EXPAND)
newButton.Bind(wx.EVT_BUTTON, self.OnProfileNew)
loadButton.Bind(wx.EVT_BUTTON, self.OnProfileLoad)
importButton.Bind(wx.EVT_BUTTON, self.OnProfileImport)
GettingStartedLink = wx.adv.HyperlinkCtrl(StartupPanel,
label = 'Getting Started with BindControl',
url = 'https://github.com/emersonrp/bindcontrol/wiki/Getting-Started-With-BindControl'
)
StartupSizer.AddStretchSpacer(1)
StartupSizer.Add(ButtonSizer, 0, wx.ALIGN_CENTER)
StartupSizer.Add(GettingStartedLink, 0, wx.ALIGN_CENTER|wx.TOP, 60)
StartupSizer.AddStretchSpacer(1)
StartupPanel.SetSizer(StartupSizer)
StartupPanel.Layout()
return StartupPanel
def SetupProfileUI(self) -> None:
self.Profile_save.Enable(self.EnableProfCtrls())
self.Profile_saveas.Enable(self.EnableProfCtrls())
self.Profile_savedefault.Enable(self.EnableProfCtrls() or bool(self.Profile and self.Profile.EditingDefault))
self.ProfDirButton.Enable(self.EnableProfCtrls())
# TODO - do smarter things with enabling the write and delete buttons
self.WriteButton.Enable(self.EnableProfCtrls())
self.DeleteButton.Enable(self.EnableProfCtrls())
def OnPageChanged(self, evt) -> None:
if self.Profile:
tabnumber = evt.GetSelection()
tabname = self.Profile.GetPageText(tabnumber)
if tabname == "Macro Composer" or tabname == "Popmenu Editor":
self.BottomButtonPanel.Hide()
if self.Profile:
self.Profile.PopmenuEditor.LoadMenusIfNeeded()
self.Profile.PopmenuEditor.SynchronizeUI()
else:
self.BottomButtonPanel.Show(True)
self.Layout()
def OnProfileNew(self, _ = None) -> None:
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return
# loop eternally until we get a name we like
while True:
with wx.TextEntryDialog(self, message = 'Enter name for new profile, for instance, the name of a character:', caption = "New Profile") as dlg:
result = dlg.ShowModal()
if result == wx.ID_OK:
newname = dlg.GetValue()
if not newname:
continue
checkprofile = Path(wx.ConfigBase.Get().Read('ProfilePath'))/ f"{newname}.bcp"
if checkprofile.exists():
wx.MessageBox(f"A profile called {newname} already exists. Please select another name.")
continue
break
else:
return result
self.Freeze()
try:
with wx.WindowDisabler():
_ = wx.BusyInfo(wx.BusyInfoFlags().Parent(self).Text(f'Creating New Profile {newname}...'))
wx.GetApp().Yield()
self.Sizer.Remove(0)
if self.Profile: self.Profile.Destroy()
# destroy the Startup Panel if it's there. This is only needed on Windows dunno why.
if self.StartupPanel: self.StartupPanel.Destroy()
self.Profile = Profile(self, newname = newname)
self.Profile.buildUIFromData()
wx.LogMessage(f'Created New Profile "{newname}".')
self.Sizer.Insert(0, self.Profile, 1, wx.EXPAND)
except Exception as e:
wx.LogError(f"Something broke in new profile: {e}. This is a bug.")
finally:
self.SetupProfileUI()
self.CheckProfDirButtonErrors()
self.Layout()
self.Thaw()
def OnProfileLoad(self, _) -> None:
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return
# Try to load; if the user hits "cancel" or the load fails, go back to where we were
if newProfile:= Profile.LoadFromFile(self):
self.InsertProfile(newProfile)
# we use this in the Binds Directory Window also
def InsertProfile(self, newProfile) -> bool:
try:
self.Freeze()
# OK, we're either at the startup panel or we have an existing profile. Either way, remove it:
self.Sizer.Remove(0)
# delete any existing Profile and all its subwidgets and geegaws
if self.Profile: self.Profile.DestroyLater()
# destroy the Startup Panel if it's there. This is only needed on Windows dunno why.
if self.StartupPanel: self.StartupPanel.DestroyLater()
# and set up our new profile as the current one
self.Profile = newProfile
self.Sizer.Insert(0, self.Profile, 1, wx.EXPAND)
self.Layout()
except Exception as e:
wx.LogError(f"Something broke while setting up profile load: {e}")
return False
finally:
if self.IsFrozen(): self.Thaw()
# OK, we made it, set up the UI bits etc.
self.SetupProfileUI()
self.CheckProfDirButtonErrors()
if not newProfile.EditingDefault:
wx.ConfigBase.Get().Write('LastProfile', str(newProfile.Filepath()))
wx.ConfigBase.Get().Flush()
return True
def OnProfileImport(self, _) -> bool:
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return False
pathname = ''
config = wx.ConfigBase.Get()
with wx.FileDialog(self, "Import build file",
wildcard = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
defaultDir = config.Read('GamePath'),
style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
wx.LogMessage("User canceled importing build file")
return False # the user changed their mind
pathname = fileDialog.GetPath()
if pathname:
buildfile = Path(pathname)
if profiledata := Util.BuildFiles.ParseBuildFile(buildfile):
generaldata = {'General' : profiledata}
if newprofile := Profile(self, newname = profiledata['Name'], profiledata = generaldata):
newprofile.buildUIFromData(set_power_picks = True)
self.InsertProfile(newprofile)
else:
wx.LogError('Build file was empty or contained errors')
return False
return True
def OnProfileSave(self, _) -> None:
if not self.Profile: return
self.Profile.doSaveToFile()
def OnProfileSaveAs(self, _) -> None:
if not self.Profile: return
self.Profile.SaveToFile()
def OnProfileSaveDefault(self, _) -> None:
if not self.Profile: return
self.Profile.SaveAsDefault()
def OnProfileEditDefault(self, _) -> None:
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return
with wx.WindowDisabler():
_ = wx.BusyInfo('Loading...')
wx.GetApp().Yield()
if defaultProfile := Profile(self, editdefault = True):
defaultProfile.buildUIFromData()
self.InsertProfile(defaultProfile)
defaultProfile.RemovePage(defaultProfile.FindPage(defaultProfile.PopmenuEditor)) # hide the Popmenu Editor
wx.LogWarning("You are editing the default profile, which will be the basis for all new and imported profiles.")
def OnProfileClose(self, _) -> None:
if not self.Profile: return
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return
self.Sizer.Remove(0)
if self.Profile:
self.Profile.DestroyLater()
self.Profile = None
wx.ConfigBase.Get().Write('LastProfile', '')
wx.ConfigBase.Get().Flush()
self.StartupPanel = self.MakeStartupPanel()
self.Sizer.Insert(0, self.StartupPanel, 1, wx.EXPAND)
self.SetTitle('BindControl')
self.SetupProfileUI()
self.Layout()
def OnProfDirButton(self, _ = None) -> None:
if not self.Profile: return # should try not to get here in the first place
ProfDirDialog = wx.Dialog(self, title = "Set Binds Directory")
sizer = wx.BoxSizer(wx.VERTICAL)
ProfDirDialog.SetSizer(sizer)
sizer.Add(wx.StaticText(ProfDirDialog, label = "Select the directory where this profile will write its bindfiles:"), 1, wx.EXPAND|wx.ALL, 10)
config = wx.ConfigBase.Get()
bindpath = config.Read('BindTextPath' if config.ReadBool('RelativeBindsDir') else 'BindPath')
separator = "\\" if platform.system() == "Windows" else "/"
if bindpath[-1:] == separator: separator = ''
dirSizer = wx.BoxSizer(wx.HORIZONTAL)
dirSizer.Add(wx.StaticText(ProfDirDialog, label = f"{bindpath}{separator}"), 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 10)
PathText = cgTextCtrl(ProfDirDialog)
dirSizer.Add(PathText, 1, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)
PathText.Bind(wx.EVT_TEXT, self.OnPathTextChanged)
sizer.Add(dirSizer, 1, wx.EXPAND)
sizer.Add(wx.StaticText(ProfDirDialog, label = "Changing this value will automatically save the Profile,\nincluding any other changes you have made."), 1, wx.EXPAND|wx.ALL, 10)
buttonsizer = ProfDirDialog.CreateSeparatedButtonSizer(wx.OK|wx.CANCEL)
sizer.Add(buttonsizer, 1, wx.EXPAND|wx.ALL, 10)
ProfDirDialog.Layout()
PathText.ClearErrors() # whyyyy?
with ProfDirDialog as dlg:
PathText.SetValue(self.Profile.ProfileBindsDir()) # do this here to trigger wx.EVT_TEXT
result = dlg.ShowModal()
if result == wx.ID_OK:
newvalue = PathText.GetValue()
# call us again if we tried to OK an error state
if PathText.HasErrors(): return self.OnProfDirButton()
# if we changed the directory, offer to delete the old one.
otherprofile = Util.Paths.CheckProfileForBindsDir(config, self.Profile.ProfileBindsDir())
if (
# we changed it to a new value:
self.Profile.ProfileBindsDir() and (newvalue != self.Profile.ProfileBindsDir())
and
# the old one isn't owned by another profile:
((not otherprofile) or (otherprofile and (otherprofile == self.Profile.ProfileName())))
):
answer = wx.MessageBox(
f'Binds directory changed. Delete all binds in old binds directory?\n{self.Profile.BindsDir()}',
'Binds directory Changed',wx.YES_NO, self
)
if answer == wx.YES:
self.Profile.DeleteBindFiles()
self.Profile.Data['ProfileBindsDir'] = newvalue
self.Profile.doSaveToFile()
# need this out here in case we cancelled on a previously-blank one.
# This is very very unlikely to happen and awful if it does.
# TODO: yes later on I see that this is indeed awful. Fix it.
#
# TODO-ish: if they erase an existing valid one or otherwise cause an
# error, and then hit "cancel" this gets triggered, which is not
# perfect - this logic needs a little smartening.
if PathText.HasErrors(): return self.OnProfDirButton()
self.CheckProfDirButtonErrors()
def CheckIfProfileNeedsSaving(self) -> int:
result = wx.OK
if self.Profile:
if self.Profile.IsModified():
result = wx.MessageBox(f"Profile {self.Profile.ProfileName()} not saved, save now?", "Profile modified", wx.YES_NO|wx.CANCEL)
if result == wx.YES:
if self.Profile.EditingDefault:
self.Profile.Data.doSaveAsDefault()
else:
self.Profile.doSaveToFile()
if self.Profile.PopmenuEditor.CheckForModifiedMenus():
result = wx.MessageBox("Some popmenus contain unsaved changes, return to editor?", "Popmenus modified", wx.YES_NO)
if result == wx.YES:
result = wx.CANCEL
peidx = self.Profile.FindPage(self.Profile.PopmenuEditor)
self.Profile.SetSelection(peidx)
return result
def CheckProfDirButtonErrors(self) -> None:
config = wx.ConfigBase.Get()
if not self.Profile: return
if self.Profile.ProfileBindsDir():
self.ProfDirButton.RemoveError('undef')
else:
self.ProfDirButton.AddError('undef', 'Your binds directory is unset. Binds cannot be written.')
if len(self.Profile.ProfileBindsDir()) <= 8:
self.ProfDirButton.RemoveWarning('toolong')
else:
self.ProfDirButton.AddWarning('toolong', 'Your binds directory name is rather long. This is not an error but can lead to some binds being too long for the game to use.')
otherprofile = Util.Paths.CheckProfileForBindsDir(config, self.Profile.ProfileBindsDir())
if otherprofile and (otherprofile != self.Profile.ProfileName()):
self.ProfDirButton.AddWarning('owned', f'The binds directory you have chosen is marked as owned by the profile "{otherprofile}." This is not an error, but be sure this is what you want to do.')
else:
self.ProfDirButton.RemoveWarning('owned')
self.DeleteButton.Enable(self.EnableProfCtrls() and not self.ProfDirButton.HasErrors())
self.WriteButton .Enable(self.EnableProfCtrls() and not self.ProfDirButton.HasErrors())
def EnableProfCtrls(self):
return bool(self.Profile and not self.Profile.EditingDefault)
def OnPathTextChanged(self, evt) -> None:
textctrl = evt.EventObject
value = textctrl.GetValue()
if not value:
textctrl.AddError('undef', 'You must specify a bindfile directory name.')
else:
textctrl.RemoveError('undef')
if re.search(r'[^A-Za-z0-9_]', value):
textctrl.AddError('unicode', 'The binds directory must contain only A-Z, a-z, 0-9, and _ characters.')
else:
textctrl.RemoveError('unicode')
if re.search(r'\s', value):
textctrl.AddError('spaces', 'The binds directory cannot contain spaces.')
else:
textctrl.RemoveError('spaces')
if platform.system() == 'Windows':
if os.path.isreserved(value): # pyright: ignore
textctrl.AddError('reserved', 'The name you have selected is a reserved filename in Windows. Please select another.')
else:
textctrl.RemoveError('reserved')
if value: # don't do this check if it's blank
exists = None
# look at the existing bindsdirs and see if we match
for bindsdir in Util.Paths.GetAllProfileBindsDirs(config):
# check case-insensitive because Windows
if bindsdir.lower() == value.lower():
# but stash it away as the case-sensitive version because Linux
exists = bindsdir
break
if exists and self.Profile:
existingProfile = Util.Paths.CheckProfileForBindsDir(config, exists)
if existingProfile != self.Profile.ProfileName():
existingProfileWarning = f', and is managed by the profile {existingProfile}' if existingProfile else ''
textctrl.AddWarning('exists', f'The directory you have selected already exists{existingProfileWarning}. This is not an error, but be sure this is where you want to save your binds.')
else:
textctrl.RemoveWarning('exists')
def OnWriteBindsButton(self, _) -> None:
if not self.Profile: return
self.Profile.WriteBindFiles()
def OnDeleteBindsButton(self, _) -> None:
if not self.Profile: return
self.Profile.DeleteBindFiles()
def OnMenuPrefsDialog(self, _ = None) -> None:
with PrefsDialog(self.Profile or self) as dlg: # parent to self.Profile to make CheckAllConflicts work
dlg.ShowAndUpdatePrefs()
def OnMenuAboutBox(self, _) -> None:
from datetime import datetime, UTC
this_year = datetime.now(tz = UTC).year
if self.about_info is None:
info = wx.adv.AboutDialogInfo()
info.AddDeveloper('R Pickett (emerson@hayseed.net)')
info.SetName('BindControl')
info.SetVersion(current_version())
info.SetDescription(
"BindControl can help you set up custom keybinds, macros, and popmenus in City of Heroes.\n\n"
"Based on:\n\tCityBinder 0.76, Copyright \u00A9 2005-2006 Jeff Sheets\n\tCityBinder for Homecoming 0.2, Copyright \u00A9 2021-2023 tailcoat\n\n"
"Speed-On-Demand binds originally created by Gnarley's Speed On Demand Binds.\nAdvanced Teleport Binds originally by DrLetharga.\n\n"
"Sandolphan Mastermind binds by Sandolphan in CoV beta.\nqwy Mastermind binds by qwy in the Homecoming Forums 2020.\n\n"
"Inspiration Popper design adapted from CityBinder for Homecoming by Tailcoat."
)
info.SetCopyright(f'\u00A9 2010-{this_year} R Pickett <emerson@hayseed.net>')
info.SetWebSite('https://github.com/emersonrp/bindcontrol')
self.about_info = info
wx.adv.GenericAboutBox(self.about_info, self)
def OnMenuLogWindow(self, _) -> None:
pub.sendMessage('showlogwindow')
def OnMenuExitApplication(self, _) -> None:
self.Close()
def OnHelpGettingStarted(self, _) -> None:
wx.LaunchDefaultBrowser('https://github.com/emersonrp/bindcontrol/wiki/Getting-Started-With-BindControl')
def OnHelpLicense(self, _) -> None:
ShowHelpWindow(self, 'LICENSE.html')
def OnHelpBugs(self, _) -> None:
ShowHelpWindow(self, 'ReportingBugs.html')
def OnHelpFiles(self, _) -> None:
ShowHelpWindow(self, 'OutputFiles.html')
def OnHelpBindDirs(self, _) -> None:
window = BindDirsWindow(self, title = "Bind Directories", style = wx.TINY_CAPTION|wx.CLOSE_BOX|wx.CAPTION)
window.Show()
def OnWindowClosing(self, evt) -> None:
if self.CheckIfProfileNeedsSaving() == wx.CANCEL: return
config = wx.ConfigBase.Get()
if config.ReadBool('SaveSizeAndPosition'):
config.WriteInt('WinX', self.GetPosition().x)
config.WriteInt('WinY', self.GetPosition().y)
config.WriteInt('WinH', self.GetSize().height)
config.WriteInt('WinW', self.GetSize().width)
config.Flush()
evt.Skip()
class MyApp(wx.App, wx.lib.mixins.inspection.InspectionMixin):
def OnInit(self):
# Let's try to unbuffer "print" for easier debug
# This per "Perkins"' comment on https://stackoverflow.com/questions/107705/disable-output-buffering
import builtins
import functools
builtins.print = functools.partial(print, flush=True)
self.Init()
return True
def Populate(self, input_profile):
with wx.WindowDisabler():
_ = wx.BusyInfo('Initializing BindControl...')
wx.GetApp().Yield()
self.Main = Main()
# get the height, width, and position all set up before Show()
(width, height) = (1100, 800)
if config.ReadBool('SaveSizeAndPosition') and config.HasEntry('WinH') and config.HasEntry('WinW'):
height = config.ReadInt('WinH')
width = config.ReadInt('WinW')
if width and height:
self.Main.SetSize(wx.Size(width, height))
if config.ReadBool('SaveSizeAndPosition') and config.HasEntry('WinX') and config.HasEntry('WinY'):
self.Main.SetPosition(wx.Point((config.ReadInt('WinX'), config.ReadInt('WinY'))))
# we MUST Show() the window before setting up the intial profile, or various widgets
# and dialogs and so forth will get pathological ideas about their sizes and/or
# positions, on Windows. Show(), then load.
self.Main.Show()
self.Main.SetupInitialProfile(input_profile = input_profile)
# lay out the screen now that we have a profile or startup panel
self.Main.Layout()
# TODO bootstrapping problem, can't do this inside Profile's "__init__" because
# Profile needs to be defined/initialized deep inside its innards to succeed at this.
if self.Main.Profile:
self.Main.Profile.CheckAllConflicts()
if self.Main.Profile:
wx.CallAfter(self.Main.Profile.CheckIfGameDirNeeded)
if __name__ == "__main__":
argv = sys.argv
if len(argv) > 2:
sys.stderr.write('\n')
sys.stderr.write('Usage: BindControl.py [profile_file]\n')
sys.stderr.write('\n')
sys.stderr.write('profile_file is optional, and should be a *.bcp file\n')
sys.stderr.write('\n')
exit()
input_profile = ''
filename = argv[1] if len(argv) == 2 else None
if filename:
if re.search(r'\.bcp$', filename):
input_profile = filename
app = MyApp(redirect=False)
stdpaths = wx.StandardPaths.Get()
if platform.system() == "Linux":
stdpaths.SetFileLayout(stdpaths.FileLayout_XDG)
config = wx.FileConfig('bindcontrol')
wx.ConfigBase.Set(config)
# Set up custom font waaaaay back here
rootdir = Util.Paths.GetRootDirPath()
if (platform.system() == 'Darwin') and (rootdir.parts[-1] == 'Frameworks'):
rootdir = rootdir.parent / 'Resources'
wx.Font.AddPrivateFont(str(rootdir / 'Fonts' / 'mont_demibold.ttf'))
wx.Font.AddPrivateFont(str(rootdir / 'Fonts' / 'paragon city italic.ttf'))
elif platform.system() != 'Darwin':
# don't do this AT ALL on MacOS if we're running from source.
# There seems to be no way to do this in that case, so if we didn't
# get into the "Frameworks" case above (and therefore are running from
# a pyinstaller-bundled .app dir), just don't try the fonts.
wx.Font.AddPrivateFont(str(rootdir / 'Fonts' / 'mont_demibold.ttf'))
wx.Font.AddPrivateFont(str(rootdir / 'Fonts' / 'paragon city italic.ttf'))
app.Populate(input_profile)
if config.ReadBool('ShowInspector'):
import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()