-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwinecharm.py
executable file
·10988 lines (9050 loc) · 457 KB
/
winecharm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import gi
import threading
import subprocess
import os
import shutil
import shlex
import hashlib
import signal
import re
import yaml
from pathlib import Path
import sys
import socket
import time
import glob
import fnmatch
import psutil
import inspect
import argparse
import uuid
import urllib.request
import json
from datetime import datetime, timedelta
gi.require_version('Gtk', '4.0')
gi.require_version('Gdk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import GLib, Gio, Gtk, Gdk, Adw, GdkPixbuf, Pango # Add Pango here
class WineCharmApp(Gtk.Application):
def __init__(self):
self.count = 0
self.log_file_path = os.path.expanduser('~/logfile.log')
creation_date_and_time = datetime.now()
log_message = f"=>{creation_date_and_time}\n" + "-"*50 + "\n"
#with open(self.log_file_path, 'a') as log_file:
# log_file.write(log_message)
self.print_method_name()
super().__init__(application_id='io.github.fastrizwaan.WineCharm', flags=Gio.ApplicationFlags.HANDLES_OPEN)
self.window = None # Initialize window as None
Adw.init()
# Move the global variables to instance attributes
self.debug = False
self.version = "0.97"
# Paths and directories
self.winecharmdir = Path(os.path.expanduser("~/.var/app/io.github.fastrizwaan.WineCharm/data/winecharm")).resolve()
self.prefixes_dir = self.winecharmdir / "Prefixes"
self.templates_dir = self.winecharmdir / "Templates"
self.runners_dir = self.winecharmdir / "Runners"
self.default_template_win64 = self.templates_dir / "WineCharm-win64"
self.default_template_win32 = self.templates_dir / "WineCharm-win32"
self.single_prefix_dir_win64 = self.prefixes_dir / "WineCharm-Single_win64"
self.single_prefix_dir_win32 = self.prefixes_dir / "WineCharm-Single_win32"
self.applicationsdir = Path(os.path.expanduser("~/.local/share/applications")).resolve()
self.tempdir = Path(os.path.expanduser("~/.var/app/io.github.fastrizwaan.WineCharm/data/tmp")).resolve()
self.iconsdir = Path(os.path.expanduser("~/.local/share/icons")).resolve()
self.do_not_kill = "bin/winecharm"
self.SOCKET_FILE = self.winecharmdir / "winecharm_socket"
self.settings_file = self.winecharmdir / "Settings.yaml"
# Variables that need to be dynamically updated
self.runner = "" # which wine
self.wine_version = "" # runner --version
self.template = "" # default: WineCharm-win64, if not found in Settings.yaml
self.arch = "win64" # default: win
self.connect("activate", self.on_activate)
self.connect("startup", self.on_startup)
self.connect("open", self.on_open)
# Initialize other attributes here
self.new_scripts = set() # Initialize new_scripts as an empty set
# Initialize other attributes that might be missing
self.selected_script = None
self.selected_script_name = None
self.selected_row = None
self.initializing_template = False
self.running_processes = {}
self.script_buttons = {}
self.play_stop_handlers = {}
self.options_listbox = None
self.launch_button = None
self.search_active = False
self.command_line_file = None
self.monitoring_active = True # Flag to control monitoring
self.scripts = [] # Or use a list of script objects if applicable
self.count = 0
self.focus_event_timer_id = None
self.create_required_directories() # Create Required Directories
self.icon_view = False
self.script_list = {}
self.import_steps_ui = {}
self.current_script = None
self.current_script_key = None
self.stop_processing = False
self.processing_thread = None
self.current_backup_path = None
self.current_process = None
self.runner_to_use = None
self.process_lock = threading.Lock()
self.called_from_settings = False
self.open_button_handler_id = None
self.lnk_processed_success_status = False
# Register the SIGINT signal handler
signal.signal(signal.SIGINT, self.handle_sigint)
self.script_buttons = {}
self.current_clicked_row = None # Initialize current clicked row
self.hamburger_actions = [
("🛠️ Settings...", self.show_options_for_settings),
("☠️ Kill all...", self.on_kill_all_clicked),
("🍾 Restore...", self.restore_from_backup),
("📥 Import Wine Directory", self.on_import_wine_directory_clicked),
("❓ Help...", self.on_help_clicked),
("📖 About...", self.on_about_clicked),
("🚪 Quit...", self.quit_app)
]
self.css_provider = Gtk.CssProvider()
self.css_provider.load_from_data(b"""
.menu-button.flat:hover {
background-color: @headerbar_bg_color;
}
.button-box button {
min-width: 80px;
min-height: 36px;
}
.highlighted {
background-color: rgba(127, 127, 127, 0.15);
}
.red {
background-color: rgba(228, 0, 0, 0.25);
font-weight: bold;
}
.blue {
background-color: rgba(53, 132, 228, 0.25);
font-weight: bold;
}
.normal-font { /* Add the CSS rule for the normal-font class */
font-weight: normal;
}
progressbar.header-progress {
min-height: 4px;
background: none;
border: none;
padding: 0;
}
progressbar.header-progress trough {
min-height: 4px;
border: none;
}
progressbar.header-progress progress {
min-height: 4px;
}
""")
Gtk.StyleContext.add_provider_for_display(
Gdk.Display.get_default(),
self.css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
self.back_button = Gtk.Button.new_from_icon_name("go-previous-symbolic")
self.back_button.connect("clicked", self.on_back_button_clicked)
self.open_button_handler_id = None
# Runner cache file
self.runner_cache_file = self.winecharmdir / "runner_cache.yaml"
self.runner_data = None # Will hold the runner data after fetching
self.settings = self.load_settings() # Add this line
# Set keyboard accelerators
self.set_accels_for_action("win.search", ["<Ctrl>f"])
self.set_accels_for_action("win.open", ["<Ctrl>o"])
self.set_accels_for_action("win.on_kill_all_clicked", ["<Ctrl>k"])
self.set_accels_for_action("win.toggle_view", ["<Ctrl>v"])
self.set_accels_for_action("win.back", ["<Ctrl>BackSpace"])
print("__init__ end" + " - "*50)
self.count = 0
def print_method_name(self):
self.count = self.count + 1
current_frame = sys._getframe(1) # Get the caller's frame
method_name = current_frame.f_code.co_name
print(f"=>{self.count} {method_name}")
# uncomment below to write to log file
# log_message = f"=>{self.count} {method_name}\n"
# with open(self.log_file_path, 'a') as log_file:
# log_file.write(log_message)
def ensure_directory_exists(self, directory):
self.print_method_name()
directory = Path(directory) # Ensure it's a Path object
if not directory.exists():
try:
directory.mkdir(parents=True, exist_ok=True)
print(f"Created directory: {directory}")
except Exception as e:
print(f"Error creating directory {directory}: {e}")
else:
pass
#print(f"Directory already exists: {directory}")
def create_required_directories(self):
self.print_method_name()
winecharm_data_dir = Path(os.path.expanduser("~/.var/app/io.github.fastrizwaan.WineCharm/data")).resolve()
self.tempdir = winecharm_data_dir / "tmp"
self.winecharmdir = winecharm_data_dir / "winecharm"
self.prefixes_dir = self.winecharmdir / "Prefixes"
self.templates_dir = self.winecharmdir / "Templates"
self.runners_dir = self.winecharmdir / "Runners"
directories = [self.winecharmdir, self.prefixes_dir, self.templates_dir, self.runners_dir, self.tempdir]
for directory in directories:
self.ensure_directory_exists(directory)
def on_settings_clicked(self, action=None, param=None):
self.print_method_name()
print("Settings action triggered")
# You can add code here to open a settings window or dialog.
def find_matching_processes(self, exe_name_pattern):
self.print_method_name()
matching_processes = []
for proc in psutil.process_iter(['pid', 'name', 'exe', 'cmdline']):
try:
# Retrieve the process name, executable path, or command line arguments
proc_name = proc.info['name']
proc_exe = proc.info['exe']
proc_cmdline = proc.info['cmdline']
# Match the executable name pattern
if proc_exe and exe_name_pattern in proc_exe:
matching_processes.append(proc)
elif proc_name and exe_name_pattern in proc_name:
matching_processes.append(proc)
elif proc_cmdline and any(exe_name_pattern in arg for arg in proc_cmdline):
matching_processes.append(proc)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# Ignore processes that are no longer available or cannot be accessed
pass
return matching_processes
def on_kill_all_clicked(self, action=None, param=None):
self.print_method_name()
try:
winecharm_pids = []
wine_exe_pids = []
exe_name_pattern = ".exe" # Pattern for executables
# Find all processes that match the .exe pattern using find_matching_processes
matching_processes = self.find_matching_processes(exe_name_pattern)
for proc in matching_processes:
try:
pid = proc.info['pid']
proc_cmdline = proc.info['cmdline']
# Build command string for matching (similar to pgrep)
command = " ".join(proc_cmdline) if proc_cmdline else proc.info['name']
# Check if this is a WineCharm process (using self.do_not_kill pattern)
if self.do_not_kill in command:
winecharm_pids.append(pid)
# Check if this is a .exe process and exclude PID 1 (system process)
elif pid != 1:
wine_exe_pids.append(pid)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# Ignore processes that are no longer available or cannot be accessed
pass
# Reverse to kill child processes first (if applicable)
wine_exe_pids.reverse()
# Kill the Wine exe processes, excluding WineCharm PIDs
for pid in wine_exe_pids:
if pid not in winecharm_pids:
try:
os.kill(pid, signal.SIGKILL)
print(f"Terminated process with PID: {pid}")
except ProcessLookupError:
print(f"Process with PID {pid} not found")
except PermissionError:
print(f"Permission denied to kill PID: {pid}")
except Exception as e:
print(f"Error retrieving process list: {e}")
# Optionally, clear the running processes dictionary
self.running_processes.clear()
GLib.timeout_add_seconds(0.5, self.load_script_list)
def on_help_clicked(self, action=None, param=None):
self.print_method_name()
print("Help action triggered")
# You can add code here to show a help dialog or window.
def on_about_clicked(self, action=None, param=None):
self.print_method_name()
about_dialog = Adw.AboutWindow(
transient_for=self.window,
application_name="WineCharm",
application_icon="io.github.fastrizwaan.WineCharm",
version=f"{self.version}",
copyright="GNU General Public License (GPLv3+)",
comments="A Charming Wine GUI Application",
website="https://github.com/fastrizwaan/WineCharm",
developer_name="Mohammed Asif Ali Rizvan",
license_type=Gtk.License.GPL_3_0,
issue_url="https://github.com/fastrizwaan/WineCharm/issues"
)
about_dialog.present()
def quit_app(self, action=None, param=None):
self.print_method_name()
self.quit()
def get_default_icon_path(self):
#self.print_method_name()
xdg_data_dirs = os.getenv("XDG_DATA_DIRS", "").split(":")
icon_relative_path = "icons/hicolor/128x128/apps/org.winehq.Wine.png"
for data_dir in xdg_data_dirs:
icon_path = Path(data_dir) / icon_relative_path
if icon_path.exists():
return icon_path
# Fallback icon path in case none of the paths in XDG_DATA_DIRS contain the icon
return Path("/app/share/icons/hicolor/128x128/apps/org.winehq.Wine.png")
def on_startup(self, app):
self.create_main_window()
# Clear or initialize the script list
self.set_dynamic_variables()
self.script_list = {}
self.load_script_list()
self.create_script_list()
if not self.template:
self.template = getattr(self, f'default_template_{self.arch}')
self.template = self.expand_and_resolve_path(self.template)
missing_programs = self.check_required_programs()
if missing_programs:
self.show_missing_programs_dialog(missing_programs)
else:
if not self.template.exists():
self.initialize_template(self.template, self.on_template_initialized)
else:
self.set_dynamic_variables()
# Process the command-line file if the template already exists
if self.command_line_file:
print("Template exists. Processing command-line file after UI initialization.")
self.process_cli_file_later(self.command_line_file)
# After loading scripts and building the UI, check for running processes
self.set_dynamic_variables()
self.check_running_processes_on_startup()
# Start fetching runner URLs asynchronously
threading.Thread(target=self.maybe_fetch_runner_urls).start()
def remove_symlinks_and_create_directories(self, wineprefix):
"""
Remove all symbolic link files in the specified directory (drive_c/users/{user}) and
create normal directories in their place.
Args:
wineprefix: The path to the Wine prefix where symbolic links will be removed.
"""
userhome = os.getenv("USER") or os.getenv("USERNAME")
if not userhome:
print("Error: Unable to determine the current user from environment.")
return
user_dir = Path(wineprefix) / "drive_c" / "users"
print(f"Removing symlinks from: {user_dir}")
# Iterate through all symbolic links in the user's directory
for item in user_dir.rglob("*"):
if item.is_symlink():
try:
# Remove the symlink and create a directory in its place
item.unlink()
item.mkdir(parents=True, exist_ok=True)
print(f"Replaced symlink with directory: {item}")
except Exception as e:
print(f"Error processing {item}: {e}")
def initialize_template(self, template_dir, callback, arch='win64'):
"""
Modified template initialization with architecture support
"""
template_dir = Path(template_dir) if not isinstance(template_dir, Path) else template_dir
self.create_required_directories()
self.initializing_template = True
self.stop_processing = False
self.current_arch = arch # Store current architecture
# Disabled Cancel/Interruption
## Disconnect open button handler
#if self.open_button_handler_id is not None:
# self.open_button.disconnect(self.open_button_handler_id)
# self.open_button_handler_id = self.open_button.connect("clicked", self.on_cancel_template_init_clicked)
self.disconnect_open_button()
# Architecture-specific steps
steps = [
("Initializing wineprefix",
f"WINEARCH={arch} WINEPREFIX='{template_dir}' WINEDEBUG=-all wineboot -i"),
("Replace symbolic links with directories",
lambda: self.remove_symlinks_and_create_directories(template_dir)),
("Installing arial",
f"WINEPREFIX='{template_dir}' winetricks -q arial"),
# ("Installing tahoma",
# f"WINEPREFIX='{template_dir}' winetricks -q tahoma"),
# ("Installing times",
# f"WINEPREFIX='{template_dir}' winetricks -q times"),
# ("Installing courier",
# f"WINEPREFIX='{template_dir}' winetricks -q courier"),
# ("Installing webdings",
# f"WINEPREFIX='{template_dir}' winetricks -q webdings"),
("Installing openal",
f"WINEPREFIX='{template_dir}' winetricks -q openal"),
#("Installing vkd3d",
#f"WINEPREFIX='{template_dir}' winetricks -q vkd3d"),
#("Installing dxvk",
#f"WINEPREFIX='{template_dir}' winetricks -q dxvk"),
]
# Set total steps and initialize progress UI
self.total_steps = len(steps)
self.show_processing_spinner(f"Initializing {template_dir.name} Template...")
def initialize():
for index, (step_text, command) in enumerate(steps, 1):
if self.stop_processing:
GLib.idle_add(self.cleanup_cancelled_template_init, template_dir)
return
GLib.idle_add(self.show_initializing_step, step_text)
try:
if callable(command):
command()
else:
process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
while process.poll() is None:
if self.stop_processing:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
GLib.idle_add(self.cleanup_cancelled_template_init, template_dir)
return
time.sleep(0.1)
if process.returncode != 0:
raise subprocess.CalledProcessError(process.returncode, command)
GLib.idle_add(self.mark_step_as_done, step_text)
if hasattr(self, 'progress_bar'):
GLib.idle_add(lambda: self.progress_bar.set_fraction(index / self.total_steps))
except subprocess.CalledProcessError as e:
print(f"Error initializing template: {e}")
GLib.idle_add(self.cleanup_cancelled_template_init, template_dir)
return
if not self.stop_processing:
GLib.idle_add(lambda: self.on_template_initialized(arch))
GLib.idle_add(self.hide_processing_spinner)
self.disconnect_open_button()
GLib.idle_add(self.reset_ui_after_template_init)
threading.Thread(target=initialize).start()
def on_template_initialized(self, arch=None):
print(f"Template initialization complete for {arch if arch else 'default'} architecture.")
self.initializing_template = False
# Update architecture setting if we were initializing a specific arch
if arch:
self.arch = arch
# Set template path based on architecture
self.template = self.default_template_win32 if arch == 'win32' \
else self.default_template_win64
self.save_settings()
# Ensure the spinner is stopped after initialization
self.hide_processing_spinner()
#self.set_open_button_label("Open")
#self.set_open_button_icon_visible(True)
#self.search_button.set_sensitive(True)
#self.view_toggle_button.set_sensitive(True)
# Disabled Cancel/Interruption
#if self.open_button_handler_id is not None:
# self.open_button_handler_id = self.open_button.connect("clicked", self.on_open_button_clicked)
print("Template initialization completed and UI updated.")
self.show_initializing_step("Initialization Complete!")
self.mark_step_as_done("Initialization Complete!")
if self.command_line_file:
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(self.command_line_file)
file_extension = Path(self.command_line_file).suffix.lower()
if file_extension in ['.exe', '.msi']:
print("A"*100)
print(f"Processing file: {self.command_line_file} (Valid extension: {file_extension})")
print("Trying to process file inside on template initialized")
GLib.idle_add(self.show_processing_spinner, "Processing...")
self.process_cli_file(self.command_line_file)
elif file_extension in ['.wzt', '.bottle', '.prefix']:
print("B"*100)
self.restore_prefix_bottle_wzt_tar_zst(self.command_line_file)
else:
print("C"*100)
print(f"Invalid file type: def on_open: {file_extension}. Only .exe or .msi files are allowed.")
GLib.timeout_add_seconds(0.5, self.show_info_dialog, "Invalid File Type", "Only .exe and .msi files are supported.")
self.command_line_file = None
return False
# If not called from settings create script list else go to settings
if not self.called_from_settings:
self.reconnect_open_button()
GLib.timeout_add_seconds(0.5, self.create_script_list)
if self.called_from_settings:
GLib.idle_add(lambda: self.replace_open_button_with_settings())
self.show_options_for_settings()
self.set_dynamic_variables()
#self.disconnect_open_button()
##self.reconnect_open_button()
#self.show_options_for_settings()
#self.revert_open_button()
#self.called_from_settings = False
def process_cli_file_later(self, file_path):
#self.create_main_window()
print("D"*100)
if file_path:
file_extension = Path(file_path).suffix.lower()
if file_extension in ['.exe', '.msi']:
print("A"*100)
print(f"Processing file: {file_path} (Valid extension: {file_extension})")
print("Trying to process file inside on template initialized")
GLib.idle_add(self.show_processing_spinner, "Processing")
self.process_cli_file_in_thread(file_path)
elif file_extension in ['.wzt', '.bottle', '.prefix']:
print("B"*100)
GLib.idle_add(self.show_processing_spinner, "Restoring")
self.restore_prefix_bottle_wzt_tar_zst(file_path)
else:
print("C"*100)
print(f"Invalid file type: def on_open: {file_extension}. Only .exe or .msi files are allowed.")
GLib.timeout_add_seconds(0.5, self.show_info_dialog, "Invalid File Type", "Only .exe and .msi files are supported.")
self.command_line_file = None
return False
self.create_script_list()
def set_open_button_label(self, label_text):
self.print_method_name()
"""Helper method to update the open button's label"""
box = self.open_button.get_child()
if not box:
return
child = box.get_first_child()
while child:
if isinstance(child, Gtk.Label):
child.set_label(label_text)
elif isinstance(child, Gtk.Image):
child.set_visible(False) # Hide the icon during processing
child = child.get_next_sibling()
def show_initializing_step(self, step_text):
self.print_method_name()
"""
Show a new processing step in the flowbox
"""
if hasattr(self, 'progress_bar'):
# Calculate total steps dynamically
if hasattr(self, 'total_steps'):
total_steps = self.total_steps
else:
# Default for bottle creation
total_steps = 8
current_step = len(self.step_boxes) + 1
progress = current_step / total_steps
# Update progress bar
self.progress_bar.set_fraction(progress)
self.progress_bar.set_text(f"Step {current_step}/{total_steps}")
# Create step box
step_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
step_box.set_margin_start(12)
step_box.set_margin_end(12)
step_box.set_margin_top(6)
step_box.set_margin_bottom(6)
# Add status icon and label
step_spinner = Gtk.Spinner()
step_label = Gtk.Label(label=step_text)
step_label.set_halign(Gtk.Align.START)
step_label.set_hexpand(True)
step_box.append(step_spinner)
step_box.append(step_label)
step_spinner.start()
# Add to flowbox
flowbox_child = Gtk.FlowBoxChild()
flowbox_child.set_child(step_box)
self.flowbox.append(flowbox_child)
# Store reference
self.step_boxes.append((step_box, step_spinner, step_label))
def mark_step_as_done(self, step_text):
self.print_method_name()
"""
Mark a step as completed in the flowbox
"""
if hasattr(self, 'step_boxes'):
for step_box, step_spinner, step_label in self.step_boxes:
if step_label.get_text() == step_text:
step_box.remove(step_spinner)
done_icon = Gtk.Image.new_from_icon_name("emblem-ok-symbolic")
step_box.prepend(done_icon)
break
def check_required_programs(self):
self.print_method_name()
if shutil.which("flatpak-spawn"):
return []
# List of supported terminals
terminal_options = [
'ptyxis',
'gnome-terminal',
'konsole',
'xfce4-terminal'
]
# Base required programs
required_programs = [
'exiftool',
'wine',
'winetricks',
'wrestool',
'icotool',
'pgrep',
'xdg-open'
]
# Check if at least one terminal is available
terminal_found = any(shutil.which(term) for term in terminal_options)
if not terminal_found:
# If no terminal is found, add "terminal-emulator" as a missing requirement
missing_programs = [prog for prog in required_programs if not shutil.which(prog)]
missing_programs.append("terminal-emulator")
return missing_programs
return [prog for prog in required_programs if not shutil.which(prog)]
def show_missing_programs_dialog(self, missing_programs):
self.print_method_name()
if not missing_programs:
return
message_parts = []
# Handle terminal emulator message
if "terminal-emulator" in missing_programs:
message_parts.append(
"Missing required terminal emulator.\nPlease install one of the following:\n"
"• ptyxis\n"
"• gnome-terminal\n"
"• konsole\n"
"• xfce4-terminal"
)
# Remove terminal-emulator from the list for other missing programs
other_missing = [prog for prog in missing_programs if prog != "terminal-emulator"]
if other_missing:
message_parts.append("\nOther missing required programs:\n" +
"\n".join(f"• {prog}" for prog in other_missing))
else:
message_parts.append("The following required programs are missing:\n" +
"\n".join(f"• {prog}" for prog in missing_programs))
message = "\n".join(message_parts)
GLib.timeout_add_seconds(1, self.show_info_dialog,"Missing Programs", message)
def set_dynamic_variables(self):
self.print_method_name()
# Check if Settings.yaml exists and set the template and arch accordingly
if self.settings_file.exists():
settings = self.load_settings() # Assuming load_settings() returns a dictionary
self.template = self.expand_and_resolve_path(settings.get('template', self.default_template_win64))
self.arch = settings.get('arch', "win64")
self.icon_view = settings.get('icon_view', False)
self.single_prefix = settings.get('single-prefix', False)
else:
self.template = self.expand_and_resolve_path(self.default_template_win64)
self.arch = "win64"
self.runner = ""
self.template = self.default_template_win64 # Set template to the initialized one
self.icon_view = False
self.single_prefix = False
self.save_settings()
def save_settings(self):
self.print_method_name()
"""Save current settings to the Settings.yaml file."""
settings = {
'template': self.replace_home_with_tilde_in_path(str(self.template)),
'arch': self.arch,
'runner': self.replace_home_with_tilde_in_path(str(self.settings.get('runner', ''))),
'wine_debug': "WINEDEBUG=fixme-all DXVK_LOG_LEVEL=none",
'env_vars': '',
'icon_view': self.icon_view,
'single-prefix': self.single_prefix
}
try:
with open(self.settings_file, 'w') as settings_file:
yaml.dump(settings, settings_file, default_flow_style=False, indent=4)
print(f"Settings saved to {self.settings_file} with content:\n{settings}")
except Exception as e:
print(f"Error saving settings: {e}")
def load_settings(self):
self.print_method_name()
"""Load settings from the Settings.yaml file."""
if self.settings_file.exists():
with open(self.settings_file, 'r') as settings_file:
settings = yaml.safe_load(settings_file) or {}
# Expand and resolve paths when loading
self.template = self.expand_and_resolve_path(settings.get('template', self.default_template_win64))
self.runner = self.expand_and_resolve_path(settings.get('runner', ''))
self.arch = settings.get('arch', "win64")
self.icon_view = settings.get('icon_view', False)
self.env_vars = settings.get('env_vars', '')
self.single_prefix = settings.get('single-prefix', False)
return settings
# If no settings file, return an empty dictionary
return {}
def set_open_button_icon_visible(self, visible):
self.print_method_name()
box = self.open_button.get_child()
child = box.get_first_child()
while child:
if isinstance(child, Gtk.Image):
child.set_visible(visible)
child = child.get_next_sibling()
def on_activate(self, *args):
self.print_method_name()
if not self.window:
self.window = Adw.ApplicationWindow(application=self)
self.window.present()
def handle_sigint(self, signum, frame):
self.print_method_name()
if self.SOCKET_FILE.exists():
self.SOCKET_FILE.unlink()
self.quit()
def create_main_window(self):
self.print_method_name()
self.window = Gtk.ApplicationWindow(application=self)
self.window.set_title("Wine Charm")
self.window.set_default_size(480, 640)
self.window.add_css_class("common-background")
self.headerbar = Gtk.HeaderBar()
self.headerbar.set_show_title_buttons(True)
self.headerbar.add_css_class("flat")
self.window.set_titlebar(self.headerbar)
# Create a box to hold the app icon and the title label
self.title_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
# App icon
app_icon = Gtk.Image.new_from_icon_name("io.github.fastrizwaan.WineCharm")
app_icon.set_pixel_size(18) # Set icon size to 18
self.title_box.append(app_icon)
# Title label
title_label = Gtk.Label(label="Wine Charm")
title_label.set_markup("<b>Wine Charm</b>") # Use Pango Markup to make the text bold
title_label.set_use_markup(True) # Enable markup for this label
self.title_box.append(title_label)
# Set the title_box as the title widget of the headerbar
self.headerbar.set_title_widget(self.title_box)
# Back button
self.back_button = Gtk.Button.new_from_icon_name("go-previous-symbolic")
self.back_button.add_css_class("flat")
self.back_button.set_visible(False) # Hide it initially
self.back_button.connect("clicked", self.on_back_button_clicked)
self.headerbar.pack_start(self.back_button)
# Create a box to hold the Search button and the view toggle button
view_and_sort_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=1)
# Search button
self.search_button = Gtk.ToggleButton()
search_icon = Gtk.Image.new_from_icon_name("system-search-symbolic")
self.search_button.set_child(search_icon)
self.search_button.connect("toggled", self.on_search_button_clicked)
self.search_button.add_css_class("flat")
view_and_sort_box.append(self.search_button) # Add search button to the left
# Icon/List view toggle button
self.view_toggle_button = Gtk.ToggleButton()
icon_view_icon = Gtk.Image.new_from_icon_name("view-grid-symbolic")
list_view_icon = Gtk.Image.new_from_icon_name("view-list-symbolic")
self.view_toggle_button.set_child(icon_view_icon if self.icon_view else list_view_icon)
self.view_toggle_button.add_css_class("flat")
self.view_toggle_button.set_tooltip_text("Toggle Icon/List View")
self.view_toggle_button.connect("toggled", self.on_view_toggle_button_clicked)
view_and_sort_box.append(self.view_toggle_button)
# Add the view_and_sort_box to the headerbar
self.headerbar.pack_start(view_and_sort_box)
# Keep the existing menu button on the right side of the headerbar
self.menu_button = Gtk.MenuButton()
menu_icon = Gtk.Image.new_from_icon_name("open-menu-symbolic")
self.menu_button.set_child(menu_icon)
self.menu_button.add_css_class("flat")
self.menu_button.set_tooltip_text("Menu")
self.headerbar.pack_end(self.menu_button)
# Create the main menu for the right menu button
menu = Gio.Menu()
# Create a "Sort" submenu and add sorting options
sort_submenu = Gio.Menu()
sort_submenu.append("Name (A-Z)", "win.sort::progname::False")
sort_submenu.append("Name (Z-A)", "win.sort::progname::True")
sort_submenu.append("Wineprefix (A-Z)", "win.sort::wineprefix::False")
sort_submenu.append("Wineprefix (Z-A)", "win.sort::wineprefix::True")
sort_submenu.append("Time (Newest First)", "win.sort::mtime::True")
sort_submenu.append("Time (Oldest First)", "win.sort::mtime::False")
# Add the sort submenu to the main menu
menu.append_submenu("🔠 Sort", sort_submenu)
# Create a "Open" submenu and add open filemanager and terminal at winezguidir
open_submenu = Gio.Menu()
open_submenu.append("Open Filemanager", "win.open_filemanager_winecharm")
open_submenu.append("Open Terminal", "win.open_terminal_winecharm")
menu.append_submenu("📂 Open", open_submenu)
self.menu_button.set_menu_model(menu)
# Add other existing options in the hamburger menu
for label, action in self.hamburger_actions:
menu.append(label, f"win.{action.__name__}")
action_item = Gio.SimpleAction.new(action.__name__, None)
action_item.connect("activate", action)
self.window.add_action(action_item)
# Create actions for sorting options
self.create_sort_actions()
# Create actions for open options
self.create_open_actions()
# Rest of the UI setup...
self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.vbox.set_margin_start(10)
self.vbox.set_margin_end(10)
#self.vbox.set_margin_top(3)
self.vbox.set_margin_bottom(10)
self.window.set_child(self.vbox)
self.open_button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
self.open_button_box.set_halign(Gtk.Align.CENTER)
open_icon = Gtk.Image.new_from_icon_name("folder-open-symbolic")
open_label = Gtk.Label(label="Open")
self.open_button_box.append(open_icon)
self.open_button_box.append(open_label)
self.open_button = Gtk.Button()
self.open_button.set_child(self.open_button_box)
self.open_button.set_size_request(-1, 36) # Set height to 36 pixels
self.open_button_handler_id = self.open_button.connect("clicked", self.on_open_button_clicked)
self.vbox.append(self.open_button)
self.search_entry = Gtk.Entry()
self.search_entry.set_size_request(-1, 36)
self.search_entry.set_placeholder_text("Search")
self.search_entry.connect("activate", self.on_search_entry_activated)
self.search_entry.connect("changed", self.on_search_entry_changed)
self.search_entry_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
search_icon = Gtk.Image.new_from_icon_name("system-search-symbolic")
self.search_entry_box.append(self.search_entry)
self.search_entry_box.set_hexpand(True)
self.search_entry.set_hexpand(True)
self.main_frame = Gtk.Frame()
self.main_frame.set_margin_top(0)
self.vbox.append(self.main_frame)
self.scrolled = Gtk.ScrolledWindow() # Make scrolled an instance variable
self.scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.scrolled.set_vexpand(True)
self.scrolled.set_hexpand(True)
self.main_frame.set_child(self.scrolled)
self.flowbox = Gtk.FlowBox()
self.flowbox.set_valign(Gtk.Align.START)
self.flowbox.set_halign(Gtk.Align.FILL)
#if self.icon_view:
# self.flowbox.set_max_children_per_line(8)
#else:
# self.flowbox.set_max_children_per_line(4)
self.flowbox.set_homogeneous(True)
self.flowbox.set_selection_mode(Gtk.SelectionMode.NONE)
self.scrolled.set_child(self.flowbox)
key_controller = Gtk.EventControllerKey()
key_controller.connect("key-pressed", self.on_key_pressed)
self.window.add_controller(key_controller)
self.create_script_list()
# Add keyboard actions
self.add_keyboard_actions()
def add_keyboard_actions(self):
self.print_method_name()
# Search action
search_action = Gio.SimpleAction.new("search", None)
search_action.connect("activate", lambda *_: self.search_button.set_active(not self.search_button.get_active()))
self.window.add_action(search_action)
# Open action (fixed signature)
open_action = Gio.SimpleAction.new("open", None)
open_action.connect("activate", lambda *_: self.on_open_button_clicked(None))
self.window.add_action(open_action)
# Toggle view action