-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathLuaTools.py
More file actions
9399 lines (7936 loc) · 400 KB
/
LuaTools.py
File metadata and controls
9399 lines (7936 loc) · 400 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
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import tkinter.font as tkfont
import winreg
import os
import sys
import httpx
import re
import json
import threading
import time
import zipfile
import tempfile
import shutil
import subprocess
import psutil
from pathlib import Path
import urllib.request
import urllib.error
# Try to import Windows API for drag and drop
try:
import ctypes
from ctypes import wintypes
from ctypes.wintypes import DWORD, HWND, UINT, WPARAM, LPARAM, BOOL, HANDLE, LPWSTR, LPCWSTR
from ctypes.wintypes import RECT, POINT
# Windows constants
WM_DROPFILES = 0x0233
CF_HDROP = 15
# Windows API functions
user32 = ctypes.windll.user32
shell32 = ctypes.windll.shell32
# Function signatures
DragQueryFileW = shell32.DragQueryFileW
DragQueryFileW.argtypes = [HANDLE, UINT, LPWSTR, UINT]
DragQueryFileW.restype = UINT
DragFinish = shell32.DragFinish
DragFinish.argtypes = [HANDLE]
SetWindowLongPtrW = user32.SetWindowLongPtrW
SetWindowLongPtrW.argtypes = [HWND, ctypes.c_int, ctypes.c_longlong]
SetWindowLongPtrW.restype = ctypes.c_longlong
GetWindowLongPtrW = user32.GetWindowLongPtrW
GetWindowLongPtrW.argtypes = [HWND, ctypes.c_int]
GetWindowLongPtrW.restype = ctypes.c_longlong
# Constants
GWLP_WNDPROC = -4
GWL_EXSTYLE = -20
WS_EX_ACCEPTFILES = 0x00000010
# Enable drag and drop
DND_AVAILABLE = True
except ImportError:
DND_AVAILABLE = False
print("Windows API not available, drag and drop disabled")
# Try to import archive libraries
try:
import rarfile
except ImportError:
rarfile = None
try:
import py7zr
except ImportError:
py7zr = None
# Version and repository configuration
__version__ = "2.6" # Your current version
__github_repo__ = "madoiscool/LuaTools" # Replace with your actual repo
class SteamStyleApp:
def __init__(self, root):
self.root = root
self.root.title("LuaTools - by melly")
self.root.geometry("900x700")
self.root.configure(bg='#0f1419') # Modern deep dark blue-black
# Store icon path for later use
if getattr(sys, 'frozen', False):
# Running as executable
self.icon_path = os.path.join(os.path.dirname(sys.executable), 'icon.ico')
else:
# Running as script
self.icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.ico')
# Set basic window icon (will be enhanced later for executables)
if os.path.exists(self.icon_path):
try:
self.root.iconbitmap(self.icon_path)
print(f"Basic window icon set: {self.icon_path}")
except Exception as e:
print(f"Could not set basic window icon: {e}")
else:
print(f"Icon file not found at: {self.icon_path}")
# Initialize timer management for copy operations
self.copy_timers = {}
# Hide window until it's centered
self.root.withdraw()
# Center the window on screen
self.center_window()
# Show the window after centering
self.root.deiconify()
# Now that the window is shown, set the proper icon for executables
if getattr(sys, 'frozen', False):
self.root.after(50, self.set_executable_icon)
# Store original window procedure for drag and drop
self.original_wndproc = None
# Modern color scheme with better contrast and visual appeal
self.colors = {
'bg': '#0f1419', # Deep dark blue-black
'secondary_bg': '#1a2332', # Slightly lighter dark blue
'card_bg': '#232b38', # Card background
'accent': '#4f46e5', # Modern indigo
'accent_hover': '#6366f1', # Lighter indigo for hover
'text': '#f8fafc', # Almost white text
'text_secondary': '#cbd5e1', # Secondary text
'text_muted': '#94a3b8', # Muted text
'button_bg': '#4f46e5', # Indigo button
'button_hover': '#6366f1', # Lighter indigo for hover
'button_secondary': '#475569', # Secondary button
'button_secondary_hover': '#64748b', # Secondary button hover
'success': '#10b981', # Modern green
'success_hover': '#059669', # Darker green for hover
'error': '#ef4444', # Modern red
'error_hover': '#dc2626', # Darker red for hover
'warning': '#f59e0b', # Modern amber
'warning_hover': '#d97706', # Darker amber for hover
'border': '#334155', # Border color
'border_light': '#475569', # Light border
'shadow': '#00000020', # Shadow color
}
# Configure modern window styling after colors are defined
# Removed problematic option_add calls for better compatibility
# Create named fonts to avoid parsing issues
try:
self.font_title = tkfont.Font(family="Arial", size=24, weight="bold")
self.font_subtitle = tkfont.Font(family="Arial", size=14)
self.font_button = tkfont.Font(family="Arial", size=12)
self.font_button_large = tkfont.Font(family="Arial", size=20, weight="bold")
self.font_status = tkfont.Font(family="Arial", size=14, weight="bold")
except Exception:
# Fallback if font creation fails
self.font_title = ("Arial", 24)
self.font_subtitle = ("Arial", 14)
self.font_button = ("Arial", 12)
self.font_button_large = ("Arial", 20)
self.font_status = ("Arial", 14)
# Force Tk default named fonts to a safe family
try:
for name in ["TkDefaultFont", "TkTextFont", "TkHeadingFont", "TkMenuFont", "TkCaptionFont", "TkSmallCaptionFont", "TkTooltipFont", "TkIconFont"]:
try:
tkfont.nametofont(name).configure(family="Arial")
except Exception:
pass
except Exception:
pass
# Settings file path - handle both script and executable modes
if getattr(sys, 'frozen', False):
# Running as executable (PyInstaller)
application_path = os.path.dirname(sys.executable)
else:
# Running as script
application_path = os.path.dirname(os.path.abspath(__file__))
self.settings_file = os.path.join(application_path, 'melly-settings.json')
# Load settings
self.settings = self.load_settings()
# Enable drag and drop if available
if DND_AVAILABLE:
self.enable_drag_drop()
# Add method for creating modern rounded buttons
self.create_modern_button = self.create_modern_button
self.create_modern_frame = self.create_modern_frame
# Store icon path for use in other windows
self.icon_path = icon_path if 'icon_path' in locals() and os.path.exists(icon_path) else None
self.setup_ui()
# Set up Steam directories on first launch
self.setup_steam_directories()
# Initialize download queue
self.download_queue = []
self.completed_downloads = []
self.failed_downloads = []
self.current_download = None
self.download_manager_frame = None
# Track queued games for persistent state
self.queued_games = set() # Set of app_ids that are queued or downloading
# Multi-threaded download management
self.active_downloads = {} # Dict of {app_id: download_item} for currently downloading items
self.download_threads = {} # Dict of {app_id: thread} for active download threads
self.current_batch_completed = []
self.current_batch_failed = []
# Persistent HTTP client for downloads (keeps connections warm, supports HTTP/2)
try:
self.http_client = httpx.Client(
http2=True,
follow_redirects=True,
headers={"User-Agent": "Mozilla/5.0"}
)
except Exception:
self.http_client = None
# Apply minimize behavior based on settings
self.apply_minimize_setting()
# Check for updates 3 seconds after startup (non-blocking) - only if not disabled
if not self.settings.get('dont_prompt_update', False):
self.root.after(3000, self.check_for_updates)
# Force refresh icon after window is shown (for better compatibility)
if getattr(sys, 'frozen', False):
self.root.after(100, self.force_refresh_icon)
# Also try to refresh after a longer delay
self.root.after(1000, self.force_refresh_icon)
def set_window_icon(self, window):
"""Set the icon for a window (main window or popup)"""
if self.icon_path and os.path.exists(self.icon_path):
try:
# For executables, try Windows API first
if getattr(sys, 'frozen', False):
try:
import ctypes
hwnd = window.winfo_id()
# Load the icon from the executable itself
icon_handle = ctypes.windll.shell32.ExtractIconW(0, sys.executable, 0)
if icon_handle:
# Send WM_SETICON message to set the icon
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 0, icon_handle) # WM_SETICON
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 1, icon_handle) # WM_SETICON for small icon
print(f"Icon set for window {window} using Windows API")
else:
# Fallback to iconbitmap
window.iconbitmap(self.icon_path)
print(f"Icon set for window {window} using iconbitmap")
except Exception as e:
print(f"Windows API icon setting failed for {window}: {e}")
# Fallback to iconbitmap
window.iconbitmap(self.icon_path)
print(f"Icon set for window {window} using fallback method")
else:
# Running as script, use normal method
window.iconbitmap(self.icon_path)
print(f"Icon set for window {window} from script")
except Exception as e:
print(f"Could not set icon for window {window}: {e}")
else:
print(f"No icon available to set for window: {window}")
def force_refresh_icon(self):
"""Force refresh the window icon using multiple methods"""
if not getattr(sys, 'frozen', False):
return
try:
import ctypes
print("Attempting to force refresh window icon...")
# Method 1: Try to set icon using Windows API icon extraction
hwnd = self.root.winfo_id()
icon_handle = ctypes.windll.shell32.ExtractIconW(0, sys.executable, 0)
if icon_handle:
# Send WM_SETICON message to set the icon
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 0, icon_handle) # WM_SETICON
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 1, icon_handle) # WM_SETICON for small icon
print("Window icon refreshed using Windows API icon extraction")
return
else:
print("Could not extract icon from executable")
# Method 2: Try to set icon using executable path
try:
self.root.iconbitmap(default=sys.executable)
print("Window icon refreshed using executable path")
return
except Exception as e:
print(f"Executable path icon setting failed: {e}")
# Method 3: Try to set icon using iconbitmap with executable
try:
self.root.iconbitmap(sys.executable)
print("Window icon refreshed using iconbitmap with executable")
return
except Exception as e:
print(f"iconbitmap with executable failed: {e}")
# Method 4: Try to use the icon.ico file if it exists
if self.icon_path and os.path.exists(self.icon_path):
try:
self.root.iconbitmap(self.icon_path)
print("Window icon refreshed using icon.ico file")
return
except Exception as e:
print(f"icon.ico file icon setting failed: {e}")
# Method 5: Try using wm_iconbitmap (alternative method)
try:
self.root.wm_iconbitmap(sys.executable)
print("Window icon refreshed using wm_iconbitmap")
return
except Exception as e:
print(f"wm_iconbitmap failed: {e}")
# Method 6: Try to set icon using Windows registry method
try:
self.set_icon_via_registry()
print("Window icon refreshed using registry method")
return
except Exception as e:
print(f"Registry method failed: {e}")
except Exception as e:
print(f"Force refresh icon failed: {e}")
def set_executable_icon(self):
"""Set the proper icon for executables after window is shown"""
try:
import ctypes
print("Setting executable icon after window creation...")
print(f"Executable path: {sys.executable}")
# Set the taskbar icon ID
myappid = 'luatools.app.1.0'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
print("Taskbar icon ID set")
# Get the window handle
hwnd = self.root.winfo_id()
print(f"Window handle: {hwnd}")
# Try to extract icon from executable
icon_handle = ctypes.windll.shell32.ExtractIconW(0, sys.executable, 0)
if icon_handle:
print(f"Icon handle extracted: {icon_handle}")
# Send WM_SETICON message to set the icon
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 0, icon_handle) # WM_SETICON
ctypes.windll.user32.SendMessageW(hwnd, 0x0080, 1, icon_handle) # WM_SETICON for small icon
print("Executable icon set successfully using Windows API")
# Also try to set the icon using iconbitmap with the executable
try:
self.root.iconbitmap(sys.executable)
print("Executable icon also set using iconbitmap")
except Exception as e:
print(f"iconbitmap with executable failed: {e}")
else:
print("WARNING: Could not extract icon from executable - this means PyInstaller didn't embed the icon properly")
print("This usually means the --icon flag in PyInstaller didn't work or the icon file is corrupted")
# Try alternative methods
try:
self.root.iconbitmap(sys.executable)
print("Executable icon set using iconbitmap with executable path")
except Exception as e:
print(f"iconbitmap with executable path failed: {e}")
# Try with the icon.ico file
if self.icon_path and os.path.exists(self.icon_path):
try:
self.root.iconbitmap(self.icon_path)
print("Executable icon set using icon.ico file")
except Exception as e2:
print(f"icon.ico file failed: {e2}")
except Exception as e:
print(f"set_executable_icon failed: {e}")
def set_icon_via_registry(self):
"""Try to set icon using Windows registry method"""
try:
import winreg
# Try to get the icon from the executable's registry entry
key_path = r"SOFTWARE\Classes\Applications\LuaTools.exe\DefaultIcon"
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:
icon_path, _ = winreg.QueryValueEx(key, "")
if os.path.exists(icon_path):
self.root.iconbitmap(icon_path)
return True
except:
pass
# Try alternative registry path
key_path = r"SOFTWARE\Classes\Applications\LuaTools.exe\shell\open\command"
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:
exe_path, _ = winreg.QueryValueEx(key, "")
if os.path.exists(exe_path):
self.root.iconbitmap(exe_path)
return True
except:
pass
except Exception as e:
print(f"Registry icon method failed: {e}")
return False
def safe_after_configure(self, widget, attribute, value, delay, original_value):
"""
Safely schedule a widget configuration change with conflict prevention.
This method prevents the issue where rapid clicking on copy buttons
can cause the visual feedback (like "Copied!" text) to get stuck
because multiple timers are scheduled simultaneously.
Args:
widget: The Tkinter widget to configure
attribute: The attribute to temporarily change (e.g., 'text', 'bg')
value: The temporary value to set
delay: Delay in milliseconds before restoring original value
original_value: The value to restore after the delay
"""
# Cancel any existing timer for this widget and attribute
timer_key = f'_timer_{attribute}'
if hasattr(widget, timer_key):
self.root.after_cancel(getattr(widget, timer_key))
# Schedule the configuration change
timer_id = self.root.after(delay, lambda: widget.configure(**{attribute: original_value}))
setattr(widget, timer_key, timer_id)
def manage_copy_timer(self, widget_id, timer_id):
"""
Manage copy timers globally to prevent conflicts.
Args:
widget_id: Unique identifier for the widget
timer_id: The timer ID to store
"""
# Cancel any existing timer for this widget
if widget_id in self.copy_timers:
try:
self.root.after_cancel(self.copy_timers[widget_id])
print(f"Cancelled previous timer {self.copy_timers[widget_id]} for widget {widget_id}")
except Exception as e:
print(f"Error cancelling previous timer: {e}")
# Store the new timer
self.copy_timers[widget_id] = timer_id
print(f"Stored timer {timer_id} for widget {widget_id}")
def clear_copy_timer(self, widget_id):
"""
Clear a copy timer for a specific widget.
Args:
widget_id: Unique identifier for the widget
"""
if widget_id in self.copy_timers:
try:
self.root.after_cancel(self.copy_timers[widget_id])
del self.copy_timers[widget_id]
print(f"Cleared timer for widget {widget_id}")
except Exception as e:
print(f"Error clearing timer: {e}")
def clear_all_copy_timers(self):
"""
Clear all copy timers (useful for debugging or cleanup).
"""
print(f"Clearing all copy timers: {len(self.copy_timers)} active")
for widget_id, timer_id in list(self.copy_timers.items()):
try:
self.root.after_cancel(timer_id)
print(f"Cancelled timer {timer_id} for widget {widget_id}")
except Exception as e:
print(f"Error cancelling timer {timer_id}: {e}")
self.copy_timers.clear()
print("All copy timers cleared")
def debug_copy_timers(self):
"""
Debug method to show all active copy timers.
"""
print(f"Active copy timers: {len(self.copy_timers)}")
for widget_id, timer_id in self.copy_timers.items():
print(f" Widget {widget_id}: Timer {timer_id}")
def force_restore_all_copy_text(self):
"""
Force restore all copy text that might be stuck.
This is useful for debugging when text gets stuck.
"""
print("Force restoring all copy text...")
# Clear all timers first
self.clear_all_copy_timers()
# You can add specific widget restoration logic here if needed
print("All copy text should be restored")
def handle_copy_app_id(self, label_widget, app_id):
"""
Handle copying app ID to clipboard with proper timer management.
Args:
label_widget: The label widget to update
app_id: The app ID to copy
"""
# Create unique widget ID for timer management
widget_id = f"app_id_{app_id}"
print(f"Handling copy for App ID {app_id}, widget {widget_id}")
# Copy the app ID to clipboard
self.root.clipboard_clear()
self.root.clipboard_append(str(app_id))
print(f"Copied App ID {app_id} to clipboard")
# Store original text and set appropriate "Copied!" text
try:
# Get the original text (not the current "Copied!" text)
if not hasattr(label_widget, '_original_text'):
original_text = label_widget.cget('text')
label_widget._original_text = original_text
else:
original_text = label_widget._original_text
# Determine if this is from download manager or game manager
if "App ID:" in original_text:
copied_text = "Copied AppID!"
else:
copied_text = "Copied!"
label_widget.configure(text=copied_text)
print(f"Set label text to '{copied_text}' for {app_id}")
except Exception as e:
print(f"Error setting label text: {e}")
return
# Schedule text restoration using global timer management
def restore_text():
try:
# Always restore to the original text, regardless of current state
if hasattr(label_widget, '_original_text'):
label_widget.configure(text=label_widget._original_text)
print(f"Restored text for {app_id} to original")
else:
# Fallback: try to restore to what we think is original
label_widget.configure(text=original_text)
print(f"Restored text for {app_id} using fallback")
# Clear the timer from global management
self.clear_copy_timer(widget_id)
except Exception as e:
print(f"Error restoring text: {e}")
timer_id = self.root.after(1000, restore_text)
self.manage_copy_timer(widget_id, timer_id)
print(f"Scheduled timer {timer_id} for widget {widget_id}")
def handle_copy_file_name(self, label_widget, file_name):
"""
Handle copying file name to clipboard with proper timer management.
Args:
label_widget: The label widget to update
file_name: The file name to copy
"""
# Create unique widget ID for timer management
widget_id = f"file_name_{hash(file_name)}"
print(f"Handling copy for file name {file_name}, widget {widget_id}")
# Copy the file name to clipboard
self.root.clipboard_clear()
self.root.clipboard_append(file_name)
print(f"Copied file name {file_name} to clipboard")
# Store original background and set visual feedback
try:
original_bg = label_widget.cget('bg')
label_widget.configure(bg='#4a4a4a')
print(f"Set label background to feedback color for {file_name}")
except Exception as e:
print(f"Error setting label background: {e}")
return
# Schedule background restoration using global timer management
def restore_background():
try:
label_widget.configure(bg=original_bg)
print(f"Restored background for {file_name}")
# Clear the timer from global management
self.clear_copy_timer(widget_id)
except Exception as e:
print(f"Error restoring background: {e}")
timer_id = self.root.after(200, restore_background)
self.manage_copy_timer(widget_id, timer_id)
print(f"Scheduled timer {timer_id} for widget {widget_id}")
def force_restore_all_copy_text(self):
"""
Force restore all copy text that might be stuck.
This is useful for debugging when text gets stuck.
"""
print("Force restoring all copy text...")
# Clear all timers first
self.clear_all_copy_timers()
# You can add specific widget restoration logic here if needed
print("All copy text should be restored")
def force_restore_text_immediately(self, label_widget, app_id):
"""
Force restore text immediately for a specific widget.
This is useful for debugging when text gets stuck.
"""
try:
if hasattr(label_widget, '_original_text'):
label_widget.configure(text=label_widget._original_text)
print(f"Force restored text for {app_id}")
else:
print(f"No original text stored for {app_id}")
except Exception as e:
print(f"Error force restoring text: {e}")
def center_window(self):
"""Center the window on the screen"""
self.root.update_idletasks()
width = self.root.winfo_width()
height = self.root.winfo_height()
x = (self.root.winfo_screenwidth() // 2) - (width // 2)
y = (self.root.winfo_screenheight() // 2) - (height // 2)
self.root.geometry(f"{width}x{height}+{x}+{y}")
def center_popup(self, window):
"""Center a popup window on the screen"""
window.update_idletasks()
width = window.winfo_width()
height = window.winfo_height()
x = (window.winfo_screenwidth() // 2) - (width // 2)
y = (window.winfo_screenheight() // 2) - (height // 2)
window.geometry(f"{width}x{height}+{x}+{y}")
def enable_drag_drop(self):
"""Enable drag and drop for the main window"""
if not DND_AVAILABLE:
return
try:
# Get window handle
hwnd = self.root.winfo_id()
# Enable file drop style
ex_style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE)
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex_style | WS_EX_ACCEPTFILES)
# Store original window procedure
self.original_wndproc = GetWindowLongPtrW(hwnd, GWLP_WNDPROC)
# Set up window procedure for drag and drop
def wndproc(hwnd, msg, wparam, lparam):
if msg == WM_DROPFILES:
self.handle_drop(wparam)
return 0
# Use a safer way to call the original window procedure
try:
return user32.CallWindowProcW(ctypes.cast(self.original_wndproc, ctypes.c_void_p), hwnd, msg, wparam, lparam)
except:
# Fallback: just return 0 if the call fails
return 0
# Create window procedure wrapper
self.wndproc_wrapper = ctypes.WINFUNCTYPE(ctypes.c_longlong, HWND, UINT, WPARAM, LPARAM)(wndproc)
# Set new window procedure
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, ctypes.cast(self.wndproc_wrapper, ctypes.c_void_p).value)
except Exception as e:
print(f"Failed to enable drag and drop: {e}")
def handle_drop(self, wparam):
"""Handle file drop event"""
try:
# Get number of files dropped
file_count = DragQueryFileW(wparam, 0xFFFFFFFF, None, 0)
dropped_files = []
invalid_files = []
print(f"Drag and drop: {file_count} files detected")
for i in range(file_count):
# Get file path length
path_len = DragQueryFileW(wparam, i, None, 0)
# Create buffer for file path
buffer = ctypes.create_unicode_buffer(path_len + 1)
# Get file path
DragQueryFileW(wparam, i, buffer, path_len + 1)
file_path = buffer.value
print(f"File {i+1}: {file_path}")
# Validate file type
if self.is_valid_file_type(file_path):
print(f"✓ Valid file: {file_path}")
dropped_files.append(file_path)
else:
print(f"✗ Invalid file: {file_path}")
invalid_files.append(os.path.basename(file_path))
# Finish drag operation
DragFinish(wparam)
print(f"Valid files: {len(dropped_files)}, Invalid files: {len(invalid_files)}")
# Show warning for invalid files
if invalid_files:
invalid_msg = f"The following files were ignored (unsupported format):\n\n"
for filename in invalid_files:
invalid_msg += f"• {filename}\n"
invalid_msg += f"\nSupported formats: .lua, .zip, .rar, .7z"
messagebox.showwarning("Unsupported Files", invalid_msg)
# Process valid files only if we have any
if dropped_files:
print(f"Processing {len(dropped_files)} valid files...")
self.process_files(dropped_files)
elif invalid_files:
# We had invalid files but no valid ones
print("No valid files to process")
messagebox.showwarning("No Files", "No files were dropped.")
except Exception as e:
print(f"Error handling drop: {e}")
import traceback
traceback.print_exc()
DragFinish(wparam)
def load_settings(self):
"""Load settings from JSON file"""
default_settings = {
'auto_restart_steam': False,
'api_timeout': 10,
'max_download_threads': 3, # New setting for concurrent downloads
'theme': 'steam_dark',
'minimize_to_tray': False,
# Legacy single API settings (for backward compatibility)
'manifest_download_url': '',
'manifest_good_status_code': 200,
'manifest_unavailable_status_code': 404,
# New modular API system
'api_list': [], # Start with no default APIs
'api_request_timeout': 15, # New timeout setting for API requests
'backup_downloads': False,
'show_only_installed': False,
'sort_by': 'smart sorting',
'search_results_limit': 5,
'installed_games_shown_limit': 25,
'show_file_names': False,
'dont_start_downloads_until_button_pressed': False,
'dont_prompt_update': False # New setting for update prompt
}
try:
print(f"Loading settings from: {self.settings_file}")
if os.path.exists(self.settings_file):
print("Settings file exists, loading...")
with open(self.settings_file, 'r', encoding='utf-8') as f:
content = f.read()
print(f"Settings file content length: {len(content)} characters")
loaded_settings = json.loads(content)
print(f"Settings loaded successfully, keys: {list(loaded_settings.keys())}")
# Migration: Convert legacy single API settings to new multi-API format
if 'api_list' not in loaded_settings and 'manifest_download_url' in loaded_settings:
legacy_url = loaded_settings.get('manifest_download_url', '')
legacy_success = loaded_settings.get('manifest_good_status_code', 200)
legacy_unavailable = loaded_settings.get('manifest_unavailable_status_code', 404)
if legacy_url.strip():
# Create API list from legacy settings
loaded_settings['api_list'] = [
{
'name': 'Migrated API',
'url': legacy_url,
'success_code': legacy_success,
'unavailable_code': legacy_unavailable,
'enabled': True
}
]
else:
# Start with empty API list (no default APIs)
loaded_settings['api_list'] = []
# Merge with defaults to ensure all settings exist
for key, value in default_settings.items():
if key not in loaded_settings:
loaded_settings[key] = value
print(f"Final settings after merge: {list(loaded_settings.keys())}")
return loaded_settings
else:
print("Settings file does not exist, creating default...")
# Create default settings file
self.save_settings(default_settings)
return default_settings
except Exception as e:
print(f"Error loading settings: {e}")
import traceback
traceback.print_exc()
return default_settings
def save_settings(self, settings=None):
"""Save settings to JSON file"""
if settings is None:
settings = self.settings
try:
with open(self.settings_file, 'w', encoding='utf-8') as f:
json.dump(settings, f, indent=4, ensure_ascii=False)
except Exception as e:
print(f"Error saving settings: {e}")
def update_setting(self, key, value):
"""Update a single setting (does not save automatically)"""
self.settings[key] = value
def create_checkbox_setting(self, parent, title, setting_key, description):
"""Create a checkbox setting widget"""
# Container frame
setting_frame = tk.Frame(parent, bg=self.colors['bg'])
setting_frame.pack(fill=tk.X, pady=10, padx=20)
# Title and checkbox
title_frame = tk.Frame(setting_frame, bg=self.colors['bg'])
title_frame.pack(fill=tk.X)
# Checkbox variable
var = tk.BooleanVar(value=self.settings.get(setting_key, False))
# Store reference to variable
if hasattr(self, 'setting_vars'):
self.setting_vars[setting_key] = var
# Checkbox
checkbox = tk.Checkbutton(
title_frame,
text=title,
variable=var,
font=('Segoe UI', 12, 'bold'),
fg=self.colors['text'],
bg=self.colors['bg'],
selectcolor=self.colors['secondary_bg'],
activebackground=self.colors['bg'],
activeforeground=self.colors['text']
)
checkbox.pack(side=tk.LEFT)
# Description
desc_label = tk.Label(
setting_frame,
text=description,
font=('Segoe UI', 10),
fg=self.colors['text'],
bg=self.colors['bg'],
wraplength=500,
justify=tk.LEFT
)
desc_label.pack(anchor=tk.W, pady=(5, 0))
# Separator
separator = tk.Frame(setting_frame, height=1, bg=self.colors['secondary_bg'])
separator.pack(fill=tk.X, pady=(10, 0))
def create_spinbox_setting(self, parent, title, setting_key, min_val, max_val, increment, description):
"""Create a spinbox setting widget"""
# Container frame
setting_frame = tk.Frame(parent, bg=self.colors['bg'])
setting_frame.pack(fill=tk.X, pady=10, padx=20)
# Title and spinbox
title_frame = tk.Frame(setting_frame, bg=self.colors['bg'])
title_frame.pack(fill=tk.X)
# Title label
title_label = tk.Label(
title_frame,
text=title,
font=('Segoe UI', 12, 'bold'),
fg=self.colors['text'],
bg=self.colors['bg']
)
title_label.pack(side=tk.LEFT)
# Spinbox variable
var = tk.IntVar(value=self.settings.get(setting_key, 10))
# Store reference to variable
if hasattr(self, 'setting_vars'):
self.setting_vars[setting_key] = var
# Spinbox
spinbox = tk.Spinbox(
title_frame,
from_=min_val,
to=max_val,
increment=increment,
textvariable=var,
font=('Segoe UI', 10),
bg=self.colors['secondary_bg'],
fg=self.colors['text'],
insertbackground=self.colors['text'],
relief=tk.FLAT,
width=10
)
spinbox.pack(side=tk.RIGHT)
# Validation function to only allow numbers
def validate_numeric_input(P):
if P == "": # Allow empty string
return True
if P.isdigit(): # Allow only digits
return True
return False
# Register validation command
vcmd = (self.root.register(validate_numeric_input), '%P')
spinbox.config(validate='key', validatecommand=vcmd)
# Bind events to update the variable (but don't save yet)
def update_var_on_key_release(e):
try:
value = var.get()
if value == "": # If empty, reset to default
var.set(self.settings.get(setting_key, 10))
except:
# If conversion fails, reset to default
var.set(self.settings.get(setting_key, 10))
def update_var_on_focus_out(e):
try:
value = var.get()
if value == "": # If empty, reset to default
var.set(self.settings.get(setting_key, 10))
except:
# If conversion fails, reset to default
var.set(self.settings.get(setting_key, 10))
spinbox.bind('<KeyRelease>', update_var_on_key_release)
spinbox.bind('<FocusOut>', update_var_on_focus_out)
# Description
desc_label = tk.Label(
setting_frame,
text=description,
font=('Segoe UI', 10),
fg=self.colors['text'],
bg=self.colors['bg'],
wraplength=500,
justify=tk.LEFT
)
desc_label.pack(anchor=tk.W, pady=(5, 0))
# Separator
separator = tk.Frame(setting_frame, height=1, bg=self.colors['secondary_bg'])
separator.pack(fill=tk.X, pady=(10, 0))
def create_text_setting(self, parent, title, setting_key, description, default_value=""):
"""Create a text input setting widget"""
# Container frame
setting_frame = tk.Frame(parent, bg=self.colors['bg'])
setting_frame.pack(fill=tk.X, pady=10, padx=20)
# Title and text input
title_frame = tk.Frame(setting_frame, bg=self.colors['bg'])
title_frame.pack(fill=tk.X)