forked from Opticos/GWSL-Source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.py
4817 lines (3785 loc) · 176 KB
/
manager.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
# GWSL Dashboard *lets do this again*
# Copyright Paul-E/Opticos Studios 2022-2023
# https://sites.google.com/bartimee.com/opticos-studios/home
# Dedicated to the Sacred Heart of Jesus
# #########
# # #############
# ~ #########
# ######### ####
# \@/
# |
# #
# O #.
# |> #
# _# #
import time
import os
import sys
import win32
import subprocess
import threading
import iset
import re
import pymsgbox
import random
import winshell
from win32com.client import Dispatch
import winreg
from winreg import *
from exe_layer import cmd
import logging
import ipaddress
import rounder
import sv_ttk
import win32mica
BUILD_MODE = "WIN32" # MSIX or WIN32
version = "1.4.6"
lc_name = "Licenses145.txt"
show_ad = False
debug = False
args = sys.argv
frozen = 'not'
if getattr(sys, 'frozen', False):
# we are running in a bundle
frozen = 'ever so'
bundle_dir = sys._MEIPASS
else:
# we are running in a normal Python environment
bundle_dir = os.path.dirname(os.path.abspath(__file__))
if debug == True:
print("debug mode")
print('we are', frozen, 'frozen')
print('bundle dir is', bundle_dir)
print('sys.argv[0] is', sys.argv[0])
print('sys.executable is', sys.executable)
print('os.getcwd is', os.getcwd())
asset_dir = bundle_dir + "\\assets\\"
app_path = os.getenv('APPDATA') + "\\GWSL\\"
if os.path.isdir(app_path) == False:
# os.mkdir(app_path)
print(subprocess.getoutput('mkdir "' + app_path + '"'))
print("creating appdata directory")
# EMERGENCY LOG DELETER FOR 1.3.6. Delete in 1.3.8
"""
try:
if os.path.exists(app_path + "GWSL_helper.sh") == True:
scr = open(app_path + "GWSL_helper.sh", "r")
lines = scr.read()
if "v3" not in lines:
print("Cleaning Logs...")
os.remove(app_path + 'dashboard.log')
os.remove(app_path + 'settings.json')
except:
pass
"""
class DuplicateFilter(logging.Filter):
def filter(self, record):
# add other fields if you need more granular comparison, depends on your app
current_log = (record.module, record.levelno, record.msg)
if current_log != getattr(self, "last_log", None):
self.last_log = current_log
return True
return False
logger = logging.Logger("GWSL " + version, level=0)
# logger = logging.getLogger("GWSL " + version)
# Create handlers
f_handler = logging.FileHandler(app_path + 'dashboard.log')
# f_handler.setLevel(10)
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_format)
# Add handlers to the logger
logger.addHandler(f_handler)
logger.addFilter(DuplicateFilter())
updated = False
new_install = False
def set_update():
print("Updating settings")
old_iset = iset.read()
iset.create(app_path + "\\settings.json")
new_iset = iset.read()
#migrate user settings
new_iset["putty"]["ip"] = old_iset["putty"]["ip"]
new_iset["distro_blacklist"] = old_iset["distro_blacklist"]
new_iset["app_blacklist"] = old_iset["app_blacklist"]
new_iset["xserver_profiles"] = old_iset["xserver_profiles"]
try:
new_iset["general"]["acrylic_enabled"] = old_iset["general"]["acrylic_enabled"]
except:
pass
try:
new_iset["general"]["clipboard"] = old_iset["general"]["clipboard"]
except:
pass
try:
new_iset["general"]["start_menu_mode"] = old_iset["general"]["start_menu_mode"]
except:
pass
try:
new_iset["general"]["shell_gui"] = old_iset["general"]["shell_gui"]
except:
pass
try:
new_iset["graphics"]["hidpi"] = old_iset["graphics"]["hidpi"]
except:
pass
try:
new_iset["putty"]["ssh_key"] = old_iset["putty"]["ssh_key"]
except:
pass
# 1.4.5
try:
new_iset["general"]["force_disable_primary"] = old_iset["general"]["force_disable_primary"]
except:
pass
try:
new_iset["general"]["hide_donation_reminder"] = old_iset["general"]["hide_donation_reminder"]
except:
pass
iset.set(new_iset)
try:
iset.path = app_path + "settings.json"
if os.path.exists(app_path + "\\settings.json") == False:
iset.create(app_path + "\\settings.json")
print("creating settings")
new_install = True
else:
sett = iset.read()
if "conf_ver" not in sett:
iset.create(app_path + "\\settings.json")
print("Updating settings")
else:
if sett["conf_ver"] >= 7:
if debug == True:
print("Settings up to date")
try:
v = sett["gwsl_ver"]
if v != version:
updated = True
sett["gwsl_ver"] = version
iset.set(sett)
except:
updated = True
set_update()
else:
updated = True
set_update()
# Get the script ready
import wsl_tools as tools
if os.path.exists(app_path + "GWSL_helper.sh") == False:
# print("Moving helper script")
print(subprocess.getoutput('copy "' + bundle_dir + "\\assets\GWSL_helper.sh" + '" "' + app_path + '"'))
if os.path.exists(app_path + "oiw_update.txt") == False:
print("show ad")
#with open(app_path + "oiw_update.txt", "w") as filer:
# filer.write("Delete this file to get the OpenInWSL Ad on startup again")
# filer.close()
show_ad = True
else:
# make sure the script is up to date
scr = open(app_path + "GWSL_helper.sh", "r")
lines = scr.read()
if "v4" in lines:
if debug == True:
print("Script is up to date")
else:
print("Updating Script")
print(subprocess.getoutput('copy "' + bundle_dir + "\\assets\GWSL_helper.sh" + '" "' + app_path + '"'))
if os.path.exists(app_path + lc_name) == False:
# print("Moving Licenses")
print(subprocess.getoutput('copy "' + bundle_dir + "\\assets\\" + lc_name + '" "' + app_path + '"'))
except Exception as e:
logger.exception("Exception occurred - Config generation")
sys.exit()
tools.script = app_path + "\\GWSL_helper.sh"
try:
import ctypes
import platform
if int(platform.release()) >= 8:
ctypes.windll.shcore.SetProcessDpiAwareness(True)
except Exception as e:
logger.exception("Exception occurred - Cannot set dpi aware")
import tkinter as tk
from tkinter import *
from tkinter import ttk
root = None # tk.Tk() #this is intensive... import as needed?
# root.withdraw()
from PIL import Image, ImageTk
import PIL
import win32gui
import PIL.ImageTk
import win32con
import win32api
import keyboard
def get_system_light():
"""
Sets color of white based on Windows registry theme setting
:return:
"""
global light, white, accent
try:
registry = ConnectRegistry(None, HKEY_CURRENT_USER)
key = OpenKey(registry, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize')
key_value = QueryValueEx(key, 'SystemUsesLightTheme')
k = int(key_value[0])
light = False
white = [255, 255, 255]
if k == 1:
light = True
white = [0, 0, 0]
for i in range(3):
if accent[i] > 50:
accent[i] -= 50
except:
white = [255, 255, 255]
light = False
def raise_windows(*args):
hwnd = HWND
SetWindowPos = windll.user32.SetWindowPos
if pos_config == "bottom":
w, h = winpos, screensize[1] - taskbar - int(HEIGHT)
elif pos_config == "top":
w, h = winpos, taskbar
elif pos_config == "right":
w, h = winpos - taskbar, screensize[1] - HEIGHT
elif pos_config == "left":
w, h = taskbar, screensize[1] - HEIGHT
SetWindowPos(hwnd, -1, w, h, 0, 0, 0x0001)
"""
try:
win32gui.ShowWindow(HWND, 5)
win32gui.SetForegroundWindow(HWND)
except Exception as e:
logger.exception("Exception occurred - cannot raise window")
"""
# import gettext
# zh = gettext.translation('manager', localedir='locale', languages=['zh'])
# zh.install()
# _ = #zh.gettext
_ = lambda s: s
default_font = asset_dir + "SegUIVar.ttf"#"segoeui.ttf"
# default_font = asset_dir + "NotoSans-Regular.ttf"#"msyh.ttc"
if "--r" not in args:
os.environ["PBR_VERSION"] = "4.0.2"
import singleton
try:
instance = singleton.SingleInstance()
except singleton.SingleInstanceException:
print("quit")
try:
def windowEnumerationHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
results = []
top_windows = []
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
if "gwsl dashboard" in i[1].lower():
win32gui.ShowWindow(i[0], 5)
win32gui.SetForegroundWindow(i[0])
break
except Exception as e:
logger.exception("Exception occurred - cannot raise window")
sys.exit()
except PermissionError:
print("quit")
try:
def windowEnumerationHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
results = []
top_windows = []
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
if "gwsl dashboard" in i[1].lower():
win32gui.ShowWindow(i[0], 5)
win32gui.SetForegroundWindow(i[0])
break
except Exception as e:
logger.exception("Exception occurred - cannot raise window")
pass
sys.exit()
try:
from win10toast import ToastNotifier
toaster = ToastNotifier()
dd = [random.randrange(0, 8), random.randrange(0, 8), random.randrange(0, 8)] # pick a random date to ask for donations
# DISPLAY ones
import OpticUI as ui
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "4.0.2"
import pygame, webbrowser
# print("whoops")
import animator as anima
from pygame.locals import *
t = time.perf_counter()
import pygame.gfxdraw
ui.init("dpi") # , tk, root)
from ctypes import wintypes, windll
if int(platform.release()) >= 8:
ctypes.windll.shcore.SetProcessDpiAwareness(True)
from win32api import GetMonitorInfo, MonitorFromPoint
from pathlib import Path
monitor_info = GetMonitorInfo(MonitorFromPoint((0, 0)))
monitor_area = monitor_info.get("Monitor")
work_area = monitor_info.get("Work")
taskbar = int(monitor_area[3] - work_area[3])
pos_config = "bottom" # loc of taskbar
if work_area[1] != 0:
taskbar = work_area[1]
pos_config = "top"
elif work_area[0] != 0:
taskbar = work_area[0]
pos_config = "left"
elif work_area[2] != monitor_area[2]:
taskbar = monitor_area[2] - work_area[2]
pos_config = "right"
else:
taskbar = int(monitor_area[3] - work_area[3])
pos_config = "bottom"
ui.set_scale(1)
# pygame init takes a long time...
# pygame.display.init()
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
WIDTH, HEIGHT = ui.inch2pix(3.8), ui.inch2pix(5.7) ##ui.inch2pix(7.9), ui.inch2pix(5)
if pos_config == "top":
winpos = screensize[0] - WIDTH
winh = taskbar - HEIGHT
elif pos_config == "bottom":
winpos = screensize[0] - WIDTH
winh = screensize[1]
elif pos_config == "right":
winpos = screensize[0] - WIDTH
winh = screensize[1]
elif pos_config == "left":
winpos = taskbar
winh = screensize[1]
sett = iset.read()
try:
start_menu = sett["general"]["start_menu_mode"]
except:
start_menu = False
if start_menu == True:
if pos_config == "top":
winpos = 0
winh = taskbar - HEIGHT
elif pos_config == "bottom":
winpos = 0
winh = screensize[1]
elif pos_config == "right":
winpos = screensize[0] - WIDTH
winh = screensize[1]
elif pos_config == "left":
winpos = taskbar
winh = screensize[1]
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (winpos, winh) # screensize[1] - taskbar)
py_root = pygame.display.set_mode([WIDTH, HEIGHT], NOFRAME)
HWND = pygame.display.get_wm_info()["window"]
keyboard.add_hotkey('alt+ctrl+g', raise_windows)#, args=HWND)
# win32gui.MoveWindow(HWND, screensize[0] - WIDTH, screensize[1] - taskbar - HEIGHT, WIDTH, HEIGHT, True)
canvas = pygame.Surface([WIDTH, HEIGHT]) # , pygame.SRCALPHA)
try:
win32gui.ShowWindow(HWND, 5)
win32gui.SetForegroundWindow(HWND)
except:
pass
ui.set_size([WIDTH, HEIGHT])
pygame.display.set_caption("GWSL Dashboard")
ui.start_graphics(pygame, asset_dir)
ico = pygame.image.load(asset_dir + "icon.png").convert_alpha()
pygame.display.set_icon(ico)
fpsClock = pygame.time.Clock()
lumen_opac = 6
# light_source = pygame.image.load(asset_dir + "lumens/7.png").convert_alpha()
#sync, clock, link, laptop, invalid/failed circle,
icons_old = {"refresh":"", "clock":"", "link":"",
"laptop":"", "error":"", "settings":"", "app_list":"",
"shell":"", "network":"", "heart":"", "question":"",
"plus":"", "minus":"", "x":"", "check":"", "dbus_config":"",
"theme":"", "discord":"", "export":"", "folder":""}
#these are all 24 weight
icons = {"refresh":"", "clock":"", "link":"",
"laptop":"", "error":"", "settings":"", "app_list":"",
"shell":"", "network":"", "heart":"", "question":"",#oldshell
"plus":"", "minus":"", "x":"", "check":"", "dbus_config":"",
"theme":"", "discord":"", "export":"", "folder":""}
ico_font = asset_dir + "SEGMDL2.TTF"
modern = True
if modern == True:
ico_font = asset_dir + "segoefluent.ttf"#"SEGMDL2.TTF"
if "fluent" not in ico_font:
icons = icons_old
# lumen = pygame.Surface([WIDTH, HEIGHT], SRCALPHA).convert_alpha()
# mask = pygame.Surface([WIDTH, HEIGHT], SRCALPHA).convert_alpha()
# mask.fill([255, 0, 0])
# pay = pygame.image.load(asset_dir + "paypal.png").convert_alpha()
# pay = pygame.transform.smoothscale(pay, [ui.inch2pix(1), int((pay.get_height() / pay.get_width()) * ui.inch2pix(1))])
back = pygame.Surface([WIDTH, HEIGHT]) # mini1.copy()
def get_pos():
rect = win32gui.GetWindowRect(HWND)
return [int(rect[0]), int(rect[1])]
poser = get_pos()
back = pygame.transform.scale(back, screensize)
accent = ui.get_color()
get_system_light()
fuchsia = [12, 222, 123]
# Set window transparency color
hwnd = HWND
long = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
long | win32con.WS_EX_LAYERED)
#win32con.WS_BORDER
#win32gui.SetLayeredWindowAttributes(HWND, win32api.RGB(*[100, 100, 100]), int(255), win32con.LWA_COLORKEY)
#region = win32gui.CreateRoundRectRgn(0, 0, WIDTH, HEIGHT, 20, 20)
#win32gui.SetWindowRgn(hwnd, region, True)
import rounder
if rounder.round(HWND) == True:
pad = ui.inch2pix(0.14)
fade = False
else:
pad = 0
fade = True
if start_menu == True:
padx = -1 * pad
else:
padx = pad
sett = iset.read()
try:
acrylic = sett["general"]["acrylic_enabled"]
except Exception as e:
logger.exception("Exception occurred - Please reset settings")
acrylic = True
if acrylic == True:
import blur
blur.blur(HWND)
else:
try:
mini1 = pygame.image.load(os.getenv('APPDATA') + r"\Microsoft\Windows\Themes\TranscodedWallpaper").convert()
except:
mini1 = pygame.Surface(screensize)
back = mini1.copy()
back = pygame.transform.scale(back, screensize)
hide = sett["general"]["hide_donation_reminder"]
show_donate = not hide
except Exception as e:
logger.exception("Exception occurred - Cannot Init Display")
def get_version(machine):
try:
machines = os.popen("wsl.exe -l -v").read() # lines()
machines = re.sub(r'[^a-z A-Z0-9_./\n-]', r'', machines).splitlines()
#machines = machines.splitlines()
machines2 = []
wsl_1 = True
for i in machines:
b = ''.join(i).split()
if 'VERSION' in b:
wsl_1 = False
if 'NAME' not in b and b != [] and b != None:
machines2.append(b)
if wsl_1 == True:
print("assuming wsl 1")
return 1
for i in machines2:
if i[0] == machine:
return int(i[2])
return 1
except:
return 1
def reboot(machine):
"""
Reboots WSL instance
:param machine:
:return:
"""
os.popen("wsl.exe -t " + str(machine))
time.sleep(1)
os.popen("wsl.exe -d " + str(machine))
def helper(topic):
"""
Build URL for specified topic
:param topic:
:return:
"""
if topic == "machine chooser":
url = "the-gwsl-user-interface"
elif topic == "configure":
url = "configuring-a-wsl-distro-for-use-with-gwsl"
elif topic == "theme":
url = "configuring-a-wsl-distro-for-use-with-gwsl"
elif topic == "launcher":
url = "using-the-integrated-linux-app-launcher"
webbrowser.get('windows-default').open("https://opticos.github.io/gwsl/tutorials/manual.html#" + str(url))
def help_short():
"""
Open help page on shortcut creator in browser
:return:
"""
webbrowser.get('windows-default').open(
"https://opticos.github.io/gwsl/tutorials/manual.html#using-the-gwsl-shortcut-creator")
def help_ssh():
"""
Open help page on using GWSL with SSH
:return:
"""
webbrowser.get('windows-default').open("https://opticos.github.io/gwsl/tutorials/manual.html#using-gwsl-with-ssh")
def wsl_run(distro, command, caller, nolog=False):
"""
One Run to Rule Them All... nvm
"""
cmd = "wsl.exe ~ -d " + str(distro) + " . ~/.profile;nohup /bin/sh -c " + '"' + str(command) + '&"'
if nolog == False:
logger.info(f"(runos) WSL SHELL $ {cmd}")
#logger.info(f"WSL OUTPUT > {out}")
#subprocess.Popen(cmd, shell=True)
#print(caller, cmd)
run = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
universal_newlines=True
)
out = str(run.stdout.read().rstrip())
#print(out)
return out
#return out
def runs(distro, command, nolog=False):
cmd = "wsl.exe ~ -d " + str(distro) + " . ~/.profile;nohup /bin/sh -c " + '"' + str(command) + '&"'
if nolog == False:
logger.info(f"(runos) WSL SHELL $ {cmd}")
subprocess.Popen(cmd,
shell=True) # .readlines()
#print("runs. it would be", cmd)
return None
#return wsl_run(distro, command, "runs")
def run(distro, command, nolog=False):
#"""
cmd = "wsl.exe ~ -d " + str(distro) + " . ~/.profile;nohup /bin/sh -c " + '"' + str(command) + '&"'
#old out = subprocess.getoutput(cmd) # .readlines()
out = subprocess.check_output(cmd, shell=True, errors="ignore")
if nolog == False:
logger.info(f"(run) WSL SHELL $ {cmd}")
logger.info(f"WSL OUTPUT > {out}")
#print("run. it would be", cmd)
return out
#"""
#return wsl_run(distro, command, "run")
def start_dbus(distro):
command = "/etc/init.d/dbus start"
cmd = "wsl.exe ~ -d " + str(distro) + " /bin/sh -c " + '"' + str(command) + '"'
try:
out = subprocess.getoutput(cmd)
except:
out = ""
return out
def runo3(distro, command, nolog=False):
#"""
cmd = "wsl.exe ~ -d " + str(distro) + " . ~/.profile;/bin/sh -c " + '"' + str(command) + '"'
out = subprocess.getoutput(cmd) # .readlines()
if nolog == False:
logger.info(f"(runo3) WSL SHELL $ {cmd}")
logger.info(f"WSL OUTPUT > {out}")
#print("runo3. it would be", cmd)
return out
#"""
#return wsl_run(distro, command, "runo3")
def runo2(distro, command, nolog=False):
#"""
cmd = "wsl.exe -d " + str(distro) + ' ' + "/bin/sh -c " + '"' + str(command) + '"'
out = os.popen(cmd).readlines()
if nolog == False:
logger.info(f"(runo2) WSL SHELL $ {cmd}")
logger.info(f"WSL OUTPUT > {out}")
#print("runo2. it would be", cmd)
return out
#"""
#return wsl_run(distro, command, "runo2")
""" obselete
def runo(distro, command):
cmd = "wsl.exe -d " + str(distro) + " /bin/sh -c " + '"' + str(command) + '"'
out = os.popen(cmd).readlines()
logger.info(f"(runo) WSL SHELL $ {cmd}")
logger.info(f"WSL OUTPUT > {out}")
return out
"""
def get_ip(machine):
"""
Get IP of select WSL instance
:return:
"""
#print("get_ip")
cmd = "wsl.exe -d " + str(machine) + ' ' + "/bin/sh -c " + '"' + """(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}')""" + '"'
#print(cmd)
result = os.popen(cmd).readlines()[0]
try:
result = result.rstrip()
except:
pass
if "nameserver" in result:
result = result[len("nameserver") + 1:]
try:
ipa = ipaddress.ip_address(result)
except:
cmd = "wsl.exe -d " + str(machine) + ' ' + "/bin/sh -c " + '"' + """echo $(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}')""" + '"'
result = os.popen(cmd).readlines()[0]
#result = "localhost"
#print("ipa", ipa, "ipd")
#result = runo3(machine, """echo $(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}')""")
#print("ip", result, "done")
return result # [0][:-1]
def test_x():
"""
Test the VCXSRV config by launching xclock
:return:
"""
subprocess.Popen("VCXSRV/xclock -display localhost:0")
def choose_machine():
"""
Builds the choose machine menu
:return:
"""
global selected, canvas, WIDTH, HEIGHT, mini, back, lumen, mask
machines = os.popen("wsl.exe -l -q").read() # lines()
machines = re.sub(r'[^a-zA-Z0-9_./\n-]', r'', machines).splitlines()
machines[:] = (value for value in machines if value != "")
# Hide this if wsl not installed?
if "CopyrightcMicrosoftCorporation.All".lower() in str(machines).lower():
machines = []
print("no wsl")
sett = iset.read()
avoid = sett["distro_blacklist"]
docker_blacklist = []
for i in machines:
for a in avoid:
if str(a).lower() in str(i).lower():
docker_blacklist.append(i)
for i in docker_blacklist:
machines.remove(i)
if len(machines) == 1:
return machines[0]
elif len(machines) > 7:
if len(machines) != 23:
return pymsgbox.confirm(text=_('Select a WSL Machine'), title=_('Choose WSL Machine'), buttons=machines)
else:
machines = []
animator.animate("choose", [100, 0])
machine = False
b = pygame.Surface([WIDTH, HEIGHT])
draw(b)
while True:
mouse = False
if win32gui.GetFocus() != HWND:
if animator.get("start")[0] == 100:
animator.animate("start", [0, 0])
animator.animate("start2", [0, 0])
break
# if animator.get("start")[0] == 0:
# pygame.quit()
# sys.exit()
for event in pygame.event.get():
if event.type == QUIT:
# subprocess.getoutput('taskkill /F /IM GWSL_service.exe')
# subprocess.getoutput('taskkill /F /IM GWSL_vcxsrv.exe')
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
mouse = event.pos
elif event.type == VIDEORESIZE:
WIDTH, HEIGHT = event.size
if WIDTH < ui.inch2pix(7.9):
WIDTH = ui.inch2pix(7.9)
if HEIGHT < ui.inch2pix(5):
HEIGHT = ui.inch2pix(5)
canvas = pygame.display.set_mode([WIDTH, HEIGHT], RESIZABLE)
# ui.set_size([WIDTH, HEIGHT])
# mini = pygame.image.load(bak).convert()
back = mini.copy()
back = pygame.transform.scale(back, [WIDTH, HEIGHT])
ui.iris2(back, [0, 0],
[WIDTH, HEIGHT],
[0, 0, 0], radius=10, shadow_enabled=False, resolution=50)
# mini = pygame.transform.smoothscale(mini, [display.get_width() - ui.inch2pix(0.1), ui.inch2pix(0.55)])
mini = pygame.transform.smoothscale(mini1, [display.get_width() - ui.inch2pix(0.1), ui.inch2pix(0.55)])
b = pygame.Surface([WIDTH, HEIGHT])
draw(b)
lumen = pygame.Surface([WIDTH, HEIGHT], SRCALPHA).convert_alpha()
# mask = pygame.Surface([WIDTH, HEIGHT], SRCALPHA).convert_alpha()
# mask.fill([255, 0, 0])
canvas.blit(b, [0, 0])
v = animator.get("choose")[0] / 100
# canvas.fill([0, 0, 0, int((1 - v) * 255)])
ui.iris2(canvas, [0, 0],
[WIDTH, HEIGHT],
False, radius=10, shadow_enabled=False, resolution=30, alpha=int(v * 255))
if light == False:
pygame.gfxdraw.rectangle(canvas, [0, 0, WIDTH, HEIGHT + 1], [100, 100, 100, int(v*100)])
else:
pygame.gfxdraw.rectangle(canvas, [0, 0, WIDTH, HEIGHT + 1], [255, 255, 255, int(v*80)])
pygame.gfxdraw.rectangle(canvas, [0, 0, WIDTH, HEIGHT + 1], [0, 0, 0, int(v*80)])
# pygame.gfxdraw.box(canvas, [0, 0, WIDTH, HEIGHT], [0, 0, 0] + [int(v * 180)])
title_font = ui.font(default_font, int(ui.inch2pix(0.21)))
if len(machines) != 0:
txt = title_font.render(_("Choose A WSL Distro:"), True, white)
else:
txt = title_font.render(_("No WSL Distros Installed."), True, white)
txt.set_alpha(int(v * 255))
canvas.blit(txt, [WIDTH / 2 - txt.get_width() / 2, ui.inch2pix(0.5) - int(ui.inch2pix(0.1) * (v))])
title_font = ui.font(default_font, int(ui.inch2pix(0.19)))
txt = title_font.render("?", True, white)
txt.set_alpha(int(v * 255))
canvas.blit(txt,
[WIDTH - txt.get_width() - ui.inch2pix(0.3), ui.inch2pix(0.2) - int(ui.inch2pix(0.1) * (1 - v))])
hover = pygame.mouse.get_pos()
if hover[0] > WIDTH - txt.get_width() - ui.inch2pix(0.4) and hover[0] < WIDTH - ui.inch2pix(0.1):
if hover[1] > ui.inch2pix(0.1) and hover[1] < ui.inch2pix(0.3) + txt.get_height() - int(
ui.inch2pix(0.1) * (1 - v)):
if mouse != False:
helper("machine chooser")
d = ui.inch2pix(0.2)
h = ui.inch2pix(0.8) + txt.get_height() + ui.inch2pix(0.25)
title_font = ui.font(default_font, int(ui.inch2pix(0.19)))
# title_font.bold = True
selected = False
if len(machines) != 0:
for i in machines:
s2 = False
ni = i[0].upper() + i[1:]
ni = ni.replace("-", " ")
ni = ni.replace("_", " ")
txt = title_font.render(ni, True, white)
if hover[0] > (WIDTH / 2) - (txt.get_width() / 2) - ui.inch2pix(0.2) and hover[0] < (WIDTH / 2) - (
txt.get_width() / 2) + txt.get_width() + ui.inch2pix(0.2):
if hover[1] > h - ui.inch2pix(0.1) - int(v * d) + 1 and hover[
1] < h + txt.get_height() + ui.inch2pix(0.1) - int(v * d):
if mouse != False:
machine = i
animator.animate("choose", [0, 0])
selected = True
s2 = True
s = animator.get("select")[0] / 100
if s2 == False:
txt.set_alpha(int(v * 255))
else:
txt.set_alpha(int((1 - s) * v * 255))
canvas.blit(txt, [WIDTH / 2 - txt.get_width() / 2, h - int(v * d)])
if s2 == True:
txt = title_font.render(ni, True, accent)
txt.set_alpha(int((s) * v * 255))
canvas.blit(txt, [WIDTH / 2 - txt.get_width() / 2, h - int(v * d)])
h += ui.inch2pix(0.3) + txt.get_height()
d += ui.inch2pix(0.1)
if selected == True:
animator.animate("select", [100, 0])
else:
animator.animate("select", [0, 0])
txt = title_font.render(_("Cancel"), True, white)
txt.set_alpha(int(v * 255))
canvas.blit(txt, [WIDTH / 2 - txt.get_width() / 2, HEIGHT - ui.inch2pix(0.2) - txt.get_height() - int(v * d)])
if mouse != False:
if mouse[0] > WIDTH / 2 - txt.get_width() / 2 - ui.inch2pix(0.2) and mouse[
0] < WIDTH / 2 - txt.get_width() / 2 + txt.get_width() + ui.inch2pix(0.2):
if mouse[1] > HEIGHT - ui.inch2pix(0.2) - txt.get_height() - ui.inch2pix(0.1) - int(v * d) and mouse[
1] < HEIGHT - ui.inch2pix(0.2) - txt.get_height() + txt.get_height() + ui.inch2pix(0.1) - int(
v * d):
machine = None
animator.animate("choose", [0, 0])
fpsClock.tick(60)
animator.update()