-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_window.py
More file actions
executable file
·1152 lines (926 loc) · 45 KB
/
main_window.py
File metadata and controls
executable file
·1152 lines (926 loc) · 45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Game Chooser - A desktop game library manager
# Copyright (C) 2025 Alec Olson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
"""
Main window for Game Chooser application
"""
import wx
import os
import subprocess
import platform
import webbrowser
import threading
import random
from pathlib import Path
from models import Game
from library_manager import GameLibraryManager
from game_list import GameListCtrl
from dialogs import GameDialog, PreferencesDialog, DeleteGameDialog, FirstTimeSetupDialog
class FilterWorker(threading.Thread):
"""Background thread for filtering games to prevent UI freezing"""
def __init__(self, games, search_term, tree_criteria, library_filter, callback):
super().__init__(daemon=True)
self.games = games
self.search_term = search_term.lower().strip() if search_term else ""
self.tree_criteria = tree_criteria
self.library_filter = library_filter # List of active libraries (empty means all)
self.callback = callback
self._stop_event = threading.Event()
def stop(self):
"""Signal the thread to stop"""
self._stop_event.set()
def run(self):
"""Filter games in background"""
filtered = []
for game in self.games:
# Check if we should stop
if self._stop_event.is_set():
return
# Apply library filter
# Manual games and web games are always included
if game.library_name and game.library_name != "manual" and game.library_name != "":
# If library_filter is None, show all (no filtering)
# If library_filter is empty list, show none (all unchecked)
# If library_filter has items, show only those
if self.library_filter is not None and game.library_name not in self.library_filter:
continue
# Apply tree filter
if self.tree_criteria:
platform_match = not self.tree_criteria["platforms"] or \
any(p in self.tree_criteria["platforms"] for p in game.platforms)
genre_match = not self.tree_criteria["genres"] or \
game.genre in self.tree_criteria["genres"] or \
(game.genre == "" and "Unknown Genre" in self.tree_criteria["genres"])
dev_match = not self.tree_criteria["developers"] or \
game.developer in self.tree_criteria["developers"] or \
(game.developer == "" and "Unknown Developer" in self.tree_criteria["developers"])
year_match = not self.tree_criteria["years"] or \
game.year in self.tree_criteria["years"] or \
(game.year == "" and "Unknown Year" in self.tree_criteria["years"])
if not (platform_match and genre_match and dev_match and year_match):
continue
# Apply search filter
if self.search_term:
# Exclude "unknown" from all searches
if "unknown" in self.search_term:
continue
if not any(self.search_term in field.lower() for field in
[game.title, game.developer]):
continue
filtered.append(game)
# Call the callback with results if not stopped
if not self._stop_event.is_set():
wx.CallAfter(self.callback, filtered)
class MainFrame(wx.Frame):
"""Main application window"""
def __init__(self):
super().__init__(None, title="Game Chooser (0)")
self.library_manager = GameLibraryManager()
self.filtered_games = []
self.filter_worker = None # Background filtering thread
self._tree_cache = None # Cache for tree categories
self._games_hash = None # Hash to detect when games list changes
self.dialog_active = False # Flag to block spurious events when modal dialogs are open
self.restoring_tree = False # Flag to block saves during tree restoration
self.initializing = True # Flag to prevent focus stealing during startup
self.current_tree_filters = ["platform", "genre", "developer", "year"] # Track active tree filters
self.active_libraries = None # Track active libraries for filtering (None means show all, empty list means show none)
self.library_menu_items = {} # Map library names to menu items
# Set up UI
self.init_ui()
# Load saved state
self.load_saved_state()
# Initial library check
self.check_libraries()
# Update title
self.update_title()
# Bind close event
self.Bind(wx.EVT_CLOSE, self.on_close)
def init_ui(self):
"""Initialize the user interface"""
panel = wx.Panel(self)
main_sizer = wx.BoxSizer(wx.VERTICAL)
# Menu bar
self.create_menu_bar()
# Search combo box
search_sizer = wx.BoxSizer(wx.HORIZONTAL)
search_label = wx.StaticText(panel, label="Search:")
self.search_combo = wx.ComboBox(panel, style=wx.CB_DROPDOWN)
self.search_combo.Bind(wx.EVT_TEXT, self.on_search_text)
self.search_combo.Bind(wx.EVT_COMBOBOX, self.on_search_select)
search_sizer.Add(search_label, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5)
search_sizer.Add(self.search_combo, 1, wx.EXPAND)
main_sizer.Add(search_sizer, 0, wx.EXPAND | wx.ALL, 5)
# Splitter for list and tree
splitter = wx.SplitterWindow(panel)
# Game list
self.game_list = GameListCtrl(splitter, self.library_manager)
self.game_list.SetLabel("Games")
self.game_list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_game_selected)
self.game_list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_game_activated)
# Context menu: right-click handled by list event, keyboard shortcuts in on_list_key
self.game_list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_list_context)
self.game_list.Bind(wx.EVT_KEY_DOWN, self.on_list_key)
# Tree control
tree_panel = wx.Panel(splitter)
tree_sizer = wx.BoxSizer(wx.VERTICAL)
# Add hidden label for accessibility
tree_label = wx.StaticText(tree_panel, label="Filter games by:")
tree_label.Hide()
tree_sizer.Add(tree_label, 0, wx.ALL, 0)
self.tree_ctrl = wx.TreeCtrl(tree_panel,
style=wx.TR_DEFAULT_STYLE | wx.TR_MULTIPLE)
self.tree_ctrl.Bind(wx.EVT_TREE_SEL_CHANGED, self.on_tree_selection)
self.tree_ctrl.Bind(wx.EVT_KEY_DOWN, self.on_tree_key)
tree_sizer.Add(self.tree_ctrl, 1, wx.EXPAND)
tree_panel.SetSizer(tree_sizer)
# Set up splitter - use exposed control property
splitter.SplitVertically(self.game_list.control, tree_panel)
splitter.SetSashGravity(0.5)
main_sizer.Add(splitter, 1, wx.EXPAND)
# Launch button
self.launch_btn = wx.Button(panel, label="Launch")
self.launch_btn.Bind(wx.EVT_BUTTON, self.on_launch)
main_sizer.Add(self.launch_btn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
panel.SetSizer(main_sizer)
# Store splitter reference
self.splitter = splitter
# Set up keyboard shortcuts
self.setup_accelerators()
# Note: Tree will be built after loading saved state
# to use the saved filter configuration
# Populate initial game list
self.refresh_game_list()
def create_menu_bar(self):
"""Create the menu bar"""
menu_bar = wx.MenuBar()
# File menu
file_menu = wx.Menu()
add_game_item = file_menu.Append(wx.ID_ANY, "&Add Game\tCtrl+N")
self.Bind(wx.EVT_MENU, self.on_add_game, add_game_item)
refresh_item = file_menu.Append(wx.ID_ANY, "&Refresh Library\tF5")
self.Bind(wx.EVT_MENU, self.on_refresh, refresh_item)
file_menu.AppendSeparator()
# Use platform-appropriate exit shortcut (wxPython handles Ctrl->Cmd mapping on macOS)
system = platform.system()
exit_shortcut = "Ctrl+Q" if system == "Darwin" else "Alt+F4"
exit_item = file_menu.Append(wx.ID_EXIT, f"E&xit\t{exit_shortcut}")
self.Bind(wx.EVT_MENU, self.on_exit, exit_item)
menu_bar.Append(file_menu, "&File")
# Edit menu
edit_menu = wx.Menu()
edit_game_item = edit_menu.Append(wx.ID_ANY, "&Edit Game\tCtrl+E")
self.Bind(wx.EVT_MENU, self.on_edit_game, edit_game_item)
delete_game_item = edit_menu.Append(wx.ID_ANY, "&Delete Game\tDel")
self.Bind(wx.EVT_MENU, self.on_delete_game, delete_game_item)
edit_menu.AppendSeparator()
# Use Ctrl for both platforms (wxPython maps to Cmd on macOS automatically)
pref_item = edit_menu.Append(wx.ID_PREFERENCES, "&Preferences\tCtrl+,")
self.Bind(wx.EVT_MENU, self.on_preferences, pref_item)
menu_bar.Append(edit_menu, "&Edit")
# View menu
view_menu = wx.Menu()
# Filter Tree submenu
filter_tree_menu = wx.Menu()
# Store menu items as instance variables for state updates
self.filter_platform_item = filter_tree_menu.AppendCheckItem(wx.ID_ANY, "&Platform")
self.Bind(wx.EVT_MENU, self.on_toggle_filter_platform, self.filter_platform_item)
self.filter_genre_item = filter_tree_menu.AppendCheckItem(wx.ID_ANY, "&Genre")
self.Bind(wx.EVT_MENU, self.on_toggle_filter_genre, self.filter_genre_item)
self.filter_developer_item = filter_tree_menu.AppendCheckItem(wx.ID_ANY, "&Developer")
self.Bind(wx.EVT_MENU, self.on_toggle_filter_developer, self.filter_developer_item)
self.filter_year_item = filter_tree_menu.AppendCheckItem(wx.ID_ANY, "&Year")
self.Bind(wx.EVT_MENU, self.on_toggle_filter_year, self.filter_year_item)
view_menu.AppendSubMenu(filter_tree_menu, "&Filter Tree")
# Libraries submenu
self.libraries_menu = wx.Menu()
self.build_libraries_menu()
view_menu.AppendSubMenu(self.libraries_menu, "&Libraries")
menu_bar.Append(view_menu, "&View")
# Launch menu
launch_menu = wx.Menu()
random_game_item = launch_menu.Append(wx.ID_ANY, "&Random Game\tCtrl+R")
self.Bind(wx.EVT_MENU, self.on_random_game, random_game_item)
menu_bar.Append(launch_menu, "&Launch")
self.SetMenuBar(menu_bar)
def setup_accelerators(self):
"""Set up keyboard accelerators"""
accel_entries = []
# Ctrl+F for search
search_id = wx.NewIdRef()
accel_entries.append((wx.ACCEL_CTRL, ord('F'), search_id))
self.Bind(wx.EVT_MENU, lambda e: self.search_combo.SetFocus(), id=search_id)
# Ctrl+N for new game
new_game_id = wx.NewIdRef()
accel_entries.append((wx.ACCEL_CTRL, ord('N'), new_game_id))
self.Bind(wx.EVT_MENU, self.on_add_game, id=new_game_id)
# Ctrl+Enter for open folder
open_folder_id = wx.NewIdRef()
accel_entries.append((wx.ACCEL_CTRL, wx.WXK_RETURN, open_folder_id))
self.Bind(wx.EVT_MENU, self.on_open_folder, id=open_folder_id)
# F5 for refresh
refresh_id = wx.NewIdRef()
accel_entries.append((wx.ACCEL_NORMAL, wx.WXK_F5, refresh_id))
self.Bind(wx.EVT_MENU, self.on_refresh, id=refresh_id)
# Ctrl+R for random game
random_game_id = wx.NewIdRef()
accel_entries.append((wx.ACCEL_CTRL, ord('R'), random_game_id))
self.Bind(wx.EVT_MENU, self.on_random_game, id=random_game_id)
accel_table = wx.AcceleratorTable(accel_entries)
self.SetAcceleratorTable(accel_table)
def check_libraries(self):
"""Check if first run and show setup dialog"""
if self.library_manager.is_first_run:
dlg = FirstTimeSetupDialog(self, self.library_manager)
result = dlg.ShowModal()
dlg.Destroy()
# If libraries were added, prompt user to scan
if result == wx.ID_OK and self.library_manager.config["libraries"]:
response = wx.MessageBox(
"Would you like to scan your libraries for games now?\n\n"
"You can also scan later using Refresh (F5).",
"Scan Libraries?",
wx.YES_NO | wx.ICON_QUESTION
)
if response == wx.YES:
try:
scan_result = self.library_manager.scan_with_dialog(self)
# If scan wasn't cancelled, refresh UI
if scan_result is not None:
exceptions_count, removed_libraries = scan_result
# Handle removed libraries
if removed_libraries:
lib_paths = "\n".join([f"• {lib['name']}: {lib['path']}" for lib in removed_libraries])
message = f"The following library paths were not found and have been removed from your configuration:\n\n{lib_paths}\n\nWould you like to update your library settings?"
if wx.MessageBox(message, "Missing Library Paths Removed",
wx.YES_NO | wx.ICON_WARNING) == wx.YES:
self.on_preferences(None)
except PermissionError as e:
wx.MessageBox(str(e), "Permission Denied", wx.OK | wx.ICON_ERROR)
# Refresh UI in case they added stuff
self.refresh_game_list()
self.build_tree(force_rebuild=True)
# Always continue to main window (no forced scanning)
self.initializing = False
self.game_list.SetFocus()
def build_tree(self, filters=None, force_rebuild=False, restore_selections=True):
"""Build the tree control hierarchy with flat 2-level structure using cache"""
if filters is None:
filters = ["platform", "genre", "developer", "year"]
# Store the current filters for dialog state
self.current_tree_filters = filters
# Generate a simple hash of games to detect changes
current_hash = len(self.library_manager.games)
if current_hash > 0:
# Include first and last game titles for better change detection
current_hash = hash((current_hash,
self.library_manager.games[0].title if self.library_manager.games else "",
self.library_manager.games[-1].title if self.library_manager.games else ""))
# Check if we can use cached data
if not force_rebuild and self._tree_cache is not None and self._games_hash == current_hash:
categories = self._tree_cache
else:
# Collect unique values for each category
categories = {
"platform": set(),
"genre": set(),
"developer": set(),
"year": set()
}
for game in self.library_manager.games:
# Collect platforms
if "platform" in filters:
for platform in game.platforms:
categories["platform"].add(platform)
# Collect genres
if "genre" in filters:
genre = game.genre or "Unknown Genre"
categories["genre"].add(genre)
# Collect developers
if "developer" in filters:
developer = game.developer or "Unknown Developer"
categories["developer"].add(developer)
# Collect years
if "year" in filters:
year = game.year or "Unknown Year"
categories["year"].add(year)
# Cache the results
self._tree_cache = categories
self._games_hash = current_hash
# Clear and rebuild tree control
self.tree_ctrl.DeleteAllItems()
root = self.tree_ctrl.AddRoot("Filters")
# Category labels and their children
category_labels = {
"platform": "Platform",
"genre": "Genre",
"developer": "Developer",
"year": "Release Year"
}
for category_key in ["platform", "genre", "developer", "year"]:
if category_key in filters and categories[category_key]:
# Add category node
category_node = self.tree_ctrl.AppendItem(root, category_labels[category_key])
# Add all values under this category (case-insensitive sort)
for value in sorted(categories[category_key], key=str.lower):
self.tree_ctrl.AppendItem(category_node, value)
# Expand only the root to show categories, but keep all categories collapsed
self.tree_ctrl.Expand(root)
# Restore saved selections (only if requested)
if restore_selections:
self.restore_tree_selections()
def on_tree_selection(self, event):
"""Handle tree selection changes"""
# Save tree selections (skip during restoration to avoid multiple saves)
if not self.restoring_tree:
self.save_tree_selections()
self.apply_filters()
def on_tree_key(self, event):
"""Handle tree keyboard events"""
if event.GetKeyCode() == wx.WXK_ESCAPE:
# Clear selection
self.tree_ctrl.UnselectAll()
self.apply_filters()
elif event.GetKeyCode() == wx.WXK_DELETE:
# Delete selected game if applicable
# (Tree doesn't have games anymore, so this might not apply)
pass
else:
event.Skip()
def get_tree_selection_criteria(self):
"""Get filtering criteria from tree selection"""
selections = self.tree_ctrl.GetSelections()
if not selections:
return None
criteria = {
"platforms": set(),
"genres": set(),
"developers": set(),
"years": set()
}
# Category label mapping
category_mapping = {
"Platform": "platforms",
"Genre": "genres",
"Developer": "developers",
"Release Year": "years"
}
for item in selections:
item_text = self.tree_ctrl.GetItemText(item)
parent = self.tree_ctrl.GetItemParent(item)
# Skip root node
if parent == self.tree_ctrl.GetRootItem() or not parent:
# This is a category node - ignore for now (could add "select all" logic later)
continue
# Get parent category
parent_text = self.tree_ctrl.GetItemText(parent)
if parent_text in category_mapping:
criteria_key = category_mapping[parent_text]
criteria[criteria_key].add(item_text)
return criteria
def save_tree_selections(self):
"""Save current tree selections to config"""
selections = self.tree_ctrl.GetSelections()
paths = []
for item in selections:
item_text = self.tree_ctrl.GetItemText(item)
parent = self.tree_ctrl.GetItemParent(item)
# Skip root node
if parent == self.tree_ctrl.GetRootItem() or not parent:
continue
# Build path: "Parent/Child"
parent_text = self.tree_ctrl.GetItemText(parent)
path = f"{parent_text}/{item_text}"
paths.append(path)
self.library_manager.config["SavedState"]["tree_selections"] = paths
self.library_manager.save_config()
def restore_tree_selections(self):
"""Restore saved tree selections"""
saved_paths = self.library_manager.config["SavedState"]["tree_selections"]
if not saved_paths:
return
# Set flag to prevent saving during restoration
self.restoring_tree = True
try:
# Clear current selections
self.tree_ctrl.UnselectAll()
# Walk tree to find and select items
root = self.tree_ctrl.GetRootItem()
if not root:
return
# Iterate through category nodes
category_item, cookie = self.tree_ctrl.GetFirstChild(root)
while category_item:
category_text = self.tree_ctrl.GetItemText(category_item)
# Iterate through child items
child_item, child_cookie = self.tree_ctrl.GetFirstChild(category_item)
while child_item:
child_text = self.tree_ctrl.GetItemText(child_item)
path = f"{category_text}/{child_text}"
if path in saved_paths:
self.tree_ctrl.SelectItem(child_item, True)
child_item, child_cookie = self.tree_ctrl.GetNextChild(category_item, child_cookie)
category_item, cookie = self.tree_ctrl.GetNextChild(root, cookie)
finally:
# Always clear the flag
self.restoring_tree = False
def apply_filters(self):
"""Apply search and tree filters using background thread"""
# Stop any existing filter operation
if self.filter_worker and self.filter_worker.is_alive():
self.filter_worker.stop()
self.filter_worker.join(timeout=0.1) # Brief wait for cleanup
search_term = self.search_combo.GetValue()
tree_criteria = self.get_tree_selection_criteria()
# Start new filter operation in background
self.filter_worker = FilterWorker(
self.library_manager.games,
search_term,
tree_criteria,
self.active_libraries,
self.on_filter_complete
)
self.filter_worker.start()
def on_filter_complete(self, filtered_games):
"""Called when background filtering is complete"""
self.filtered_games = filtered_games
self.game_list.populate(filtered_games)
# Select and focus item for screen reader accessibility
if filtered_games:
# Try to restore previously selected game
last_selected = self.library_manager.config["SavedState"]["last_selected"]
selected_index = 0 # Default to first item
if last_selected:
# Search for the saved game in filtered results
for i, game in enumerate(filtered_games):
if game.title == last_selected:
selected_index = i
break
# Select and focus the item (for screen reader compatibility)
# But don't steal keyboard focus - let user stay where they are
self.game_list.Select(selected_index)
self.game_list.Focus(selected_index)
# Removed SetFocus() - was stealing focus from tree control on every filter change
def refresh_game_list(self):
"""Refresh the game list display"""
self.apply_filters()
self.update_title()
def on_search_text(self, event):
"""Handle search text changes immediately"""
# Apply filters immediately - virtual list makes this fast
self.apply_filters()
def on_search_select(self, event):
"""Handle combo box selection"""
self.apply_filters()
def on_game_selected(self, event):
"""Handle game selection in list"""
# Ignore spurious selection events when modal dialogs are active
if self.dialog_active:
return
game = self.game_list.get_selected_game()
if game:
self.launch_btn.SetLabel(f"Launch {game.title}")
# Save selected game
self.library_manager.config["SavedState"]["last_selected"] = game.title
self.library_manager.save_config()
def on_game_activated(self, event):
"""Handle double-click on game"""
self.on_launch(None)
def on_list_context(self, event):
"""Show context menu for list (supports both mouse and keyboard)"""
menu = wx.Menu()
game = self.game_list.get_selected_game()
if game:
launch_item = menu.Append(wx.ID_ANY, "Launch")
self.Bind(wx.EVT_MENU, self.on_launch, launch_item)
edit_item = menu.Append(wx.ID_ANY, "Edit")
self.Bind(wx.EVT_MENU, self.on_edit_game, edit_item)
open_folder_item = menu.Append(wx.ID_ANY, "Open folder")
self.Bind(wx.EVT_MENU, self.on_open_folder, open_folder_item)
delete_item = menu.Append(wx.ID_ANY, "Delete")
self.Bind(wx.EVT_MENU, self.on_delete_game, delete_item)
menu.AppendSeparator()
add_game_item = menu.Append(wx.ID_ANY, "Add Game")
self.Bind(wx.EVT_MENU, self.on_add_game, add_game_item)
# Determine if this is a mouse event or keyboard event
if hasattr(event, 'GetEventType') and event.GetEventType() == wx.wxEVT_LIST_ITEM_RIGHT_CLICK:
# Mouse right-click: show at default position (wxPython positions automatically)
self.PopupMenu(menu)
else:
# Keyboard event (Shift+F10, context menu key): show at selected item
# Get selected item position
selected_index = self.game_list.GetFirstSelected()
if selected_index >= 0:
# Get item rectangle to position menu near selected item
rect = self.game_list.control.GetItemRect(selected_index)
pos = wx.Point(rect.x + 10, rect.y + rect.height // 2)
self.game_list.control.PopupMenu(menu, pos)
else:
# No selection, show at default position
self.PopupMenu(menu)
menu.Destroy()
def on_list_key(self, event):
"""Handle list keyboard events"""
key = event.GetKeyCode()
if key == ord('E') and event.ControlDown():
self.on_edit_game(None)
elif key == wx.WXK_DELETE:
self.on_delete_game(None)
elif key in [wx.WXK_RETURN, wx.WXK_SPACE]:
self.on_launch(None)
elif key == wx.WXK_WINDOWS_MENU or (key == wx.WXK_F10 and event.ShiftDown()):
# Applications/context menu key or Shift+F10
self.on_list_context(event)
else:
event.Skip()
def on_open_folder(self, event):
"""Open the game's folder in the file manager"""
game = self.game_list.get_selected_game()
if not game:
return
# Skip web games - no local folder to open
if game.launch_path.startswith("http"):
return
# Get full path to game
full_path = self.library_manager.get_full_path(game)
if not full_path or not Path(full_path).exists():
wx.MessageBox("Game folder not found.",
"Folder Not Found", wx.OK | wx.ICON_ERROR)
return
# Get the game directory
game_dir = str(Path(full_path).parent)
# Open folder with platform-specific command
try:
system = platform.system()
if system == "Windows":
# Open folder and highlight the executable
subprocess.Popen(['explorer', '/select,', full_path])
elif system == "Darwin":
# macOS - just open the folder
subprocess.Popen(['open', game_dir])
except Exception as e:
wx.MessageBox(f"Failed to open folder: {e}",
"Error", wx.OK | wx.ICON_ERROR)
def launch_game(self, game):
"""Launch a specific game"""
# Check platform compatibility for non-web games
if not game.launch_path.startswith("http"):
# Get current platform
current_system = platform.system()
# Map system name to our platform names
platform_map = {
"Windows": "Windows",
"Darwin": "macOS",
"Linux": "Linux"
}
current_platform = platform_map.get(current_system, current_system)
# Check if current platform is supported by the game
if current_platform not in game.platforms:
# Build supported platforms string
supported = ", ".join(game.platforms) if game.platforms else "no platforms"
# Show error dialog
wx.MessageBox(
f"You're trying to run {game.title} on {current_platform}, but it only supports {supported}.",
"Uh-oh",
wx.OK | wx.ICON_ERROR
)
return
if game.launch_path.startswith("http"):
# Web game
webbrowser.open(game.launch_path)
else:
# Regular game
full_path = self.library_manager.get_full_path(game)
if not full_path or not Path(full_path).exists():
wx.MessageBox("Game executable not found. Please locate the game.",
"File Not Found", wx.OK | wx.ICON_ERROR)
# File dialog to relocate
dlg = wx.FileDialog(self, "Locate Game Executable")
if dlg.ShowModal() == wx.ID_OK:
new_path = dlg.GetPath()
# Validate path is in a library
valid = False
for lib in self.library_manager.config["libraries"]:
if new_path.startswith(lib["path"]):
# Update game path
rel_path = Path(new_path).relative_to(Path(lib["path"]).parent)
game.launch_path = str(rel_path).replace(os.sep, '/')
self.library_manager.save_games()
valid = True
break
if not valid:
wx.MessageBox("Selected file is not in a configured game library.",
"Invalid Location", wx.OK | wx.ICON_ERROR)
return
dlg.Destroy()
return
# Launch the game
try:
game_dir = str(Path(full_path).parent)
system = platform.system()
if system == "Darwin" and full_path.endswith(".app"):
# macOS .app bundle
subprocess.Popen(["open", "-a", full_path], cwd=game_dir)
else:
# Regular executable
subprocess.Popen([full_path], cwd=game_dir)
# Minimize window
self.Iconize(True)
except Exception as e:
wx.MessageBox(f"Failed to launch game: {e}",
"Launch Error", wx.OK | wx.ICON_ERROR)
def on_launch(self, event):
"""Launch selected game"""
game = self.game_list.get_selected_game()
if not game:
return
self.launch_game(game)
def on_random_game(self, event):
"""Pick a random game from filtered list and offer to launch it"""
if not self.filtered_games:
wx.MessageBox("No games available to choose from.",
"No Games", wx.OK | wx.ICON_INFORMATION)
return
# Filter for platform-compatible games only
current_system = platform.system()
platform_map = {
"Windows": "Windows",
"Darwin": "macOS",
"Linux": "Linux"
}
current_platform = platform_map.get(current_system, current_system)
# Get games compatible with current platform (or web games)
compatible_games = [
game for game in self.filtered_games
if game.launch_path.startswith("http") or current_platform in game.platforms
]
if not compatible_games:
wx.MessageBox(
f"No games compatible with {current_platform} in the current filtered list.",
"No Compatible Games",
wx.OK | wx.ICON_INFORMATION
)
return
# Pick random game
random_game = random.choice(compatible_games)
# Show dialog
response = wx.MessageBox(
f"Your game for today is...\n\n{random_game.title}\n\nLaunch now?",
"Random Game",
wx.YES_NO | wx.ICON_QUESTION
)
if response == wx.YES:
self.launch_game(random_game)
def on_edit_game(self, event):
"""Edit selected game"""
game = self.game_list.get_selected_game()
if not game:
return
dlg = GameDialog(self, self.library_manager, game)
# Block spurious selection events while modal dialog is active
self.dialog_active = True
try:
if dlg.ShowModal() == wx.ID_OK:
self.library_manager.save_games()
self.refresh_game_list()
finally:
self.dialog_active = False
dlg.Destroy()
def on_delete_game(self, event):
"""Delete selected game"""
game = self.game_list.get_selected_game()
if not game:
return
# Remember the current index position to maintain list position after deletion
current_index = self.game_list.GetFirstSelected()
# Show custom delete dialog
dlg = DeleteGameDialog(self, game.title)
# Block spurious selection events while modal dialog is active
self.dialog_active = True
try:
result = dlg.ShowModal()
finally:
self.dialog_active = False
dlg.Destroy()
if result == wx.ID_YES:
# Delete without adding to exceptions
self.library_manager.games.remove(game)
self.library_manager.save_games()
self.refresh_game_list()
# Select previous item to stay in same area of list
new_index = max(0, current_index - 1) if current_index > 0 else 0
if new_index < len(self.filtered_games):
self.game_list.Select(new_index)
self.game_list.Focus(new_index)
elif result == DeleteGameDialog.ID_DELETE_AND_EXCEPTION:
# Delete and add to exceptions
self.library_manager.add_to_exceptions(game)
self.library_manager.games.remove(game)
self.library_manager.save_games()
self.refresh_game_list()
# Select previous item to stay in same area of list
new_index = max(0, current_index - 1) if current_index > 0 else 0
if new_index < len(self.filtered_games):
self.game_list.Select(new_index)
self.game_list.Focus(new_index)
def on_add_game(self, event):
"""Add a new game"""
dlg = GameDialog(self, self.library_manager)
# Block spurious selection events while modal dialog is active
self.dialog_active = True
try:
if dlg.ShowModal() == wx.ID_OK:
self.library_manager.games.append(dlg.game)
self.library_manager.save_games()
self.refresh_game_list()
finally:
self.dialog_active = False
dlg.Destroy()
def on_toggle_filter_platform(self, event):
"""Toggle platform filter in tree"""
self._toggle_filter("platform")
def on_toggle_filter_genre(self, event):
"""Toggle genre filter in tree"""
self._toggle_filter("genre")
def on_toggle_filter_developer(self, event):
"""Toggle developer filter in tree"""
self._toggle_filter("developer")
def on_toggle_filter_year(self, event):
"""Toggle year filter in tree"""
self._toggle_filter("year")
def _toggle_filter(self, filter_key):
"""Toggle a filter and rebuild tree"""
if filter_key in self.current_tree_filters:
self.current_tree_filters.remove(filter_key)
else:
self.current_tree_filters.append(filter_key)
# Rebuild tree with updated filters
self.build_tree(self.current_tree_filters)
# Update menu item check states
self.update_filter_menu_state()
# Save filter state immediately
self.library_manager.config["SavedState"]["tree_filters"] = self.current_tree_filters
self.library_manager.save_config()
def update_filter_menu_state(self):
"""Update filter menu item check states based on current filters"""
self.filter_platform_item.Check("platform" in self.current_tree_filters)
self.filter_genre_item.Check("genre" in self.current_tree_filters)
self.filter_developer_item.Check("developer" in self.current_tree_filters)
self.filter_year_item.Check("year" in self.current_tree_filters)
def build_libraries_menu(self):
"""Build/rebuild the libraries submenu with current libraries"""
# Clear existing items
for item in self.library_menu_items.values():
self.libraries_menu.Delete(item)
self.library_menu_items.clear()
# Get all libraries (excluding manual)
libraries = [lib for lib in self.library_manager.config["libraries"]
if lib["name"] != "manual"]
# Initialize active_libraries if None (first time setup)
if self.active_libraries is None:
self.active_libraries = [lib["name"] for lib in libraries]
# Add menu item for each library
for library in libraries:
lib_name = library["name"]
menu_item = self.libraries_menu.AppendCheckItem(wx.ID_ANY, lib_name)
self.library_menu_items[lib_name] = menu_item
# Bind event handler
self.Bind(wx.EVT_MENU, lambda evt, name=lib_name: self.on_toggle_library(evt, name), menu_item)
# Check the item if library is in active list
menu_item.Check(lib_name in self.active_libraries)
def on_toggle_library(self, event, library_name):
"""Toggle library visibility"""
if library_name in self.active_libraries: