From 785d41e140efaaf10ab317a79bae21a4fd7bf39b Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 12 Apr 2020 08:51:11 -0700 Subject: [PATCH] launch menu: add fancy example for windows This commit adds some helper functions that make it possible to dynamically discover and add WSL distributions to the launcher menu. refs: https://github.com/wez/wezterm/issues/159 --- docs/config/launch.markdown | 59 +++++++++++++++++++++++++++++++++++++ docs/config/lua.markdown | 48 ++++++++++++++++++++++++++++++ src/scripting/mod.rs | 54 +++++++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+) diff --git a/docs/config/launch.markdown b/docs/config/launch.markdown index 5e675dad1..c60c810b2 100644 --- a/docs/config/launch.markdown +++ b/docs/config/launch.markdown @@ -103,3 +103,62 @@ return { Screenshot +Here's a fancy example that will add some helpful entries to the launcher +menu when running on Windows: + +```lua +local wezterm = require 'wezterm'; + +local launch_menu = {} + +if wezterm.target_triple == "x86_64-pc-windows-msvc" then + table.insert(launch_menu, { + label = "PowerShell", + args = {"powershell.exe", "-NoLogo"}, + }) + + -- Find installed visual studio version(s) and add their compilation + -- environment command prompts to the menu + for _, vsvers in ipairs(wezterm.glob("Microsoft Visual Studio/20*", "C:/Program Files (x86)")) do + local year = vsvers:gsub("Microsoft Visual Studio/", "") + table.insert(launch_menu, { + label = "x64 Native Tools VS " .. year, + args = {"cmd.exe", "/k", "C:/Program Files (x86)/" .. vsvers .. "/BuildTools/VC/Auxiliary/Build/vcvars64.bat"}, + }) + end + + -- Enumerate any WSL distributions that are installed and add those to the menu + local success, wsl_list, wsl_err = wezterm.run_child_process({"wsl.exe", "-l"}) + -- `wsl.exe -l` has a bug where it always outputs utf16: + -- https://github.com/microsoft/WSL/issues/4607 + -- So we get to convert it + wsl_list = wezterm.utf16_to_utf8(wsl_list) + + for idx, line in ipairs(wezterm.split_by_newlines(wsl_list)) do + -- Skip the first line of output; it's just a header + if idx > 1 then + -- Remove the "(Default)" marker from the default line to arrive + -- at the distribution name on its own + local distro = line:gsub(" %(Default%)", "") + + -- Add an entry that will spawn into the distro with the default shell + table.insert(launch_menu, { + label = distro .. " (WSL default shell)", + args = {"wsl.exe", "--distribution", distro}, + }) + + -- Here's how to jump directly into some other program; in this example + -- its a shell that probably isn't the default, but it could also be + -- any other program that you want to run in that environment + table.insert(launch_menu, { + label = distro .. " (WSL zsh login shell)", + args = {"wsl.exe", "--distribution", distro, "--exec", "/bin/zsh", "-l"}, + }) + end + end +end + +return { + launch_menu = launch_menu, +} +``` diff --git a/docs/config/lua.markdown b/docs/config/lua.markdown index dbafeed04..e10898517 100644 --- a/docs/config/lua.markdown +++ b/docs/config/lua.markdown @@ -252,3 +252,51 @@ for _, v in ipairs(wezterm.glob("/etc/*.conf")) do end ``` +### `wezterm.run_child_process(args)` + +*Since: nightly* + +This function accepts an argument list; it will attempt to spawn that command +and will return a tuple consisting of the boolean success of the invocation, +the stdout data and the stderr data. + +```lua +local wezterm = require 'wezterm'; + +local success, stdout, stderr = wezterm.run_child_process({"ls", "-l"}) +``` + +### `wezterm.split_by_newlines(str)` + +*Since: nightly* + +This function takes the input string and splits it by newlines (both `\n` and `\r\n` +are recognized as newlines) and returns the result as an array of strings that +have the newlines removed. + +```lua +local wezterm = require 'wezterm'; + +local example = "hello\nthere\n"; + +for _, line in ipairs(wezterm.split_by_newlines(example)) do + wezterm.log_error(line) +end +``` + +### `wezterm.utf16_to_utf8(str)` + +*Since: nightly* + +This function is overly specific and exists primarily to workaround +[this wsl.exe issue](https://github.com/microsoft/WSL/issues/4456). + +It takes as input a string and attempts to convert it from utf16 to utf8. + +```lua +local wezterm = require 'wezterm'; + +local success, wsl_list, wsl_err = wezterm.run_child_process({"wsl.exe", "-l"}) +wsl_list = wezterm.utf16_to_utf8(wsl_list) +``` + diff --git a/src/scripting/mod.rs b/src/scripting/mod.rs index 40ffd1dee..9b86884bb 100644 --- a/src/scripting/mod.rs +++ b/src/scripting/mod.rs @@ -2,6 +2,7 @@ use crate::config::{FontAttributes, TextStyle}; use anyhow::anyhow; +use bstr::BString; use mlua::{Lua, Table, Value}; use std::path::Path; @@ -130,6 +131,10 @@ pub fn make_lua_context(config_dir: &Path) -> anyhow::Result { wezterm_mod.set("read_dir", lua.create_function(read_dir)?)?; wezterm_mod.set("glob", lua.create_function(glob)?)?; + wezterm_mod.set("utf16_to_utf8", lua.create_function(utf16_to_utf8)?)?; + wezterm_mod.set("split_by_newlines", lua.create_function(split_by_newlines)?)?; + wezterm_mod.set("run_child_process", lua.create_function(run_child_process)?)?; + package.set("path", path_array.join(";"))?; let loaded: Table = package.get("loaded")?; @@ -251,3 +256,52 @@ fn glob<'lua>( } Ok(entries) } + +fn split_by_newlines<'lua>(_: &'lua Lua, text: String) -> mlua::Result> { + Ok(text + .lines() + .map(|s| { + // Ungh, `str.lines()` is supposed to split by `\n` or `\r\n`, but I've + // found that it is necessary to have an additional trim here in order + // to actually remove the `\r`. + s.trim_end_matches('\r').to_string() + }) + .collect()) +} + +/// Ungh: https://github.com/microsoft/WSL/issues/4456 +fn utf16_to_utf8<'lua>(_: &'lua Lua, text: mlua::String) -> mlua::Result { + let bytes = text.as_bytes(); + + if bytes.len() % 2 != 0 { + return Err(mlua::Error::external(anyhow!( + "input data has odd length, cannot be utf16" + ))); + } + + // This is "safe" because we checked that the length seems reasonable, + // and our new slice is within those same bounds. + let wide: &[u16] = + unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, bytes.len() / 2) }; + + String::from_utf16(wide).map_err(|e| mlua::Error::external(e)) +} + +fn run_child_process<'lua>( + _: &'lua Lua, + args: Vec, +) -> mlua::Result<(bool, BString, BString)> { + let mut cmd = std::process::Command::new(&args[0]); + + if args.len() > 1 { + cmd.args(&args[1..]); + } + + let output = cmd.output().map_err(|e| mlua::Error::external(e))?; + + Ok(( + output.status.success(), + output.stdout.into(), + output.stderr.into(), + )) +}