forked from cascadium/wsl-windows-toolbar-launcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsl_windows_toolbar.py
executable file
·571 lines (507 loc) · 22.5 KB
/
wsl_windows_toolbar.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
#!/usr/bin/env python3
import os
import logging
import shutil
import subprocess
import sys
import glob
import magic
from platform import uname
import click
from PIL import Image
# Set up default logging format and level
import xdg.Menu
import xdg.IconTheme
from click import confirm
from jinja2 import Environment, PackageLoader, FileSystemLoader
logging.basicConfig(level=logging.INFO, format='%(asctime)s[%(levelname)s]: %(message)s')
logger = logging.getLogger(__name__)
# Pre-run checks up here
if uname().system.upper() != "LINUX" or "MICROSOFT" not in uname().release.upper():
logger.error("WSL Linux environment required (detected: %s [%s])",
uname().system,
uname().release)
exit(1)
# Check required tools are available
for exe in ["cmd.exe", "attrib.exe", "powershell.exe", "wscript.exe", "wslpath"]:
# Just check for non zero return codes
logger.debug("Checking availability of %s...", exe)
try:
proc = subprocess.check_output(["which", exe])
logger.debug("Found: %s", proc.rstrip().decode())
except subprocess.CalledProcessError:
logger.error("The %s application must be in the current user's executable $PATH.", exe)
sys.exit(os.EX_UNAVAILABLE)
PROC_MOUNTS = "/proc/mounts"
DEFAULT_HOST_MOUNTPOINT = "/mnt/c"
if os.path.exists(PROC_MOUNTS):
with open(PROC_MOUNTS) as mount_fh:
for mount in mount_fh.readlines():
fs, mp, typ, opts, dump, pas = mount.rstrip().split()
if typ in ["drvfs", "9p"]:
DEFAULT_HOST_MOUNTPOINT = mp
WINDOWS_USERPROFILE = subprocess.check_output(
["cmd.exe", "/C", "echo", "%USERPROFILE%"],
stderr=subprocess.DEVNULL
).rstrip().decode("utf-8")
WSL_USERPROFILE = subprocess.check_output(
["wslpath", WINDOWS_USERPROFILE]
).rstrip().decode("utf-8")
WINDOWS_USERAPPDATA = subprocess.check_output(
["cmd.exe", "/C", "echo", "%APPDATA%"],
stderr=subprocess.DEVNULL
).rstrip().decode("utf-8")
WSL_USERAPPDATA = subprocess.check_output(
["wslpath", WINDOWS_USERAPPDATA]
).rstrip().decode("utf-8")
# Install in the start menu
DEFAULT_INSTALL_DIRECTORY = os.path.join(
WSL_USERAPPDATA, "Microsoft", "Windows", "Start Menu", "Programs", "WSL Windows Toolbar")
# Install metadata in our local .config directory
DEFAULT_METADATA_DIRECTORY = os.path.join(
WSL_USERPROFILE, ".config", "wsl-windows-toolbar-launcher/metadata")
# Default order of preference for menu selection
MENU_PREFERENCES = ["gnome", "xfce", "kf5"]
DEFAULT_MENU_LOCATION = "/etc/xdg/menus"
MENUS_AVAILABLE = glob.glob("%s/*-applications.menu" % DEFAULT_MENU_LOCATION)
DEFAULT_MENU_FILE = None
# Prefer these as defaults if available
for menu_type in MENU_PREFERENCES:
menu_file_name = "/etc/xdg/menus/%s-applications.menu" % menu_type
if menu_file_name in MENUS_AVAILABLE:
DEFAULT_MENU_FILE = menu_file_name
break
# Otherwise prefer the first one available
if DEFAULT_MENU_FILE is None and len(MENUS_AVAILABLE) > 0:
DEFAULT_MENU_FILE = MENUS_AVAILABLE[0]
DEFAULT_METADATA_DIRECTORY = os.path.join(
WSL_USERPROFILE, ".config", "wsl-windows-toolbar-launcher/metadata")
FREEDESKTOP_FIELD_CODES = [
"%f",
"%F",
"%u",
"%U",
"%d",
"%D",
"%n",
"%N",
"%i",
"%c",
"%k",
"%v",
"%m"
]
# Default environment detection for optional extras
has_cairosvg = False
has_imagemagick = False
try:
from cairosvg import svg2png
has_cairosvg = True
except ImportError:
logger.warning("Could not find cairosvg - will not be able to convert svg ")
pass
try:
if 'ImageMagick' in subprocess.check_output(["convert", "-version"]).rstrip().decode():
has_imagemagick = True
except Exception:
logger.warning("Could not find imagemagick - some xpm icons may not convert correctly")
pass
@click.command()
@click.option("--install-directory",
"-i",
type=click.Path(),
default=DEFAULT_INSTALL_DIRECTORY,
show_default=False,
help="Install the launchers here [default: %s]" % DEFAULT_INSTALL_DIRECTORY)
@click.option("--metadata-directory",
"-m",
type=click.Path(),
default=DEFAULT_METADATA_DIRECTORY,
show_default=False,
help="Install any metadata here [default: %s]" % DEFAULT_METADATA_DIRECTORY)
@click.option("--distribution",
"-d",
type=str,
default=os.environ['WSL_DISTRO_NAME'],
show_default=False,
help="WSL Distro to generate shortcuts for [default: $WSL_DISTRO_NAME]")
@click.option("--user",
"-u",
type=str,
default=os.environ['USER'],
show_default=False,
help="WSL Distro's user to launch programs as [default: $USER]")
@click.option("--confirm-yes",
"-y",
is_flag=True,
default=False,
show_default=True,
help="Assume the answer to all confirmation prompts is 'yes'")
@click.option("--menu-file",
"-f",
type=click.File('r'),
default=DEFAULT_MENU_FILE,
show_default=True,
help="The *.menu menu file to parse")
@click.option("--wsl-executable",
"-w",
type=str,
default="C:\\Windows\\System32\\wsl.exe",
show_default=True,
help="Path to the WSL executable relative to the windows installation")
@click.option("--target-name",
"-n",
type=str,
default="WSL",
show_default=True,
help="Name to give to the created installation (will be displayed in toolbar menu)")
@click.option("--preferred-theme",
"-t",
type=str,
default="Adwaita",
show_default=True,
help="Preferred menu theme to use")
@click.option("--alternative-theme",
"-T",
type=str,
default=[
"Papirus",
"Humanity",
"elementary-xfce"
],
show_default=True,
multiple=True,
help="Alternative menu themes to consider (pass multiple times)")
@click.option("--jinja-template-batch",
"-j",
type=click.File('r'),
default=None,
show_default=False,
help="Optional Jinja template to use instead of the inbuilt default (advanced users only)")
@click.option("--jinja-template-shell",
"-J",
type=click.File('r'),
default=None,
show_default=False,
help="Optional Jinja template to use instead of the inbuilt default (advanced users only)")
@click.option("--rc-file",
"-r",
type=click.File('r'),
default=os.path.expanduser("~/.bashrc"),
show_default=False,
help="Optional rc file to source prior to launching the command instead of ~/.bashrc")
@click.option("--launch-directory",
"-D",
type=click.Path(exists=True, file_okay=False),
default=os.path.expanduser("~"),
show_default=False,
help="Optional default linux path to open applications relative to (defaults to ~)")
@click.option("--batch-encoding",
"-E",
type=str,
default=None,
show_default=False,
help="Optional batch file output encoding (defaults to None)")
@click.option("--use-batch-newline-crlf",
"-N",
is_flag=True,
default=False,
show_default=False,
help="Optional use batch file newline value CRLF (defaults to False)")
@click.option("--shortcut-suffix",
"-s",
type=str,
default=None,
show_default=False,
help="String to add to end of shortcut name (defaults to ' (target name)')")
def cli(install_directory,
metadata_directory,
distribution,
user,
confirm_yes,
menu_file,
wsl_executable,
target_name,
preferred_theme,
alternative_theme,
jinja_template_batch,
jinja_template_shell,
rc_file,
launch_directory,
batch_encoding,
use_batch_newline_crlf,
shortcut_suffix):
# Debug information
logger.info("distribution = '%s'", distribution)
logger.info("user = '%s'", user)
logger.info("confirm_yes = %s", confirm_yes)
logger.info("menu_file = '%s'", menu_file.name if menu_file else None)
logger.info("wsl_executable = '%s'", wsl_executable)
logger.info("target_name = '%s'", target_name)
logger.info("preferred_theme = '%s'", preferred_theme)
logger.info("alternative_theme = '%s'", alternative_theme)
logger.info("jinja_template_batch = '%s'", jinja_template_batch.name if jinja_template_batch else None)
logger.info("jinja_template_shell = '%s'", jinja_template_shell.name if jinja_template_shell else None)
logger.info("rc_file = '%s'", rc_file.name)
logger.info("has_imagemagick = %s", has_imagemagick)
logger.info("has_cairosvg = %s", has_cairosvg)
logger.info("launch_directory = '%s'", launch_directory)
logger.info("batch_encoding = '%s'", batch_encoding)
logger.info("use_batch_newline_crlf = %s", use_batch_newline_crlf)
if shortcut_suffix is None:
shortcut_suffix = " (%s)" % target_name
logger.info("shortcut_suffix = '%s'", shortcut_suffix)
# Add distro to directory names, since we want to support multiple concurrent distributions
install_directory = os.path.join(install_directory, target_name)
metadata_directory = os.path.join(metadata_directory, target_name)
# OK print it debug information for these now
logger.info("install_directory = '%s'", install_directory)
logger.info("metadata_directory = '%s'", metadata_directory)
if not menu_file:
logger.error(
"Could not find an appropriate .menu file in %s - perhaps yum/apt install gnome-menus or another desktop?",
DEFAULT_MENU_LOCATION
)
sys.exit(os.EX_OSFILE)
if not confirm_yes:
logger.info("For full list of options available, call script again with --help")
logger.info("This script will write to the above locations if it can, but giving final chance to chicken out.")
confirm("Press <enter> to continue or ctrl+c to abort.")
# OK we're ready to go - ensure we can create / have write access to the installation directory
try:
# Create directory and fear not if it already exists
os.makedirs(install_directory, exist_ok=True)
os.makedirs(metadata_directory, exist_ok=True)
except PermissionError:
logger.error("No permissions to create directories %s or %s - aborting", install_directory, metadata_directory)
sys.exit(os.EX_NOPERM)
# Make metadata a hidden system file to hide it from indexer (cleaner search results for powertoys etc)
set_hidden_from_indexer(metadata_directory)
# Check we have absolute ownership of this directory - if not, chicken out
if not is_directory_writable(install_directory):
logger.error("Could not confirm write access to all contents of %s - aborting", install_directory)
sys.exit(os.EX_NOPERM)
# Find all desktop menu items, indexed by menu path
menu = xdg.Menu.parse(menu_file.name)
entries = get_desktop_entries(menu)
# Create shortcut launcher script (avoids terminal being displayed while launching)
silent_launcher_script_file = os.path.join(metadata_directory, "silent-launcher.vbs")
if not os.path.exists(silent_launcher_script_file):
try:
with open(silent_launcher_script_file, "w") as lsf:
# If this gets more complicated, we could make this a resource, but at one line, this is fine
lsf.write('CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False')
except Exception:
logger.error("Could not create %s", silent_launcher_script_file)
sys.exit(os.EX_IOERR)
# Build windows path for the launcher script
silent_launcher_script_file_win = get_windows_path_from_wsl_path(silent_launcher_script_file)
# Load in the template which is used to generate the launcher script
if not jinja_template_batch:
# Default load from package
env = Environment(loader=PackageLoader('wsl_windows_toolbar', package_path=''))
batch_template = env.get_template("wsl-windows-toolbar-template.bat.j2")
shell_template = env.get_template("wsl-windows-toolbar-template.sh.j2")
else:
# Optionally load from custom filesystem location
env = Environment(loader=FileSystemLoader(os.path.dirname(os.path.abspath(jinja_template_batch.name))))
batch_template = env.get_template(os.path.basename(jinja_template_batch.name))
shell_template = env.get_template(os.path.basename(jinja_template_shell.name))
# Create shortcut files
shortcuts_installed = 0
for path, entry in entries.items():
logger.info("Creating menu item for: %s", path)
exec_cmd = entry.getExec()
# https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#key-path
exec_dir = entry.getPath()
# https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#key-terminal
run_in_terminal = entry.getTerminal()
if not exec_dir:
exec_dir = launch_directory
# These parts aren't relevant for menu launcher so prune out from the command
for substr in FREEDESKTOP_FIELD_CODES:
exec_cmd = exec_cmd.replace(substr, "")
# Carve the way for the shortcut
if shortcut_suffix is None:
shortcut_path = os.path.join(install_directory, "%s.lnk" % path)
else:
shortcut_path = os.path.join(install_directory, "%s%s.lnk" % (path, shortcut_suffix))
os.makedirs(os.path.dirname(shortcut_path), exist_ok=True)
logger.debug("Will create shortcut file: %s", shortcut_path)
# Normalize the icon to a windows path so shortcut can find it
icon = entry.getIcon()
metadata_prefix = os.path.join(metadata_directory, "%s" % path)
ico_file_winpath = create_windows_icon(
icon if icon else entry.getName().lower(),
metadata_prefix,
preferred_theme=preferred_theme,
alternative_theme=alternative_theme
)
shell_launcher_path = os.path.join(metadata_directory, "%s.sh" % path)
template_dict = {
"distribution": distribution,
"user": user,
"command": exec_cmd,
"wsl": wsl_executable,
"rcfile": rc_file.name,
"launch_script": shell_launcher_path,
"exec_dir": exec_dir,
"run_in_terminal": run_in_terminal
}
# Create a little shell launcher for the executable
with open(shell_launcher_path, mode="w") as script_handle:
script_handle.write(shell_template.render(template_dict))
# Make executable
os.chmod(shell_launcher_path, 509)
set_hidden_from_indexer(shell_launcher_path)
# Create a little batch file launcher for the executable
batch_launcher_path = os.path.join(metadata_directory, "%s.bat" % path)
batch_newline = "\r\n" if use_batch_newline_crlf else None
with open(batch_launcher_path, mode="w", encoding=batch_encoding, newline=batch_newline) as script_handle:
script_handle.write(batch_template.render(template_dict))
batch_launcher_path_win = get_windows_path_from_wsl_path(batch_launcher_path)
if run_in_terminal:
windows_lnk = create_shortcut(
shortcut_path,
batch_launcher_path_win,
comment=entry.getComment(),
icon_file=ico_file_winpath
)
else:
windows_lnk = create_shortcut(
shortcut_path,
"wscript",
'"%s" "%s"' % (silent_launcher_script_file_win, batch_launcher_path_win),
comment=entry.getComment(),
icon_file=ico_file_winpath
)
set_hidden_from_indexer(batch_launcher_path)
logger.debug("Created %s", windows_lnk)
shortcuts_installed += 1
logger.info("Finished creating %d shortcuts!", shortcuts_installed)
logger.info("Before raising an issue, make sure you have Xming / X410 etc set up in your .bashrc.")
logger.info(
"Right click on the toolbar, then select Toolbars -> New toolbar... and select the directory '%s'.",
install_directory
)
def get_windows_path_from_wsl_path(path):
return "%s\\%s" % (
subprocess.check_output(["wslpath", "-w", "-a", os.path.dirname(path)]).rstrip().decode(),
os.path.basename(path)
)
def create_shortcut(link_file, executable, arguments="", comment="", icon_file=""):
windows_lnk = get_windows_path_from_wsl_path(link_file)
powershell_cmd = "powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile "
powershell_cmd += "-Command '"
powershell_cmd += '$ws = New-Object -ComObject WScript.Shell; '
powershell_cmd += '$s = $ws.CreateShortcut("%s");' % windows_lnk
powershell_cmd += '$s.TargetPath = "%s";' % executable
powershell_cmd += '$s.Arguments = "%s";' % arguments.replace('"', '`"')
powershell_cmd += '$s.Description = "%s";' % comment
powershell_cmd += '$s.WorkingDirectory = "%USERPROFILE%";'
powershell_cmd += '$s.IconLocation = "%s";' % icon_file
powershell_cmd += '$s.Save()'
powershell_cmd += "'"
logger.debug("Powershell command to create shortcut: %s", powershell_cmd)
os.popen(powershell_cmd).read().rstrip()
return windows_lnk
def set_hidden_from_indexer(path):
try:
subprocess.check_output(["attrib.exe", "+I", "+S", "+H", get_windows_path_from_wsl_path(path)])
logger.debug("Set hidden system attributes in metadata directory %s", path)
except subprocess.CalledProcessError:
logger.exception("Failed to set hidden system attributes in metadata directory %s", path)
def create_windows_icon(icon,
metadata_prefix,
preferred_theme=None,
alternative_theme=None):
logger.debug("Creating icon files for: %s, %s [%s]", icon, metadata_prefix, preferred_theme)
os.makedirs(os.path.dirname(metadata_prefix), exist_ok=True)
icon_path = xdg.IconTheme.getIconPath(icon, theme=preferred_theme)
if not icon_path:
for icon_c in [icon, icon.lower()]:
if alternative_theme:
for theme in alternative_theme:
logger.debug("Checking with theme: %s", theme)
icon_path = xdg.IconTheme.getIconPath(icon_c, theme=theme)
if icon_path:
icon = icon_c
logger.debug("Found icon path: %s for theme %s", icon_c, theme)
break
if icon_path:
filename, extension = os.path.splitext(icon_path)
png_file = metadata_prefix + ".png"
mime_type = magic.from_file(icon_path, mime=True)
try:
# Some icons appear to have the wrong extension on windows, so check mime type here too
if extension == ".png" or mime_type == "image/png":
shutil.copyfile(icon_path, png_file)
elif has_cairosvg and (extension == ".svg" or mime_type == "image/svg"):
# Attempt with svg2png if available
with open(icon_path, 'rb') as f:
svg2png(file_obj=f, write_to=png_file)
else:
# Attempt with PIL if available
img = Image.open(icon_path)
img.save(png_file)
except Exception as e:
if has_imagemagick:
logger.debug("Could not convert using python methods - falling back on imagemagick")
try:
subprocess.check_output(["convert", icon_path, png_file], timeout=10)
logger.debug("Converted %s to %s using imagemagick", icon_path, png_file)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
logger.exception("Failed to create or find png file for %s - icon will not be available (%s: %s)",
icon_path, type(e).__name__, e)
png_file = None
if png_file:
try:
# Should have a png file available here now - convert to icon
img = Image.open(png_file)
ico_file = metadata_prefix + ".ico"
img.save(ico_file)
logger.debug("Successfully created %s", ico_file)
# Mark both icon and png as system
set_hidden_from_indexer(png_file)
set_hidden_from_indexer(ico_file)
return get_windows_path_from_wsl_path(ico_file)
except Exception:
logger.warning("Could not generate icon for %s", png_file)
else:
logger.warning("Failed to find icon file for %s", icon)
return None
def get_desktop_entries(menu, entries=None):
if entries is None:
entries = {}
for entry in menu.getEntries():
if isinstance(entry, xdg.Menu.Menu):
# Recurse subdirectory
get_desktop_entries(entry, entries)
elif isinstance(entry, xdg.Menu.MenuEntry):
# We are only interested in "Application" entries
if entry.DesktopEntry.getType() == "Application":
# Index desktop entry by path
if menu.getPath():
prefix = menu.getPath() + os.sep
else:
prefix = ""
entries[prefix + entry.DesktopEntry.getName()] = entry.DesktopEntry
return entries
def is_directory_writable(base_path):
writable = True
# Check the directory is writable
if os.access(base_path, os.W_OK):
logger.debug("Can write to %s", base_path)
else:
writable = False
logger.error("Cannot write to %s", base_path)
for root, dirs, files in os.walk(base_path):
for path in dirs + files:
if os.access(base_path, os.W_OK):
logger.debug("Can write to %s", os.path.join(root, path))
else:
writable = False
logger.error("Cannot write to %s", os.path.join(root, path))
return writable
if __name__ == '__main__':
cli()