-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniversalCompiler.py
More file actions
2207 lines (1850 loc) · 78.2 KB
/
UniversalCompiler.py
File metadata and controls
2207 lines (1850 loc) · 78.2 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
"""
Universal Compiler v2.0 - Python Edition
A powerful, all-in-one script-to-EXE compiler with a modern dark-themed GUI
Compiles PowerShell, Python, Batch, Node.js, C#, Go, Ruby, VBScript,
and AutoHotkey scripts into standalone Windows executables.
"""
import os
import sys
import json
import shutil
import subprocess
import threading
import ctypes
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, List, Any
import tkinter as tk
from tkinter import filedialog, messagebox
# Optional drag & drop support
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
HAS_DND = True
except ImportError:
HAS_DND = False
print("Note: tkinterdnd2 not installed. Drag & drop disabled.")
print("Install with: pip install tkinterdnd2")
try:
import customtkinter as ctk
except ImportError:
print("Installing customtkinter...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "customtkinter"])
import customtkinter as ctk
try:
from PIL import Image, ImageTk
except ImportError:
print("Installing Pillow...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "Pillow"])
from PIL import Image, ImageTk
# ============================================================================
# CONSTANTS & CONFIGURATION
# ============================================================================
APP_NAME = "Universal Compiler"
APP_VERSION = "2.0"
CONFIG_DIR = Path(os.environ.get("APPDATA", Path.home())) / "UniversalCompiler"
CONFIG_FILE = CONFIG_DIR / "config.json"
PROFILES_FILE = CONFIG_DIR / "profiles.json"
HISTORY_FILE = CONFIG_DIR / "history.json"
RECENT_FILE = CONFIG_DIR / "recent.json"
SETTINGS_FILE = CONFIG_DIR / "settings.json"
TEMPLATES_DIR = CONFIG_DIR / "Templates"
LOG_FILE = CONFIG_DIR / "install.log"
# Ensure config directory exists
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
# ============================================================================
# THEME DEFINITIONS
# ============================================================================
THEMES = {
"Dark": {
"bg": "#020617",
"card": "#0f172a",
"card_hover": "#1e293b",
"border": "#1e293b",
"input": "#0f172a",
"green": "#22c55e",
"green_hover": "#16a34a",
"blue": "#60a5fa",
"red": "#ef4444",
"yellow": "#eab308",
"text1": "#f8fafc",
"text2": "#94a3b8",
"text3": "#64748b",
"log_bg": "#0a0f1a",
},
"Light": {
"bg": "#f8fafc",
"card": "#ffffff",
"card_hover": "#f1f5f9",
"border": "#e2e8f0",
"input": "#ffffff",
"green": "#16a34a",
"green_hover": "#15803d",
"blue": "#3b82f6",
"red": "#dc2626",
"yellow": "#ca8a04",
"text1": "#0f172a",
"text2": "#475569",
"text3": "#94a3b8",
"log_bg": "#f1f5f9",
}
}
# ============================================================================
# DEFAULT SETTINGS & PROFILES
# ============================================================================
DEFAULT_SETTINGS = {
"theme": "Dark",
"post_build_action": "None",
"post_build_copy_path": "",
"show_notifications": True,
"auto_check_updates": True,
"max_recent_files": 10,
"max_history_items": 50,
"default_profile": "Default",
"signing_cert_path": "",
"signing_cert_password": "",
}
DEFAULT_PROFILES = {
"Default": {
"console": False,
"admin": False,
"single_file": True,
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
},
"Console App": {
"console": True,
"admin": False,
"single_file": True,
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
},
"Admin Tool": {
"console": True,
"admin": True,
"single_file": True,
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
},
"GUI Application": {
"console": False,
"admin": False,
"single_file": True,
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
},
}
# ============================================================================
# COMPILER DEFINITIONS
# ============================================================================
COMPILERS = {
"ps1": {"name": "PowerShell", "compiler": "PS2EXE", "desc": "PowerShell Script"},
"py": {"name": "Python", "compiler": "PyInstaller", "desc": "Python Script"},
"bat": {"name": "Batch", "compiler": "IExpress", "desc": "Batch Script"},
"cmd": {"name": "Command", "compiler": "IExpress", "desc": "Command Script"},
"js": {"name": "Node.js", "compiler": "pkg", "desc": "JavaScript"},
"vbs": {"name": "VBScript", "compiler": "IExpress", "desc": "VBScript"},
"ahk": {"name": "AutoHotkey", "compiler": "Ahk2Exe", "desc": "AutoHotkey"},
"cs": {"name": "C#", "compiler": "CSC", "desc": "C# Source"},
"go": {"name": "Go", "compiler": "go build", "desc": "Go Source"},
"rb": {"name": "Ruby", "compiler": "Ocra", "desc": "Ruby Script"},
}
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def load_json(filepath: Path, default: Any = None) -> Any:
"""Load JSON file with fallback to default."""
try:
if filepath.exists():
with open(filepath, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return default if default is not None else {}
def save_json(filepath: Path, data: Any) -> None:
"""Save data to JSON file."""
try:
filepath.parent.mkdir(parents=True, exist_ok=True)
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"Error saving {filepath}: {e}")
def format_size(size: int) -> str:
"""Format file size in human-readable format."""
if size >= 1_073_741_824:
return f"{size / 1_073_741_824:.1f} GB"
elif size >= 1_048_576:
return f"{size / 1_048_576:.1f} MB"
elif size >= 1024:
return f"{size / 1024:.1f} KB"
return f"{size} bytes"
def estimate_output_size(source_file: str, file_type: str) -> str:
"""Estimate the output EXE size based on file type."""
if not os.path.exists(source_file):
return "Unknown"
source_size = os.path.getsize(source_file)
estimates = {
"ps1": (5 * 1024 * 1024, 1.5), # ~5MB base + 1.5x
"py": (15 * 1024 * 1024, 2), # ~15MB base + 2x
"bat": (50 * 1024, 1.2), # ~50KB base
"cmd": (50 * 1024, 1.2),
"js": (40 * 1024 * 1024, 1.5), # ~40MB base (Node.js)
"vbs": (50 * 1024, 1.2),
"ahk": (1 * 1024 * 1024, 1.3), # ~1MB base
"cs": (10 * 1024, 1.1), # Small .NET overhead
"go": (2 * 1024 * 1024, 1.2), # ~2MB base
"rb": (20 * 1024 * 1024, 2), # ~20MB base (Ruby)
}
if file_type in estimates:
base, multiplier = estimates[file_type]
return format_size(int(base + source_size * multiplier))
return "Unknown"
def log_message(message: str) -> None:
"""Write message to log file."""
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(f"[{timestamp}] {message}\n")
except Exception:
pass
def run_command(cmd: List[str], cwd: Optional[str] = None) -> tuple:
"""Run a command and return (success, output)."""
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=cwd,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
return result.returncode == 0, result.stdout + result.stderr
except Exception as e:
return False, str(e)
def which(program: str) -> Optional[str]:
"""Find program in PATH."""
return shutil.which(program)
def show_notification(title: str, message: str) -> None:
"""Show Windows toast notification."""
try:
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast(title, message, duration=5, threaded=True)
except ImportError:
try:
# Fallback to Windows balloon notification
ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)
except Exception:
pass
except Exception:
pass
# ============================================================================
# SETTINGS MANAGEMENT
# ============================================================================
class Settings:
"""Application settings manager."""
def __init__(self):
self._settings = DEFAULT_SETTINGS.copy()
self.load()
def load(self) -> None:
"""Load settings from file."""
saved = load_json(SETTINGS_FILE, {})
for key, value in saved.items():
if key in self._settings:
self._settings[key] = value
def save(self) -> None:
"""Save settings to file."""
save_json(SETTINGS_FILE, self._settings)
def get(self, key: str, default: Any = None) -> Any:
"""Get setting value."""
return self._settings.get(key, default)
def set(self, key: str, value: Any) -> None:
"""Set setting value."""
self._settings[key] = value
self.save()
@property
def theme(self) -> str:
return self._settings["theme"]
@theme.setter
def theme(self, value: str):
self._settings["theme"] = value
self.save()
# ============================================================================
# RECENT FILES MANAGEMENT
# ============================================================================
class RecentFiles:
"""Recent files manager."""
def __init__(self, max_items: int = 10):
self.max_items = max_items
self._files: List[str] = []
self.load()
def load(self) -> None:
"""Load recent files from disk."""
saved = load_json(RECENT_FILE, [])
self._files = [f for f in saved if os.path.exists(f)][:self.max_items]
def save(self) -> None:
"""Save recent files to disk."""
save_json(RECENT_FILE, self._files)
def add(self, filepath: str) -> None:
"""Add file to recent list."""
if filepath in self._files:
self._files.remove(filepath)
self._files.insert(0, filepath)
self._files = self._files[:self.max_items]
self.save()
def get_all(self) -> List[str]:
"""Get all recent files."""
return self._files.copy()
# ============================================================================
# BUILD PROFILES MANAGEMENT
# ============================================================================
class BuildProfiles:
"""Build profiles manager."""
def __init__(self):
self._profiles = DEFAULT_PROFILES.copy()
self.load()
def load(self) -> None:
"""Load profiles from disk."""
saved = load_json(PROFILES_FILE, {})
for name, profile in saved.items():
self._profiles[name] = profile
def save(self) -> None:
"""Save profiles to disk."""
save_json(PROFILES_FILE, self._profiles)
def get(self, name: str) -> Optional[Dict]:
"""Get profile by name."""
return self._profiles.get(name)
def set(self, name: str, profile: Dict) -> None:
"""Save or update profile."""
self._profiles[name] = profile
self.save()
def names(self) -> List[str]:
"""Get all profile names."""
return list(self._profiles.keys())
# ============================================================================
# COMPILATION HISTORY
# ============================================================================
class CompilationHistory:
"""Compilation history manager."""
def __init__(self, max_items: int = 50):
self.max_items = max_items
self._history: List[Dict] = []
self.load()
def load(self) -> None:
"""Load history from disk."""
self._history = load_json(HISTORY_FILE, [])
def save(self) -> None:
"""Save history to disk."""
save_json(HISTORY_FILE, self._history)
def add(self, source: str, output: str, file_type: str,
success: bool, profile: str, size: int) -> None:
"""Add compilation to history."""
entry = {
"timestamp": datetime.now().isoformat(),
"source": source,
"output": output,
"type": file_type,
"success": success,
"profile": profile,
"size": size,
}
self._history.insert(0, entry)
self._history = self._history[:self.max_items]
self.save()
def get_all(self) -> List[Dict]:
"""Get all history entries."""
return self._history.copy()
# ============================================================================
# TEMPLATE SCRIPTS
# ============================================================================
TEMPLATES = {
"HelloWorld.ps1": '''# PowerShell Hello World
param([string]$Name = "World")
Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show("Hello, $Name!", "Hello", "OK", "Information")
''',
"HelloWorld.py": '''# Python Hello World
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
messagebox.showinfo("Hello", "Hello, World!")
root.destroy()
''',
"HelloWorld.bat": '''@echo off
echo Hello, World!
pause
''',
"HelloWorld.js": '''// Node.js Hello World
console.log("Hello, World!");
''',
"HelloWorld.cs": '''using System;
using System.Windows.Forms;
class Program {
[STAThread]
static void Main() {
MessageBox.Show("Hello, World!", "Hello");
}
}
''',
"HelloWorld.go": '''package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
''',
"HelloWorld.rb": '''# Ruby Hello World
puts "Hello, World!"
''',
"HelloWorld.vbs": '''MsgBox "Hello, World!", vbInformation, "Hello"
''',
"HelloWorld.ahk": '''MsgBox, Hello, World!
''',
}
def initialize_templates() -> None:
"""Create template files if they don't exist."""
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
for filename, content in TEMPLATES.items():
filepath = TEMPLATES_DIR / filename
if not filepath.exists():
filepath.write_text(content, encoding="utf-8")
# ============================================================================
# DEPENDENCY CHECKER
# ============================================================================
class DependencyChecker:
"""Check and install compiler dependencies."""
@staticmethod
def check_ps2exe() -> bool:
"""Check if PS2EXE is available."""
try:
result = subprocess.run(
["powershell", "-Command", "Get-Module -ListAvailable ps2exe"],
capture_output=True, text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
return "ps2exe" in result.stdout.lower()
except Exception:
return False
@staticmethod
def check_pyinstaller() -> bool:
"""Check if PyInstaller is available."""
return which("pyinstaller") is not None
@staticmethod
def check_pkg() -> bool:
"""Check if pkg is available."""
return which("pkg") is not None
@staticmethod
def check_go() -> bool:
"""Check if Go is available."""
if which("go"):
return True
go_path = Path(os.environ.get("LOCALAPPDATA", "")) / "Programs/Go/bin/go.exe"
return go_path.exists()
@staticmethod
def check_ruby() -> bool:
"""Check if Ruby/Ocra is available."""
return which("ocra") is not None
@staticmethod
def check_ahk() -> bool:
"""Check if AutoHotkey compiler is available."""
paths = [
Path(os.environ.get("ProgramFiles", "")) / "AutoHotkey/Compiler/Ahk2Exe.exe",
Path(os.environ.get("ProgramFiles", "")) / "AutoHotkey/v2/Compiler/Ahk2Exe.exe",
Path(os.environ.get("ProgramFiles(x86)", "")) / "AutoHotkey/Compiler/Ahk2Exe.exe",
]
return any(p.exists() for p in paths)
@staticmethod
def check_csc() -> bool:
"""Check if CSC is available."""
windir = os.environ.get("WINDIR", "C:\\Windows")
paths = [
Path(windir) / "Microsoft.NET/Framework64/v4.0.30319/csc.exe",
Path(windir) / "Microsoft.NET/Framework/v4.0.30319/csc.exe",
]
return any(p.exists() for p in paths)
@staticmethod
def check_iexpress() -> bool:
"""Check if IExpress is available."""
windir = os.environ.get("WINDIR", "C:\\Windows")
return (Path(windir) / "System32/iexpress.exe").exists()
@classmethod
def check_compiler(cls, file_type: str) -> bool:
"""Check if compiler for file type is available."""
checkers = {
"ps1": cls.check_ps2exe,
"py": cls.check_pyinstaller,
"bat": cls.check_iexpress,
"cmd": cls.check_iexpress,
"js": cls.check_pkg,
"vbs": cls.check_iexpress,
"ahk": cls.check_ahk,
"cs": cls.check_csc,
"go": cls.check_go,
"rb": cls.check_ruby,
}
checker = checkers.get(file_type)
return checker() if checker else False
@classmethod
def get_all_status(cls) -> Dict[str, Dict]:
"""Get status of all dependencies."""
return {
"PS2EXE": {"name": "PS2EXE", "desc": "PowerShell (.ps1)", "installed": cls.check_ps2exe(), "size": "~2 MB"},
"PyInstaller": {"name": "PyInstaller", "desc": "Python (.py)", "installed": cls.check_pyinstaller(), "size": "~15 MB"},
"pkg": {"name": "pkg", "desc": "Node.js (.js)", "installed": cls.check_pkg(), "size": "~50 MB"},
"Go": {"name": "Go", "desc": "Go (.go)", "installed": cls.check_go(), "size": "~150 MB"},
"Ruby": {"name": "Ruby+Ocra", "desc": "Ruby (.rb)", "installed": cls.check_ruby(), "size": "~120 MB"},
"AutoHotkey": {"name": "AutoHotkey", "desc": "AHK (.ahk)", "installed": cls.check_ahk(), "size": "~5 MB"},
"CSC": {"name": "CSC", "desc": "C# (.cs)", "installed": cls.check_csc(), "size": "Built-in", "builtin": True},
"IExpress": {"name": "IExpress", "desc": "Batch/VBS", "installed": cls.check_iexpress(), "size": "Built-in", "builtin": True},
}
# ============================================================================
# COMPILERS
# ============================================================================
class Compiler:
"""Handle compilation for various script types."""
@staticmethod
def compile_ps1(source: str, output: str, icon: Optional[str] = None,
admin: bool = False, no_console: bool = True,
metadata: Optional[Dict] = None) -> tuple:
"""Compile PowerShell script using PS2EXE."""
cmd = ["powershell", "-ExecutionPolicy", "Bypass", "-Command"]
ps_cmd = f'Invoke-PS2EXE -InputFile "{source}" -OutputFile "{output}"'
if icon and os.path.exists(icon):
ps_cmd += f' -IconFile "{icon}"'
if admin:
ps_cmd += " -RequireAdmin"
if no_console:
ps_cmd += " -NoConsole"
if metadata:
if metadata.get("product"):
ps_cmd += f' -Title "{metadata["product"]}"'
if metadata.get("version"):
ps_cmd += f' -Version "{metadata["version"]}"'
if metadata.get("company"):
ps_cmd += f' -Company "{metadata["company"]}"'
if metadata.get("copyright"):
ps_cmd += f' -Copyright "{metadata["copyright"]}"'
cmd.append(ps_cmd)
return run_command(cmd)
@staticmethod
def compile_py(source: str, output: str, icon: Optional[str] = None,
one_file: bool = True, console: bool = False) -> tuple:
"""Compile Python script using PyInstaller."""
output_dir = os.path.dirname(output)
output_name = os.path.splitext(os.path.basename(output))[0]
cmd = ["pyinstaller", "--distpath", output_dir, "--name", output_name, "--noconfirm"]
if one_file:
cmd.append("--onefile")
if not console:
cmd.append("--noconsole")
if icon and os.path.exists(icon):
cmd.extend(["--icon", icon])
cmd.append(source)
return run_command(cmd)
@staticmethod
def compile_batch(source: str, output: str) -> tuple:
"""Compile Batch/VBS script using IExpress."""
import tempfile
temp_dir = tempfile.mkdtemp()
try:
# Copy source to temp
src_name = os.path.basename(source)
shutil.copy(source, os.path.join(temp_dir, src_name))
# Create SED file
sed_content = f"""[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=0
HideExtractAnimation=1
UseLongFileName=1
InsideCompressed=0
CAB_FixedSize=0
RebootMode=N
TargetName={output}
FriendlyName=App
AppLaunched=cmd /c "{src_name}"
PostInstallCmd=<None>
SourceFiles=SourceFiles
[Strings]
[SourceFiles]
SourceFiles0={temp_dir}\\
[SourceFiles0]
%FILE0%={src_name}
"""
sed_file = os.path.join(temp_dir, "config.sed")
with open(sed_file, "w") as f:
f.write(sed_content)
windir = os.environ.get("WINDIR", "C:\\Windows")
iexpress = os.path.join(windir, "System32", "iexpress.exe")
return run_command([iexpress, "/N", "/Q", sed_file])
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
@staticmethod
def compile_js(source: str, output: str) -> tuple:
"""Compile Node.js script using pkg."""
cmd = ["pkg", source, "--target", "node18-win-x64", "--output", output]
return run_command(cmd)
@staticmethod
def compile_cs(source: str, output: str) -> tuple:
"""Compile C# source using CSC."""
windir = os.environ.get("WINDIR", "C:\\Windows")
csc_paths = [
os.path.join(windir, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe"),
os.path.join(windir, "Microsoft.NET", "Framework", "v4.0.30319", "csc.exe"),
]
csc = next((p for p in csc_paths if os.path.exists(p)), None)
if not csc:
return False, "CSC compiler not found"
return run_command([csc, f"/out:{output}", source])
@staticmethod
def compile_go(source: str, output: str) -> tuple:
"""Compile Go source using go build."""
go_exe = which("go")
if not go_exe:
go_path = Path(os.environ.get("LOCALAPPDATA", "")) / "Programs/Go/bin/go.exe"
if go_path.exists():
go_exe = str(go_path)
if not go_exe:
return False, "Go compiler not found"
return run_command([go_exe, "build", "-o", output, source], cwd=os.path.dirname(source))
@staticmethod
def compile_ahk(source: str, output: str, icon: Optional[str] = None) -> tuple:
"""Compile AutoHotkey script using Ahk2Exe."""
ahk_paths = [
Path(os.environ.get("ProgramFiles", "")) / "AutoHotkey/Compiler/Ahk2Exe.exe",
Path(os.environ.get("ProgramFiles", "")) / "AutoHotkey/v2/Compiler/Ahk2Exe.exe",
]
ahk = next((str(p) for p in ahk_paths if p.exists()), None)
if not ahk:
return False, "AutoHotkey compiler not found"
cmd = [ahk, "/in", source, "/out", output]
if icon and os.path.exists(icon):
cmd.extend(["/icon", icon])
return run_command(cmd)
@staticmethod
def compile_rb(source: str, output: str) -> tuple:
"""Compile Ruby script using Ocra."""
return run_command(["ocra", source, "--output", output])
@classmethod
def compile(cls, source: str, output: str, file_type: str,
icon: Optional[str] = None, admin: bool = False,
console: bool = False, single_file: bool = True,
metadata: Optional[Dict] = None) -> tuple:
"""Compile source file based on type."""
compilers = {
"ps1": lambda: cls.compile_ps1(source, output, icon, admin, not console, metadata),
"py": lambda: cls.compile_py(source, output, icon, single_file, console),
"bat": lambda: cls.compile_batch(source, output),
"cmd": lambda: cls.compile_batch(source, output),
"js": lambda: cls.compile_js(source, output),
"vbs": lambda: cls.compile_batch(source, output),
"ahk": lambda: cls.compile_ahk(source, output, icon),
"cs": lambda: cls.compile_cs(source, output),
"go": lambda: cls.compile_go(source, output),
"rb": lambda: cls.compile_rb(source, output),
}
compiler = compilers.get(file_type)
if compiler:
return compiler()
return False, f"Unsupported file type: {file_type}"
# ============================================================================
# SETUP WINDOW
# ============================================================================
class SetupWindow(ctk.CTkToplevel):
"""Dependency setup window."""
def __init__(self, parent, theme: Dict):
super().__init__(parent)
self.theme = theme
self.title("Universal Compiler - Setup")
self.geometry("600x550")
self.resizable(False, False)
# Center window
self.update_idletasks()
x = (self.winfo_screenwidth() - 600) // 2
y = (self.winfo_screenheight() - 550) // 2
self.geometry(f"600x550+{x}+{y}")
self.configure(fg_color=theme["bg"])
self.checkboxes: Dict[str, ctk.CTkCheckBox] = {}
self.completed = False
self._create_ui()
# Make modal
self.transient(parent)
self.grab_set()
def _create_ui(self):
# Header
header = ctk.CTkFrame(self, fg_color=self.theme["card"], corner_radius=0)
header.pack(fill="x", padx=0, pady=0)
title_frame = ctk.CTkFrame(header, fg_color="transparent")
title_frame.pack(padx=20, pady=15)
ctk.CTkLabel(
title_frame, text="⚡ Universal Compiler",
font=("Segoe UI", 20, "bold"),
text_color=self.theme["text1"]
).pack(side="left")
ctk.CTkLabel(
title_frame, text="v2.0",
font=("Segoe UI", 10),
text_color=self.theme["text3"]
).pack(side="left", padx=(10, 0), pady=(8, 0))
ctk.CTkLabel(
header, text="Select compilers to install",
font=("Segoe UI", 11),
text_color=self.theme["text2"]
).pack(padx=20, pady=(0, 15))
# Dependency list
deps_frame = ctk.CTkScrollableFrame(
self, fg_color=self.theme["bg"],
height=350
)
deps_frame.pack(fill="both", expand=True, padx=15, pady=10)
deps = DependencyChecker.get_all_status()
for key, dep in deps.items():
self._create_dep_card(deps_frame, key, dep)
# Progress bar (hidden initially)
self.progress_frame = ctk.CTkFrame(self, fg_color=self.theme["log_bg"])
self.progress_label = ctk.CTkLabel(
self.progress_frame, text="Installing...",
text_color=self.theme["text2"], font=("Segoe UI", 11)
)
self.progress_label.pack(padx=15, pady=(10, 5))
self.progress_bar = ctk.CTkProgressBar(
self.progress_frame, fg_color=self.theme["border"],
progress_color=self.theme["green"]
)
self.progress_bar.pack(padx=15, pady=(0, 10), fill="x")
self.progress_bar.set(0)
# Bottom buttons
bottom = ctk.CTkFrame(self, fg_color=self.theme["card"])
bottom.pack(fill="x", side="bottom")
btn_frame = ctk.CTkFrame(bottom, fg_color="transparent")
btn_frame.pack(pady=15)
self.skip_btn = ctk.CTkButton(
btn_frame, text="Skip", width=100,
fg_color=self.theme["border"],
hover_color=self.theme["card_hover"],
text_color=self.theme["text1"],
command=self._on_skip
)
self.skip_btn.pack(side="left", padx=5)
self.install_btn = ctk.CTkButton(
btn_frame, text="Install Selected", width=140,
fg_color=self.theme["green"],
hover_color=self.theme["green_hover"],
text_color=self.theme["bg"],
font=("Segoe UI", 12, "bold"),
command=self._on_install
)
self.install_btn.pack(side="left", padx=5)
def _create_dep_card(self, parent, key: str, dep: Dict):
card = ctk.CTkFrame(parent, fg_color=self.theme["card"], corner_radius=8)
card.pack(fill="x", pady=4)
inner = ctk.CTkFrame(card, fg_color="transparent")
inner.pack(fill="x", padx=12, pady=10)
# Checkbox
var = ctk.BooleanVar(value=not dep["installed"] and key == "PS2EXE")
cb = ctk.CTkCheckBox(
inner, text="", variable=var,
fg_color=self.theme["green"],
hover_color=self.theme["green_hover"],
border_color=self.theme["border"],
width=24, height=24
)
if dep["installed"] or dep.get("builtin"):
cb.configure(state="disabled")
var.set(False)
cb.pack(side="left")
self.checkboxes[key] = cb
# Info
info = ctk.CTkFrame(inner, fg_color="transparent")
info.pack(side="left", fill="x", expand=True, padx=(10, 0))
name_frame = ctk.CTkFrame(info, fg_color="transparent")
name_frame.pack(anchor="w")
ctk.CTkLabel(
name_frame, text=dep["name"],
font=("Segoe UI", 13, "bold"),
text_color=self.theme["text1"]
).pack(side="left")
if dep["installed"]:
badge = ctk.CTkLabel(
name_frame, text="✓ Installed",
font=("Segoe UI", 9),
text_color=self.theme["green"],
fg_color="#166534",
corner_radius=3
)
badge.pack(side="left", padx=(8, 0))
elif dep.get("builtin"):
badge = ctk.CTkLabel(
name_frame, text="Built-in",
font=("Segoe UI", 9),
text_color=self.theme["blue"],
fg_color="#1e3a5f",
corner_radius=3
)
badge.pack(side="left", padx=(8, 0))
ctk.CTkLabel(
info, text=dep["desc"],
font=("Segoe UI", 10),
text_color=self.theme["text2"]
).pack(anchor="w")
# Size
ctk.CTkLabel(
inner, text=dep["size"],
font=("Segoe UI", 10),
text_color=self.theme["text3"]
).pack(side="right")
def _on_skip(self):
self.completed = True
self.destroy()
def _on_install(self):
selected = [k for k, cb in self.checkboxes.items()
if cb.cget("state") != "disabled" and cb.get()]
if not selected:
self.completed = True
self.destroy()
return
self.install_btn.configure(state="disabled")
self.skip_btn.configure(state="disabled")
self.progress_frame.pack(fill="x", before=self.winfo_children()[-1])
def install_thread():
for i, dep in enumerate(selected):
self.progress_label.configure(text=f"Installing {dep}...")
self.progress_bar.set((i + 1) / len(selected))
self.update()
# Install logic here (placeholder)
if dep == "PS2EXE":
run_command(["powershell", "-Command",
"Install-Module ps2exe -Scope CurrentUser -Force"])
elif dep == "PyInstaller":
run_command([sys.executable, "-m", "pip", "install", "pyinstaller"])
self.progress_label.configure(text="Complete!")
self.after(1000, self._finish)
threading.Thread(target=install_thread, daemon=True).start()
def _finish(self):
self.completed = True
self.destroy()
# ============================================================================
# MAIN APPLICATION
# ============================================================================
class UniversalCompiler:
"""Main application class."""
def __init__(self):
# Initialize managers