diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index a2a087588..a91c6c6ec 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -75,7 +75,7 @@ Prior to starting a review ensure there are no uncommitted changes. - Required uncommitted changes should be committed with relevant commit messages. - If there are unreleated changes in the same commit, split them into separate commits. -Create an untracked code_review_findigs.md file to document any issues found during the review. Include +Create an untracked code_review_findings.md file to document any issues found during the review. Include the following information for each issue: - Status: Open, Fixed, or Won't Fix diff --git a/.gitignore b/.gitignore index 3ca812444..e94094e74 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,4 @@ scripts/packer/packer_cache scripts/packer/output-* *.box +code_review_findings.md diff --git a/CHANGELOG.md b/CHANGELOG.md index cf2a60265..55a9ba703 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,21 @@ ## Unreleased +### Changes + +- Standardize command line behavior of `Cmder.exe` position one arguments `cmd`, `bash`, and `powershell`. See `Command Line Examples` section in `README.md` +- Improve terminal selection with explicit `conemu` and `windows-terminal` launch selectors, executable-based terminal detection, and clear errors for ConEmu-only options when Windows Terminal is selected. +- Allow forcing a launch of bundled `ConEmu` when both `ConEmu` and `Windows Terminal` binaries are present in the `vendor` folder. See: `Cmder.exe Command Line Arguments` section in `README.md` + ### Fixes +- Expand machine-specific ConEmu and Windows Terminal settings paths without overlapping buffers, and report expansion failures or oversized paths. +- Load machine-specific ConEmu settings from the `/C` user configuration root without overlapping path buffers. +- Build launcher command lines without overlapping fixed-buffer formatting, preserving terminal arguments for long paths and option combinations. - Support Git for Windows' `ucrt64` directory in fresh and cached command startup, PowerShell Git discovery, and Git Bash, while retaining older `mingw64` and `mingw32` layouts. This prepares the Git security update in [#3093](https://github.com/cmderdev/cmder/pull/3093). - Show vendor build badges for the requested release ref, with a verified check-runs fallback when the README badge is unavailable. Fix missing README fallback and Azure build-link matching from [#3103](https://github.com/cmderdev/cmder/pull/3103), and link truncated release notes to their full text. - - Pass build-tool arguments directly instead of evaluating command strings, keep archive paths literal, preserve failed downloads for diagnosis, and reject unsafe vendor directory names before vendor changes. Completes the remaining script hygiene work in [#3118](https://github.com/cmderdev/cmder/issues/3118). - ## [2.0.0-rc.1](https://github.com/cmderdev/cmder/releases/tag/v2.0.0-rc.1) (2026-11-10) This is a release candidate for the new current line. The old 1.x source is preserved on `legacy/1.x`. Read [the upgrade guide](docs/UPGRADING-2.0.md) before moving an existing installation. diff --git a/README.md b/README.md index 62f9ebc19..c1ec82eaf 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The Cmder's user interface is also designed to be more eye pleasing, and you can | Argument | Description | | ------------------------- | ----------------------------------------------------------------------- | +| `conemu` | Force a bundled ConEmu terminal when it is the first argument. | | `/C [user_root_path]` | Individual user Cmder root folder. Example: `%userprofile%\cmder_config` | | `/M` | Use `conemu-%computername%.xml` for ConEmu settings storage instead of `user_conemu.xml` | | `/REGISTER [ALL, USER]` | Register a Windows Shell Menu shortcut. | @@ -66,6 +67,29 @@ The Cmder's user interface is also designed to be more eye pleasing, and you can | `/TASK [task_name]` | Task to start after launch. | | `-- [ConEmu extras pars]` | Forwards ALL remaining parameters to ConEmu. | +### Command Line Examples + +Depending on the distribution you have, bundled `Windows Terminal`, bundled `ConEmu`, or no emulator. + +- Running `.\cmder` launches: + - `Windows Terminal` default profile. Default: `Cmder` + - `ConEmu` default task. Default: `cmd::Cmder` or `{Cmder}` + - Windows default terminal emulator with `cmd` with `Cmder` settings. +- `.\cmder bash` launches: + - `Windows Terminal` profile `Cmder - Bash`. + - `ConEmu` task `bash::bash` or `{bash}`. + - `No Emulator` uses Windows default terminal emulator with `Git Bash` with `Cmder` settings. +- `.\cmder cmd` launches: + - `Windows Terminal` profile `Cmder`. + - `ConEmu` task `cmd::Cmder` or `{Cmder}`. + - `No Emulator` uses Windows default terminal emulator with `Cmd.exe` with `Cmder` settings. +- `.\cmder powershell` launches: + - `Windows Terminal` profile `Cmder - PowerShell`. + - `ConEmu` task `PowerShell::PowerShell` or `{PowerShell}`. + - `No Emulator` uses Windows default terminal emulator with `PowerShell` and `Cmder` setings. + +Use `/TASK "Profile Name"` to select a custom profile without translating its name. + ## Context Menu Integration So you've experimented with Cmder a little and want to give it a shot in a more permanent home; @@ -79,6 +103,11 @@ So you've experimented with Cmder a little and want to give it a shot in a more In a file explorer window right click in or on a directory to see "Cmder Here" in the context menu. +To keep a specific bundled terminal in the context menu, register it explicitly, +for example `.\cmder.exe conemu /REGISTER USER` or +`.\cmder.exe windows-terminal /REGISTER USER`. Without a terminal selector, +the menu command uses automatic terminal detection when launched. + ## Keyboard shortcuts ### Tab manipulation diff --git a/launcher/src/CmderLauncher.cpp b/launcher/src/CmderLauncher.cpp index df152397d..28afe78cd 100644 --- a/launcher/src/CmderLauncher.cpp +++ b/launcher/src/CmderLauncher.cpp @@ -2,6 +2,8 @@ #include #include #include "resource.h" +#include +#include #include #include @@ -105,6 +107,71 @@ void GetExecutablePath(wchar_t (&path)[N]) } } +template +void ExpandPathEnvironmentStrings(wchar_t (&path)[N]) +{ + wchar_t expandedPath[N] = { 0 }; + const DWORD length = ExpandEnvironmentStrings(path, expandedPath, static_cast(N)); + if (length == 0 || length > N) + { + ShowErrorAndExit(length == 0 ? GetLastError() : ERROR_FILENAME_EXCED_RANGE, __WFUNCTION__, __LINE__); + } + wcscpy_s(path, expandedPath); +} + +enum class TerminalKind +{ + WindowsTerminal, + ConEmu, + Console +}; + +enum class TerminalSelection +{ + Auto, + WindowsTerminal, + ConEmu +}; + +TerminalKind DetectTerminal(const wchar_t * exeDir, TerminalSelection selection = TerminalSelection::Auto) +{ + wchar_t terminalPath[MAX_PATH] = { 0 }; + + // Preserve Cmder's Windows Terminal-first preference when both emulators are bundled. + PathCombine(terminalPath, exeDir, L"vendor\\windows-terminal\\WindowsTerminal.exe"); + if (selection != TerminalSelection::ConEmu && PathFileExists(terminalPath)) + { + return TerminalKind::WindowsTerminal; + } + + SYSTEM_INFO sysInfo; + GetNativeSystemInfo(&sysInfo); + PathCombine(terminalPath, exeDir, + sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 + ? L"vendor\\conemu-maximus5\\ConEmu64.exe" + : L"vendor\\conemu-maximus5\\ConEmu.exe"); + if (selection != TerminalSelection::WindowsTerminal && PathFileExists(terminalPath)) + { + return TerminalKind::ConEmu; + } + + return TerminalKind::Console; +} + +void MigrateLegacyConfigFile(const wchar_t * configDir, const wchar_t * legacyName, const wchar_t * currentName) +{ + wchar_t legacyPath[MAX_PATH] = { 0 }; + wchar_t currentPath[MAX_PATH] = { 0 }; + PathCombine(legacyPath, configDir, legacyName); + PathCombine(currentPath, configDir, currentName); + + if (PathFileExists(legacyPath)) + { + // MoveFile does not overwrite currentPath, preserving a file already migrated by the user. + MoveFile(legacyPath, currentPath); + } +} + typedef struct _option { std::wstring name; @@ -140,7 +207,7 @@ std::wstring NormalizeTaskName(std::wstring taskName) return taskName; } -void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstring taskName = L"", std::wstring title = L"", std::wstring iconPath = L"", std::wstring cfgRoot = L"", bool use_user_cfg = true, std::wstring conemu_args = L"") +void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstring taskName = L"", std::wstring title = L"", std::wstring iconPath = L"", std::wstring cfgRoot = L"", bool use_user_cfg = true, std::wstring conemu_args = L"", TerminalSelection terminalSelection = TerminalSelection::Auto) { #if USE_TASKBAR_API wchar_t appId[MAX_PATH] = { 0 }; @@ -148,21 +215,19 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr wchar_t exeDir[MAX_PATH] = { 0 }; wchar_t icoPath[MAX_PATH] = { 0 }; wchar_t cfgPath[MAX_PATH] = { 0 }; - wchar_t backupCfgPath[MAX_PATH] = { 0 }; wchar_t cpuCfgPath[MAX_PATH] = { 0 }; wchar_t userCfgPath[MAX_PATH] = { 0 }; wchar_t defaultCfgPath[MAX_PATH] = { 0 }; wchar_t terminalPath[MAX_PATH] = { 0 }; wchar_t configDirPath[MAX_PATH] = { 0 }; + wchar_t userConfigRootPath[MAX_PATH] = { 0 }; wchar_t userConfigDirPath[MAX_PATH] = { 0 }; wchar_t userBinDirPath[MAX_PATH] = { 0 }; wchar_t userProfiledDirPath[MAX_PATH] = { 0 }; - wchar_t userProfilePath[MAX_PATH] = { 0 }; - wchar_t legacyUserProfilePath[MAX_PATH] = { 0 }; - wchar_t userAliasesPath[MAX_PATH] = { 0 }; - wchar_t legacyUserAliasesPath[MAX_PATH] = { 0 }; - wchar_t args[MAX_PATH * 2 + 256] = { 0 }; - wchar_t userConEmuCfgPath[MAX_PATH] = { 0 }; + // Avoid overlapping source/destination calls such as swprintf_s(args, L"%s ...", args). + // std::wstring grows for long paths and terminal arguments instead of silently failing at a fixed buffer size. + std::wstring args; + wchar_t selectedTerminalConfigPath[MAX_PATH] = { 0 }; wchar_t windowsTerminalDir[MAX_PATH] = { 0 }; wchar_t conEmuDir[MAX_PATH] = { 0 }; wchar_t winDir[MAX_PATH] = { 0 }; @@ -184,7 +249,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr std::wstring cmderTitle = title; std::wstring cmderTerminalArgs = conemu_args; - CopyPathOrExit(cfgRoot, userConfigDirPath); + CopyPathOrExit(cfgRoot, userConfigRootPath); GetExecutablePath(exeDir); @@ -205,108 +270,42 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr PathCombine(configDirPath, exeDir, L"config"); - /* - Convert legacy user-profile.cmd to new name user_profile.cmd - */ - PathCombine(legacyUserProfilePath, configDirPath, L"user-profile.cmd"); - if (PathFileExists(legacyUserProfilePath)) - { - PathCombine(userProfilePath, configDirPath, L"user_profile.cmd"); - - char* lPr = (char*)malloc(MAX_PATH); - char* pR = (char*)malloc(MAX_PATH); - size_t i; - wcstombs_s(&i, lPr, (size_t)MAX_PATH, - legacyUserProfilePath, (size_t)MAX_PATH); - wcstombs_s(&i, pR, (size_t)MAX_PATH, - userProfilePath, (size_t)MAX_PATH); - rename(lPr, pR); - } - - /* - Convert legacy user-aliases.cmd to new name user_aliases.cmd - */ - PathCombine(legacyUserAliasesPath, configDirPath, L"user-aliases.cmd"); - if (PathFileExists(legacyUserAliasesPath)) - { - PathCombine(userAliasesPath, configDirPath, L"user_aliases.cmd"); - - char* lPr = (char*)malloc(MAX_PATH); - char* pR = (char*)malloc(MAX_PATH); - size_t i; - wcstombs_s(&i, lPr, (size_t)MAX_PATH, - legacyUserAliasesPath, (size_t)MAX_PATH); - wcstombs_s(&i, pR, (size_t)MAX_PATH, - userAliasesPath, (size_t)MAX_PATH); - rename(lPr, pR); - } + MigrateLegacyConfigFile(configDirPath, L"user-profile.cmd", L"user_profile.cmd"); + MigrateLegacyConfigFile(configDirPath, L"user-aliases.cmd", L"user_aliases.cmd"); - /* - Was /c [path] specified? - */ - if (wcscmp(userConfigDirPath, L"") == 0) + if (cfgRoot.empty()) { - // No - It wasn't. + // No /c [path] specified; use the default config directory next to the executable. PathCombine(userConfigDirPath, exeDir, L"config"); } else { - // Yes - It was. - PathCombine(userBinDirPath, userConfigDirPath, L"bin"); + // /c [path] specified; cfgRoot is the `/c` root and Cmder configuration lives in its `config` child directory. + PathCombine(userBinDirPath, userConfigRootPath, L"bin"); SHCreateDirectoryEx(0, userBinDirPath, 0); - PathCombine(userConfigDirPath, userConfigDirPath, L"config"); + PathCombine(userConfigDirPath, userConfigRootPath, L"config"); SHCreateDirectoryEx(0, userConfigDirPath, 0); PathCombine(userProfiledDirPath, userConfigDirPath, L"profile.d"); SHCreateDirectoryEx(0, userProfiledDirPath, 0); - /* - Convert legacy user-profile.cmd to new name user_profile.cmd - */ - PathCombine(legacyUserProfilePath, userConfigDirPath, L"user-profile.cmd"); - if (PathFileExists(legacyUserProfilePath)) - { - PathCombine(userProfilePath, userConfigDirPath, L"user_profile.cmd"); - - char* lPr = (char*)malloc(MAX_PATH); - char* pR = (char*)malloc(MAX_PATH); - size_t i; - wcstombs_s(&i, lPr, (size_t)MAX_PATH, - legacyUserProfilePath, (size_t)MAX_PATH); - wcstombs_s(&i, pR, (size_t)MAX_PATH, - userProfilePath, (size_t)MAX_PATH); - rename(lPr, pR); - } - - /* - Convert legacy user-aliases.cmd to new name user_aliases.cmd - */ - PathCombine(legacyUserAliasesPath, userConfigDirPath, L"user-aliases.cmd"); - if (PathFileExists(legacyUserAliasesPath)) - { - PathCombine(userAliasesPath, userConfigDirPath, L"user_aliases.cmd"); - - char* lPr = (char*)malloc(MAX_PATH); - char* pR = (char*)malloc(MAX_PATH); - size_t i; - wcstombs_s(&i, lPr, (size_t)MAX_PATH, - legacyUserAliasesPath, (size_t)MAX_PATH); - wcstombs_s(&i, pR, (size_t)MAX_PATH, - userAliasesPath, (size_t)MAX_PATH); - rename(lPr, pR); - } + MigrateLegacyConfigFile(userConfigDirPath, L"user-profile.cmd", L"user_profile.cmd"); + MigrateLegacyConfigFile(userConfigDirPath, L"user-aliases.cmd", L"user_aliases.cmd"); } PathCombine(vendorDir, exeDir, L"vendor"); PathCombine(windowsTerminalDir, vendorDir, L"windows-terminal"); PathCombine(conEmuDir, vendorDir, L"conemu-maximus5"); GetEnvironmentVariable(L"WINDIR", winDir, MAX_PATH); + const TerminalKind terminal = DetectTerminal(exeDir, terminalSelection); + const bool isWindowsTerminal = terminal == TerminalKind::WindowsTerminal; + const bool isConEmu = terminal == TerminalKind::ConEmu; // Windows Terminal cannot select a settings file per launch, so `/c` roots // must not enter the user-root terminal settings flows below. - const bool useSharedWindowsTerminalSettings = PathFileExists(windowsTerminalDir) && cfgRoot.length() != 0; + const bool useSharedWindowsTerminalSettings = isWindowsTerminal && cfgRoot.length() != 0; - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { // Set path to vendored ConEmu config file PathCombine(cfgPath, windowsTerminalDir, L"settings\\settings.json"); @@ -316,12 +315,12 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr // Check for machine-specific then user config source file. PathCombine(cpuCfgPath, userConfigDirPath, L"windows_terminal_%COMPUTERNAME%_settings.json"); - ExpandEnvironmentStrings(cpuCfgPath, cpuCfgPath, sizeof(cpuCfgPath) / sizeof(cpuCfgPath[0])); + ExpandPathEnvironmentStrings(cpuCfgPath); // Set path to Cmder user ConEmu config file PathCombine(userCfgPath, userConfigDirPath, L"user_windows_terminal_settings.json"); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { // Set path to vendored ConEmu config file PathCombine(cfgPath, conEmuDir, L"ConEmu.xml"); @@ -331,7 +330,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr // Check for machine-specific then user config source file. PathCombine(cpuCfgPath, userConfigDirPath, L"ConEmu-%COMPUTERNAME%.xml"); - ExpandEnvironmentStrings(cpuCfgPath, cpuCfgPath, sizeof(cpuCfgPath) / sizeof(cpuCfgPath[0])); + ExpandPathEnvironmentStrings(cpuCfgPath); // Set path to Cmder user ConEmu config file PathCombine(userCfgPath, userConfigDirPath, L"user-ConEmu.xml"); @@ -355,14 +354,14 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(cfgPath, cpuCfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) { + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) ? L"Failed to copy vendor/windows-terminal/settings/settings.json file to config/windows_terminal_%COMPUTERNAME%_settings.json! Access Denied." : L"Failed to copy vendor/windows-terminal/settings/settings.json file to config/windows_terminal_%COMPUTERNAME%_settigns.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -376,14 +375,14 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(cpuCfgPath, cfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) { + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) ? L"Failed to copy config/windows_terminal_%COMPUTERNAME%_settings.json file to vendor/windows-terminal/settings/settings.json! Access Denied." : L"Failed to copy config/windows_terminal_%COMPUTERNAME%_settings.json file to vendor/windows-terminal/settings/settings.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -403,7 +402,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(cfgPath, userCfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -411,7 +410,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr : L"Failed to copy vendor/windows-terminal/settings/settings.json file to config/windows_terminal_settigns.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -425,7 +424,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(userCfgPath, cfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -433,7 +432,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr : L"Failed to copy config/user_windows_terminal_settings.json file to vendor/windows-terminal/settings/settings.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -444,9 +443,6 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr } } } - else if (!PathFileExists(windowsTerminalDir)) { // '/c [path]' was specified, don't copy anything and use existing user_[terminal emulator config] file. - PathCombine(userConEmuCfgPath, userConfigDirPath, L"user-ConEmu.xml"); - } } else if (!useSharedWindowsTerminalSettings && cfgRoot.length() == 0) // Do not initialize user-root terminal settings for `/c` Windows Terminal launches. { @@ -454,7 +450,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(cfgPath, userCfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -462,7 +458,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr : L"Failed to copy vendor/windows-terminal/settings/settings.json file to config/user_windows_terminal_settigns.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -475,7 +471,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(defaultCfgPath, cfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -483,7 +479,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr : L"Failed to copy vendor/windows-terminal_default_settings_settings.json file to vendor/windows-terminal/settings/settigns.json!", MB_TITLE, MB_ICONSTOP); exit(1); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -494,7 +490,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr } } } - else if (!CopyFile(defaultCfgPath, cfgPath, FALSE) && PathFileExists(conEmuDir)) + else if (!CopyFile(defaultCfgPath, cfgPath, FALSE) && isConEmu) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -507,7 +503,7 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr { if (!CopyFile(cfgPath, userCfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -525,13 +521,12 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr } } - PathCombine(userConEmuCfgPath, userConfigDirPath, L"user-ConEmu.xml"); } else if (!useSharedWindowsTerminalSettings && wcscmp(defaultCfgPath, L"") != 0) // Do not copy default terminal settings into `/c` Windows Terminal roots. { if ( ! CopyFile(defaultCfgPath, userCfgPath, FALSE)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, (GetLastError() == ERROR_ACCESS_DENIED) @@ -548,7 +543,6 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr exit(1); } } - PathCombine(userConEmuCfgPath, userConfigDirPath, L"user-ConEmu.xml"); } GetEnvironmentVariable(L"ProgramFiles", programFiles, MAX_PATH); @@ -560,14 +554,17 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr SYSTEM_INFO sysInfo; GetNativeSystemInfo(&sysInfo); - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { PathCombine(terminalPath, exeDir, L"vendor\\windows-terminal\\WindowsTerminal.exe"); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { - swprintf_s(args, L"%s /Icon \"%s\"", args, icoPath); - swprintf_s(args, L"%s /title \"%s\"", args, cmderTitle.c_str()); + args += L" /Icon \""; + args += icoPath; + args += L"\" /title \""; + args += cmderTitle; + args += L"\""; PathCombine(terminalPath, exeDir, sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ? L"vendor\\conemu-maximus5\\ConEmu64.exe" @@ -602,32 +599,55 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr if (!streqi(cmderStart.c_str(), L"")) { - if (PathFileExists(windowsTerminalDir)) { - swprintf_s(args, L"%s -d \"%s\"", args, cmderStart.c_str()); + if (isWindowsTerminal) { + args += L" -d \""; + args += cmderStart; + args += L"\""; } else { - swprintf_s(args, L"%s /dir \"%s\"", args, cmderStart.c_str()); + args += L" /dir \""; + args += cmderStart; + args += L"\""; } } if (is_single_mode) { - if (!PathFileExists(windowsTerminalDir)) { - swprintf_s(args, L"%s /single", args); + if (!isWindowsTerminal) { + args += L" /single"; } } if (cfgRoot.length() != 0) { - if (!PathFileExists(windowsTerminalDir)) { - swprintf_s(args, L"%s -loadcfgfile \"%s\"", args, userConEmuCfgPath); + if (isConEmu) + { + // ConEmu can load a settings file per launch. Prefer the most specific + // existing file, then fall back to the bundled configuration. + if (PathFileExists(cpuCfgPath)) + { + wcscpy_s(selectedTerminalConfigPath, cpuCfgPath); + } + else if (use_user_cfg && PathFileExists(userCfgPath)) + { + wcscpy_s(selectedTerminalConfigPath, userCfgPath); + } + else + { + wcscpy_s(selectedTerminalConfigPath, cfgPath); + } + + args += L" -loadcfgfile \""; + args += selectedTerminalConfigPath; + args += L"\""; } } if (!streqi(cmderTerminalArgs.c_str(), L"")) { - swprintf_s(args, L"%s %s", args, cmderTerminalArgs.c_str()); + args += L" "; + args += cmderTerminalArgs; } // The `/run` arg and its value MUST be the last arg of ConEmu @@ -640,30 +660,42 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr if (!streqi(cmderTask.c_str(), L"")) { - if (PathFileExists(windowsTerminalDir)) { - swprintf_s(args, L"%s -p \"%s\"", args, cmderTask.c_str()); + if (isWindowsTerminal) { + args += L" -p \""; + args += cmderTask; + args += L"\""; } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { - swprintf_s(args, L"%s /run {%s}", args, cmderTask.c_str()); + args += L" /run {"; + args += cmderTask; + args += L"}"; } else { if (streqi(cmderTask.c_str(), L"powershell")) { - swprintf_s(args, L"%s -ExecutionPolicy Bypass -NoLogo -NoProfile -NoExit -Command \"Invoke-Expression 'Import-Module ''%s'''\"", args, initPowerShell); + args += L" -ExecutionPolicy Bypass -NoLogo -NoProfile -NoExit -Command \"Invoke-Expression 'Import-Module ''"; + args += initPowerShell; + args += L"'''\""; } else if (streqi(cmderTask.c_str(), L"bash")) { - swprintf_s(args, L"%s /c \"%s\"", args, initBash); + args += L" /c \""; + args += initBash; + args += L"\""; } else if (streqi(cmderTask.c_str(), L"mintty")) { - swprintf_s(args, L"%s /c \"%s\"", args, initMintty); + args += L" /c \""; + args += initMintty; + args += L"\""; } else if (streqi(cmderTask.c_str(), L"cmder")) { - swprintf_s(args, L"%s /k \"%s\"", args, initCmd); + args += L" /k \""; + args += initCmd; + args += L"\""; } } } @@ -696,8 +728,6 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr } */ - // Ensure EnvironmentVariables are propagated. - STARTUPINFO si = { 0 }; si.cb = sizeof(STARTUPINFO); @@ -706,14 +736,18 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr si.dwFlags = STARTF_TITLEISAPPID; #endif PROCESS_INFORMATION pi; + // CreateProcess may write into its command-line argument. A vector supplies mutable, + // NUL-terminated storage without relying on the C++ standard-library version for mutable string data. + std::vector commandLine(args.begin(), args.end()); + commandLine.push_back(L'\0'); - if (!CreateProcess(terminalPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) + if (!CreateProcess(terminalPath, commandLine.data(), NULL, NULL, false, 0, NULL, NULL, &si, &pi)) { - if (PathFileExists(windowsTerminalDir)) + if (isWindowsTerminal) { MessageBox(NULL, _T("Unable to create the Windows Terminal process!"), _T("Error"), MB_OK); } - else if (PathFileExists(conEmuDir)) + else if (isConEmu) { MessageBox(NULL, _T("Unable to create the ConEmu process!"), _T("Error"), MB_OK); } @@ -723,6 +757,11 @@ void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstr } return; } + + // CreateProcess returns handles even when Cmder does not need to wait for the child. + // Close them after launch so repeated invocations do not leak operating-system handles. + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); } bool IsUserOnly(std::wstring opt) @@ -762,7 +801,7 @@ HKEY GetRootKey(std::wstring opt) return root; } -void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName, std::wstring cfgRoot, bool single) +void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName, std::wstring cfgRoot, bool single, TerminalSelection terminalSelection = TerminalSelection::Auto) { wchar_t userConfigDirPath[MAX_PATH] = { 0 }; @@ -773,23 +812,25 @@ void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName, std::wstring cfgR GetExecutablePath(exePath); - wchar_t commandStr[MAX_PATH + 20] = { 0 }; - wchar_t baseCommandStr[MAX_PATH + 20] = { 0 }; - if (single) { - swprintf_s(baseCommandStr, L"\"%s\" /single", exePath); + std::wstring commandStr = L"\""; + commandStr += exePath; + commandStr += L"\""; + if (terminalSelection == TerminalSelection::ConEmu) { + commandStr += L" conemu"; } - else { - swprintf_s(baseCommandStr, L"\"%s\"", exePath); + else if (terminalSelection == TerminalSelection::WindowsTerminal) { + commandStr += L" windows-terminal"; } - - if (cfgRoot.length() == 0) // '/c [path]' was NOT specified - { - swprintf_s(commandStr, L"%s \"%%V\"", baseCommandStr); + if (single) { + commandStr += L" /single"; } - else { + if (!cfgRoot.empty()) { CopyPathOrExit(cfgRoot, userConfigDirPath); - swprintf_s(commandStr, L"%s /c \"%s\" \"%%V\"", baseCommandStr, userConfigDirPath); + commandStr += L" /c \""; + commandStr += userConfigDirPath; + commandStr += L"\""; } + commandStr += L" \"%V\""; // Now that we have `commandStr`, it's OK to change `exePath`... PathRemoveFileSpec(exePath); @@ -810,7 +851,7 @@ void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName, std::wstring cfgR HKEY command; FAIL_ON_ERROR(RegCreateKeyEx(cmderKey, L"command", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL)); - FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL)); + FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr.c_str(), NULL)); RegCloseKey(command); RegCloseKey(cmderKey); @@ -837,11 +878,13 @@ struct cmderOptions std::wstring cmderIcon = L""; std::wstring cmderRegScope = L"USER"; std::wstring cmderTerminalArgs = L""; + TerminalSelection terminalSelection = TerminalSelection::Auto; bool cmderSingle = false; bool cmderUserCfg = true; bool registerApp = false; bool unRegisterApp = false; bool error = false; + std::wstring errorMessage = L""; }; cmderOptions GetOption() @@ -850,18 +893,11 @@ cmderOptions GetOption() LPWSTR *szArgList; int argCount; - wchar_t windowsTerminalDir[MAX_PATH] = { 0 }; - wchar_t conEmuDir[MAX_PATH] = { 0 }; - wchar_t vendorDir[MAX_PATH] = { 0 }; wchar_t exeDir[MAX_PATH] = { 0 }; GetExecutablePath(exeDir); PathRemoveFileSpec(exeDir); - PathCombine(vendorDir, exeDir, L"vendor"); - PathCombine(windowsTerminalDir, vendorDir, L"windows-terminal"); - PathCombine(conEmuDir, vendorDir, L"ConEmu-Maximus5"); - szArgList = CommandLineToArgvW(GetCommandLine(), &argCount); if (szArgList == NULL) { @@ -869,13 +905,38 @@ cmderOptions GetOption() return cmderOptions; } - for (int i = 1; i < argCount; i++) + // Match Cmder.bat: terminal selectors are recognized only as the first argument. + int firstOptionIndex = 1; + if (argCount > 1 && _wcsicmp(L"conemu", szArgList[1]) == 0) + { + cmderOptions.terminalSelection = TerminalSelection::ConEmu; + firstOptionIndex++; + } + else if (argCount > 1 && _wcsicmp(L"windows-terminal", szArgList[1]) == 0) + { + cmderOptions.terminalSelection = TerminalSelection::WindowsTerminal; + firstOptionIndex++; + } + + const TerminalKind terminal = DetectTerminal(exeDir, cmderOptions.terminalSelection); + const bool isConEmu = terminal == TerminalKind::ConEmu; + if (cmderOptions.terminalSelection != TerminalSelection::Auto && terminal == TerminalKind::Console) + { + cmderOptions.error = true; + cmderOptions.errorMessage = cmderOptions.terminalSelection == TerminalSelection::ConEmu + ? L"The requested bundled ConEmu terminal is not available." + : L"The requested bundled Windows Terminal is not available."; + } + + for (int i = firstOptionIndex; i < argCount; i++) { // MessageBox(NULL, szArgList[i], L"Arglist contents", MB_OK); if (cmderOptions.error == false) { - const bool conEmuOptions = !PathFileExists(windowsTerminalDir) && PathFileExists(conEmuDir); + // A value-taking option can consume the next argument only when it exists and is not another slash-prefixed launcher option. + const bool hasFollowingNonOptionArgument = i + 1 < argCount && szArgList[i + 1][0] != '/' && + szArgList[i + 1][0] != L'\0' && wcscmp(szArgList[i + 1], L"--") != 0; const bool needsValue = streqi(szArgList[i], L"/start") || streqi(szArgList[i], L"/task") || - streqi(szArgList[i], L"/x") || (conEmuOptions && + streqi(szArgList[i], L"/x") || (isConEmu && (streqi(szArgList[i], L"/title") || streqi(szArgList[i], L"/icon"))); if (szArgList[i][0] == L'\0' || (needsValue && (i + 1 >= argCount || szArgList[i + 1][0] == L'\0'))) @@ -886,8 +947,7 @@ cmderOptions GetOption() if (_wcsicmp(L"/c", szArgList[i]) == 0) { - if (i + 1 < argCount && szArgList[i + 1][0] != '/' && szArgList[i + 1][0] != L'\0' && - wcscmp(szArgList[i + 1], L"--") != 0) + if (hasFollowingNonOptionArgument) { cmderOptions.cmderCfgRoot = szArgList[i + 1]; i++; @@ -926,7 +986,7 @@ cmderOptions GetOption() } else if (_wcsicmp(L"/task", szArgList[i]) == 0) { - if (i + 1 < argCount && szArgList[i + 1][0] != '/' && wcscmp(szArgList[i + 1], L"--") != 0) + if (hasFollowingNonOptionArgument) { cmderOptions.cmderTask = szArgList[i + 1]; i++; @@ -936,33 +996,57 @@ cmderOptions GetOption() cmderOptions.error = true; } } - else if (_wcsicmp(L"bash", szArgList[i]) == 0 || _wcsicmp(L"powershell", szArgList[i]) == 0) + else if (_wcsicmp(L"bash", szArgList[i]) == 0 || _wcsicmp(L"powershell", szArgList[i]) == 0 || + (terminal != TerminalKind::Console && _wcsicmp(L"cmd", szArgList[i]) == 0)) { cmderOptions.cmderTask = szArgList[i]; + if (terminal == TerminalKind::WindowsTerminal) + { + cmderOptions.cmderTask = streqi(szArgList[i], L"bash") ? L"Cmder - Bash" : + streqi(szArgList[i], L"powershell") ? L"Cmder - PowerShell" : L"Cmder"; + } + else if (isConEmu && streqi(szArgList[i], L"cmd")) + { + cmderOptions.cmderTask = L"Cmder"; + } } - else if (_wcsicmp(L"/title", szArgList[i]) == 0 && !PathFileExists(windowsTerminalDir) && PathFileExists(conEmuDir)) - { - cmderOptions.cmderTitle = szArgList[i + 1]; - i++; - } - else if (_wcsicmp(L"/icon", szArgList[i]) == 0 && !PathFileExists(windowsTerminalDir) && PathFileExists(conEmuDir)) - { - cmderOptions.cmderIcon = szArgList[i + 1]; - i++; - } - else if (_wcsicmp(L"/single", szArgList[i]) == 0 && !PathFileExists(windowsTerminalDir) && PathFileExists(conEmuDir)) - { - cmderOptions.cmderSingle = true; - } - else if (_wcsicmp(L"/m", szArgList[i]) == 0 && !PathFileExists(windowsTerminalDir) && PathFileExists(conEmuDir)) + else if (_wcsicmp(L"/title", szArgList[i]) == 0 || _wcsicmp(L"/icon", szArgList[i]) == 0 || + _wcsicmp(L"/single", szArgList[i]) == 0 || _wcsicmp(L"/m", szArgList[i]) == 0) { - cmderOptions.cmderUserCfg = false; + if (!isConEmu) + { + cmderOptions.error = true; + cmderOptions.errorMessage = std::wstring(szArgList[i]) + + L" is supported only when Cmder launches ConEmu. " + + (terminal == TerminalKind::WindowsTerminal ? L"Windows Terminal" : L"the console") + + L" is currently selected."; + break; + } + + if (_wcsicmp(L"/title", szArgList[i]) == 0) + { + cmderOptions.cmderTitle = szArgList[i + 1]; + i++; + } + else if (_wcsicmp(L"/icon", szArgList[i]) == 0) + { + cmderOptions.cmderIcon = szArgList[i + 1]; + i++; + } + else if (_wcsicmp(L"/single", szArgList[i]) == 0) + { + cmderOptions.cmderSingle = true; + } + else + { + cmderOptions.cmderUserCfg = false; + } } else if (_wcsicmp(L"/register", szArgList[i]) == 0) { cmderOptions.registerApp = true; cmderOptions.unRegisterApp = false; - if (szArgList[i + 1] != NULL) + if (i + 1 < argCount) { if (_wcsicmp(L"all", szArgList[i + 1]) == 0 || _wcsicmp(L"user", szArgList[i + 1]) == 0) { @@ -975,7 +1059,7 @@ cmderOptions GetOption() { cmderOptions.unRegisterApp = true; cmderOptions.registerApp = false; - if (szArgList[i + 1] != NULL) + if (i + 1 < argCount) { if (_wcsicmp(L"all", szArgList[i + 1]) == 0 || _wcsicmp(L"user", szArgList[i + 1]) == 0) { @@ -1025,19 +1109,29 @@ cmderOptions GetOption() } } - if (!PathFileExists(windowsTerminalDir) && !PathFileExists(conEmuDir) && streqi(cmderOptions.cmderTask.c_str(), L"")) + if (streqi(cmderOptions.cmderTask.c_str(), L"")) { - cmderOptions.cmderTask = L"cmder"; + if (terminal == TerminalKind::Console) + { + cmderOptions.cmderTask = L"cmder"; + } } if (cmderOptions.error == true) { - wchar_t validOptions[512]; - HMODULE hMod = GetModuleHandle(NULL); - LoadString(hMod, IDS_SWITCHES, validOptions, 512); + if (!cmderOptions.errorMessage.empty()) + { + MessageBox(NULL, cmderOptions.errorMessage.c_str(), MB_TITLE, MB_OK | MB_ICONERROR); + } + else + { + wchar_t validOptions[512]; + HMODULE hMod = GetModuleHandle(NULL); + LoadString(hMod, IDS_SWITCHES, validOptions, 512); - // display list of valid options on unrecognized parameter - TaskDialogOpen( L"Unrecognized parameter.", validOptions ); + // display list of valid options on unrecognized parameter + TaskDialogOpen( L"Unrecognized parameter.", validOptions ); + } } LocalFree(szArgList); @@ -1060,29 +1154,19 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, return 1; } - wchar_t windowsTerminalDir[MAX_PATH] = { 0 }; wchar_t exeDir[MAX_PATH] = { 0 }; GetExecutablePath(exeDir); PathRemoveFileSpec(exeDir); - PathCombine(windowsTerminalDir, exeDir, L"vendor\\windows-terminal"); + const TerminalKind terminal = DetectTerminal(exeDir, cmderOptions.terminalSelection); if (cmderOptions.registerApp == true) { - if (PathFileExists(windowsTerminalDir)) - { - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, cmderOptions.cmderSingle); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_LISTITEM, cmderOptions.cmderCfgRoot, cmderOptions.cmderSingle); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, cmderOptions.cmderSingle); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_LISTITEM, cmderOptions.cmderCfgRoot, cmderOptions.cmderSingle); - } - else - { - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, false); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_LISTITEM, cmderOptions.cmderCfgRoot, false); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, false); - RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_LISTITEM, cmderOptions.cmderCfgRoot, false); - } + const bool single = terminal == TerminalKind::ConEmu && cmderOptions.cmderSingle; + RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, single, cmderOptions.terminalSelection); + RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_LISTITEM, cmderOptions.cmderCfgRoot, single, cmderOptions.terminalSelection); + RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_BACKGROUND, cmderOptions.cmderCfgRoot, single, cmderOptions.terminalSelection); + RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_DRIVE_PATH_LISTITEM, cmderOptions.cmderCfgRoot, single, cmderOptions.terminalSelection); } else if (cmderOptions.unRegisterApp == true) { @@ -1093,7 +1177,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } else { - StartCmder(cmderOptions.cmderStart, cmderOptions.cmderSingle, cmderOptions.cmderTask, cmderOptions.cmderTitle, cmderOptions.cmderIcon, cmderOptions.cmderCfgRoot, cmderOptions.cmderUserCfg, cmderOptions.cmderTerminalArgs); + StartCmder(cmderOptions.cmderStart, cmderOptions.cmderSingle, cmderOptions.cmderTask, cmderOptions.cmderTitle, cmderOptions.cmderIcon, cmderOptions.cmderCfgRoot, cmderOptions.cmderUserCfg, cmderOptions.cmderTerminalArgs, cmderOptions.terminalSelection); } return 0; diff --git a/launcher/tests/CmderLauncherTests.cpp b/launcher/tests/CmderLauncherTests.cpp index 2a3ae5ee4..832651b09 100644 --- a/launcher/tests/CmderLauncherTests.cpp +++ b/launcher/tests/CmderLauncherTests.cpp @@ -7,18 +7,25 @@ #include #include -// Exercise the production launcher without dialogs, shell launches, or registry -// writes. Only process input and the executable-path API are replaced. +// Exercise the production launcher without dialogs, shell launches, or registry writes. struct LauncherExit { int code; }; static std::wstring testCommandLine = L"Cmder.exe"; static std::wstring testExecutable = L"C:\\Cmder\\Cmder.exe"; static bool failModulePath = false; +static bool failEnvironmentExpansion = false; +static bool overlappingEnvironmentExpansion = false; static DWORD modulePathCapacity = 0; static int helpDialogs = 0; static int registryWrites = 0; +static bool allowRegistryWrites = false; +static int fakeRegistryKey; +static int fakeCommandKey; +static std::vector registeredCommands; static int terminalLaunches = 0; static WORD nativeArchitecture = PROCESSOR_ARCHITECTURE_AMD64; static std::wstring lastTerminalPath; +static std::wstring lastTerminalArguments; +static std::wstring lastMessage; [[noreturn]] static void TestExit(int code) { throw LauncherExit{code}; } static LPWSTR WINAPI TestGetCommandLineW() { return &testCommandLine[0]; } @@ -36,23 +43,54 @@ static DWORD WINAPI TestGetModuleFileNameW(HMODULE, LPWSTR path, DWORD capacity) wcscpy_s(path, capacity, testExecutable.c_str()); return static_cast(testExecutable.length()); } -static int WINAPI TestMessageBoxW(HWND, LPCWSTR, LPCWSTR, UINT) { return IDOK; } +static int WINAPI TestMessageBoxW(HWND, LPCWSTR message, LPCWSTR, UINT) +{ + lastMessage = message; + return IDOK; +} +static DWORD WINAPI TestExpandEnvironmentStringsW(LPCWSTR source, LPWSTR destination, DWORD capacity) +{ + overlappingEnvironmentExpansion |= source == destination; + if (failEnvironmentExpansion) { + SetLastError(ERROR_ACCESS_DENIED); + return 0; + } + return ExpandEnvironmentStringsW(source, destination, capacity); +} static HRESULT WINAPI TestTaskDialogIndirect(const TASKDIALOGCONFIG*, int*, int*, BOOL*) { ++helpDialogs; return S_OK; } -static LSTATUS WINAPI TestRegCreateKeyExW(HKEY, LPCWSTR, DWORD, LPWSTR, DWORD, - REGSAM, const LPSECURITY_ATTRIBUTES, PHKEY, LPDWORD) +static LSTATUS WINAPI TestRegCreateKeyExW(HKEY, LPCWSTR name, DWORD, LPWSTR, DWORD, + REGSAM, const LPSECURITY_ATTRIBUTES, PHKEY key, LPDWORD) { ++registryWrites; - return ERROR_ACCESS_DENIED; + if (!allowRegistryWrites) { return ERROR_ACCESS_DENIED; } + *key = reinterpret_cast(wcscmp(name, L"command") == 0 ? &fakeCommandKey : &fakeRegistryKey); + return ERROR_SUCCESS; +} +static LSTATUS WINAPI TestRegSetValueW(HKEY key, LPCWSTR, DWORD, LPCWSTR value, DWORD) +{ + if (key == reinterpret_cast(&fakeCommandKey)) { + registeredCommands.emplace_back(value); + } + return ERROR_SUCCESS; +} +static LSTATUS WINAPI TestRegSetValueExW(HKEY, LPCWSTR, DWORD, DWORD, const BYTE*, DWORD) +{ + return ERROR_SUCCESS; +} +static LSTATUS WINAPI TestRegCloseKey(HKEY) +{ + return ERROR_SUCCESS; } -static BOOL WINAPI TestCreateProcessW(LPCWSTR application, LPWSTR, LPSECURITY_ATTRIBUTES, +static BOOL WINAPI TestCreateProcessW(LPCWSTR application, LPWSTR arguments, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION) { ++terminalLaunches; lastTerminalPath = application; + lastTerminalArguments = arguments; SetLastError(ERROR_FILE_NOT_FOUND); return FALSE; } @@ -65,18 +103,26 @@ static void WINAPI TestGetNativeSystemInfo(LPSYSTEM_INFO info) #define exit TestExit #define GetCommandLineW TestGetCommandLineW #define GetModuleFileNameW TestGetModuleFileNameW +#define ExpandEnvironmentStringsW TestExpandEnvironmentStringsW #define MessageBoxW TestMessageBoxW #define TaskDialogIndirect TestTaskDialogIndirect #define RegCreateKeyExW TestRegCreateKeyExW +#define RegSetValueW TestRegSetValueW +#define RegSetValueExW TestRegSetValueExW +#define RegCloseKey TestRegCloseKey #define CreateProcessW TestCreateProcessW #define GetNativeSystemInfo TestGetNativeSystemInfo #include "../src/CmderLauncher.cpp" #undef exit #undef GetCommandLineW #undef GetModuleFileNameW +#undef ExpandEnvironmentStringsW #undef MessageBoxW #undef TaskDialogIndirect #undef RegCreateKeyExW +#undef RegSetValueW +#undef RegSetValueExW +#undef RegCloseKey #undef CreateProcessW #undef GetNativeSystemInfo @@ -127,6 +173,33 @@ static void TestPathBounds() Check(registryWrites == 0, "Rejected configuration path reached registry writes"); } +static void TestPathEnvironmentExpansion() +{ + const std::wstring variable = L"CMDER_LAUNCHER_TEST_PATH_" + std::to_wstring(GetCurrentProcessId()); + const std::wstring source = L"%" + variable + L"%"; + wchar_t path[MAX_PATH] = {}; + const std::wstring longestPath(MAX_PATH - 1, L'a'); + Check(SetEnvironmentVariableW(variable.c_str(), longestPath.c_str()) != 0, + "Could not set expansion test variable"); + CopyPathOrExit(source, path); + ExpandPathEnvironmentStrings(path); + Check(longestPath == path, "259-character environment expansion failed"); + + const std::wstring oversized(MAX_PATH, L'a'); + Check(SetEnvironmentVariableW(variable.c_str(), oversized.c_str()) != 0, + "Could not update expansion test variable"); + CopyPathOrExit(source, path); + ExpectControlledExit([&]() { ExpandPathEnvironmentStrings(path); }); + Check(source == path, "Oversized expansion changed the source path"); + + failEnvironmentExpansion = true; + ExpectControlledExit([&]() { ExpandPathEnvironmentStrings(path); }); + failEnvironmentExpansion = false; + Check(source == path, "Failed expansion changed the source path"); + Check(SetEnvironmentVariableW(variable.c_str(), NULL) != 0, + "Could not remove expansion test variable"); +} + static cmderOptions Parse(const std::wstring& arguments) { testCommandLine = L"Cmder.exe " + arguments; @@ -155,6 +228,38 @@ static std::string ReadFixture(const std::wstring& path) return std::string(content, read); } +static void TestLegacyConfigurationMigration() +{ + wchar_t temporaryPath[MAX_PATH] = {}; + wchar_t fixturePath[MAX_PATH] = {}; + Check(GetTempPathW(MAX_PATH, temporaryPath) != 0, "Could not get temporary path"); + Check(GetTempFileNameW(temporaryPath, L"cmd", 0, fixturePath) != 0, "Could not allocate fixture path"); + Check(DeleteFileW(fixturePath) != 0, "Could not prepare migration fixture directory"); + Check(CreateDirectoryW(fixturePath, NULL) != 0, "Could not create migration fixture directory"); + + const std::wstring root(fixturePath); + const std::wstring legacyProfile = root + L"\\user-profile.cmd"; + const std::wstring currentProfile = root + L"\\user_profile.cmd"; + const std::wstring legacyAliases = root + L"\\user-aliases.cmd"; + const std::wstring currentAliases = root + L"\\user_aliases.cmd"; + + WriteFixture(legacyProfile, "legacy profile"); + MigrateLegacyConfigFile(root.c_str(), L"user-profile.cmd", L"user_profile.cmd"); + Check(!PathFileExists(legacyProfile.c_str()), "Migrated legacy profile was not removed"); + Check(ReadFixture(currentProfile) == "legacy profile", "Migrated profile content changed"); + + WriteFixture(legacyAliases, "legacy aliases"); + WriteFixture(currentAliases, "current aliases"); + MigrateLegacyConfigFile(root.c_str(), L"user-aliases.cmd", L"user_aliases.cmd"); + Check(PathFileExists(legacyAliases.c_str()), "Existing current aliases overwrote legacy aliases"); + Check(ReadFixture(currentAliases) == "current aliases", "Existing current aliases changed"); + + Check(DeleteFileW(legacyAliases.c_str()) != 0, "Could not remove legacy aliases fixture"); + Check(DeleteFileW(currentAliases.c_str()) != 0, "Could not remove current aliases fixture"); + Check(DeleteFileW(currentProfile.c_str()) != 0, "Could not remove current profile fixture"); + Check(RemoveDirectoryW(root.c_str()) != 0, "Could not remove migration fixture directory"); +} + static void TestArgumentParsing() { wchar_t temporaryPath[MAX_PATH] = {}; @@ -168,23 +273,106 @@ static void TestArgumentParsing() const std::wstring conemu = vendor + L"\\conemu-maximus5"; const std::wstring windowsTerminal = vendor + L"\\windows-terminal"; const std::wstring installationConfig = root + L"\\config"; + const std::wstring userRoot = root + L"\\user"; + const std::wstring userConfig = userRoot + L"\\config"; + const std::wstring userSettings = userConfig + L"\\user_windows_terminal_settings.json"; + std::wstring machineConfig; Check(CreateDirectoryW(vendor.c_str(), NULL) != 0, "Could not create vendor fixture"); Check(CreateDirectoryW(installationConfig.c_str(), NULL) != 0, "Could not create installation config fixture"); testExecutable = root + L"\\Cmder.exe"; for (int terminal = 0; terminal < 3; ++terminal) { + if (terminal == 0) { + Check(Parse(L"").cmderTask == L"cmder", "Console default shell changed"); + Check(Parse(L"bash").cmderTask == L"bash" && + Parse(L"powershell").cmderTask == L"powershell", + "Console shorthand shell names changed"); + for (const wchar_t* arguments : {L"conemu", L"windows-terminal"}) { + const int dialogs = helpDialogs; + lastMessage.clear(); + Check(Parse(arguments).error, "Missing requested terminal did not produce an error"); + Check(lastMessage.find(L"requested bundled") != std::wstring::npos, + "Missing requested terminal did not report its availability"); + Check(helpDialogs == dialogs, "Missing requested terminal displayed generic help"); + } + } if (terminal == 1) { Check(CreateDirectoryW(conemu.c_str(), NULL) != 0, "Could not create ConEmu fixture"); WriteFixture(vendor + L"\\ConEmu.xml.default", ""); + WriteFixture(conemu + L"\\ConEmu.exe", ""); + WriteFixture(conemu + L"\\ConEmu64.exe", ""); + Check(Parse(L"").cmderTask.empty(), "ConEmu default task selection changed"); + Check(Parse(L"bash").cmderTask == L"bash" && + Parse(L"powershell").cmderTask == L"powershell", + "ConEmu shorthand task names changed"); + Check(CreateDirectoryW(userRoot.c_str(), NULL) != 0, "Could not create ConEmu user root"); + Check(CreateDirectoryW(userConfig.c_str(), NULL) != 0, "Could not create ConEmu user config"); + wchar_t computerName[MAX_COMPUTERNAME_LENGTH + 1] = {}; + DWORD computerNameLength = _countof(computerName); + Check(GetComputerNameW(computerName, &computerNameLength) != 0, "Could not get computer name"); + machineConfig = userConfig + L"\\ConEmu-" + computerName + L".xml"; + WriteFixture(machineConfig, ""); for (WORD architecture : {WORD(PROCESSOR_ARCHITECTURE_INTEL), WORD(PROCESSOR_ARCHITECTURE_AMD64), WORD(PROCESSOR_ARCHITECTURE_ARM64)}) { nativeArchitecture = architecture; StartCmder(); Check(lastTerminalPath == conemu + (architecture == PROCESSOR_ARCHITECTURE_AMD64 ? L"\\ConEmu64.exe" : L"\\ConEmu.exe"), "ConEmu executable did not match native architecture"); } + nativeArchitecture = PROCESSOR_ARCHITECTURE_AMD64; + StartCmder(L"", false, L"", L"", L"", userRoot); + Check(PathIsDirectoryW((userRoot + L"\\bin").c_str()) && + PathIsDirectoryW((userConfig + L"\\profile.d").c_str()), + "ConEmu /c launch did not create directories under the user root"); + Check(ReadFixture(machineConfig) == "", + "ConEmu /c launch changed user-owned machine settings"); + Check(lastTerminalArguments.find(L"-loadcfgfile \"" + machineConfig + L"\"") != std::wstring::npos, + "ConEmu /c launch did not select machine-specific settings"); + StartCmder(root, true, L"Custom", L"Custom Title", L"", userRoot); + const std::wstring expectedConEmuArguments = + L" /Icon \"" + root + L"\\icons\\cmder.ico\" /title \"Custom Title\" /dir \"" + root + + L"\" /single -loadcfgfile \"" + machineConfig + L"\" /run {Custom}"; + Check(lastTerminalArguments == expectedConEmuArguments, + "ConEmu command-line construction changed"); + + struct TaskCase { const wchar_t* arguments; const wchar_t* task; }; + const TaskCase taskCases[] = { + {L"cmd", L"Cmder"}, + {L"CmD", L"Cmder"}, + {L"conemu cmd", L"Cmder"}, + {L"/TASK cmd", L"cmd"}, + {L"/TASK \"Profile Name\"", L"Profile Name"} + }; + for (const auto& taskCase : taskCases) { + const auto options = Parse(taskCase.arguments); + Check(!options.error && options.cmderTask == taskCase.task, + "ConEmu cmd shorthand or literal task did not parse"); + const int launches = terminalLaunches; + Check(_tWinMain(NULL, NULL, NULL, 0) == 0 && terminalLaunches == launches + 1, + "ConEmu task selection did not launch"); + const std::wstring expectedArguments = + L" /Icon \"" + root + L"\\icons\\cmder.ico\" /title \"Cmder\" /run {" + + taskCase.task + L"}"; + Check(lastTerminalPath == conemu + L"\\ConEmu64.exe" && + lastTerminalArguments == expectedArguments, + "ConEmu did not receive the selected task"); + } } if (terminal == 2) { Check(CreateDirectoryW(windowsTerminal.c_str(), NULL) != 0, "Could not create Windows Terminal fixture"); + WriteFixture(windowsTerminal + L"\\WindowsTerminal.exe", ""); + + auto options = Parse(L"conemu /task Custom"); + Check(!options.error && options.terminalSelection == TerminalSelection::ConEmu, + "ConEmu terminal override did not parse"); + Check(_tWinMain(NULL, NULL, NULL, 0) == 0 && lastTerminalPath == conemu + L"\\ConEmu64.exe", + "ConEmu terminal override did not force ConEmu"); + + options = Parse(L"windows-terminal /task Custom"); + Check(!options.error && options.terminalSelection == TerminalSelection::WindowsTerminal, + "Windows Terminal override did not parse"); + Check(_tWinMain(NULL, NULL, NULL, 0) == 0 && + lastTerminalPath == windowsTerminal + L"\\WindowsTerminal.exe", + "Windows Terminal override did not force Windows Terminal"); } for (const wchar_t* arguments : {L"/start", L"/start \"\"", L"/task", L"/task \"\"", L"/task --", L"/x", L"/x \"\"", L"\"\""}) { @@ -218,40 +406,117 @@ static void TestArgumentParsing() !options.cmderUserCfg && options.cmderTitle == L"Custom" && options.cmderIcon == L"custom.ico", "ConEmu arguments or shorthand task consumed another option"); } + if (terminal == 2) { + for (const wchar_t* arguments : {L"/title Custom", L"/icon custom.ico", L"/single", L"/m"}) { + const int dialogs = helpDialogs; + lastMessage.clear(); + Check(Parse(arguments).error, "Windows Terminal accepted a ConEmu-only option"); + Check(lastMessage.find(L"supported only when Cmder launches ConEmu") != std::wstring::npos && + lastMessage.find(L"Windows Terminal is currently selected") != std::wstring::npos, + "Windows Terminal did not report the unsupported ConEmu option"); + Check(helpDialogs == dialogs, "Unsupported ConEmu option displayed generic help"); + } + } } const std::wstring settingsDirectory = windowsTerminal + L"\\settings"; const std::wstring settings = settingsDirectory + L"\\settings.json"; const std::wstring defaults = vendor + L"\\windows_terminal_default_settings.json"; - const std::wstring userRoot = root + L"\\user"; - const std::wstring userConfig = userRoot + L"\\config"; - const std::wstring userSettings = userConfig + L"\\user_windows_terminal_settings.json"; Check(CreateDirectoryW(settingsDirectory.c_str(), NULL) != 0, "Could not create settings directory"); - Check(CreateDirectoryW(userRoot.c_str(), NULL) != 0, "Could not create user root"); - Check(CreateDirectoryW(userConfig.c_str(), NULL) != 0, "Could not create user config directory"); WriteFixture(defaults, "{\"source\":\"Cmder defaults\"}"); WriteFixture(userSettings, "{\"source\":\"user root\"}"); StartCmder(L"", false, L"", L"", L"", userRoot); + Check(lastTerminalPath == windowsTerminal + L"\\WindowsTerminal.exe", + "Windows Terminal did not take precedence over ConEmu"); Check(ReadFixture(settings) == ReadFixture(defaults), "First /c launch did not initialize shared defaults"); Check(ReadFixture(userSettings) == "{\"source\":\"user root\"}", "First /c launch changed user terminal settings"); WriteFixture(settings, "{\"source\":\"edited shared settings\"}"); StartCmder(L"", false, L"", L"", L"", userRoot); Check(ReadFixture(settings) == "{\"source\":\"edited shared settings\"}", "Subsequent /c launch overwrote shared settings"); Check(ReadFixture(userSettings) == "{\"source\":\"user root\"}", "Subsequent /c launch changed user terminal settings"); - Check(terminalLaunches == 5, "Startup did not reach the terminal launch boundary"); + Check(terminalLaunches == 14, "Startup did not reach the terminal launch boundary"); + + struct ProfileCase { const wchar_t* arguments; const wchar_t* profile; }; + const ProfileCase profileCases[] = { + {L"", L""}, + {L"cmd", L"Cmder"}, + {L"bash", L"Cmder - Bash"}, + {L"powershell", L"Cmder - PowerShell"}, + {L"PoWeRsHeLl", L"Cmder - PowerShell"}, + {L"/task \"Custom Profile\"", L"Custom Profile"}, + {L"/task bash", L"bash"}, + {L"/task cmd", L"cmd"} + }; + for (const wchar_t* selector : {L"", L"windows-terminal "}) { + for (const auto& profileCase : profileCases) { + const auto options = Parse(std::wstring(selector) + profileCase.arguments); + Check(!options.error && options.cmderTask == profileCase.profile, + "Windows Terminal profile selection did not parse"); + const int launches = terminalLaunches; + Check(_tWinMain(NULL, NULL, NULL, 0) == 0 && terminalLaunches == launches + 1, + "Windows Terminal profile selection did not launch"); + const std::wstring expectedArguments = *profileCase.profile + ? std::wstring(L" -p \"") + profileCase.profile + L"\"" : L""; + Check(lastTerminalPath == windowsTerminal + L"\\WindowsTerminal.exe" && + lastTerminalArguments == expectedArguments, + "Windows Terminal did not receive the selected profile"); + } + } + + for (const wchar_t* arguments : {L"-- new-tab cmd.exe /k echo hello", L"/x \"-p Custom\""}) { + const auto options = Parse(arguments); + Check(!options.error && options.cmderTask.empty(), + "Raw terminal arguments selected an implicit profile"); + Check(_tWinMain(NULL, NULL, NULL, 0) == 0 && + lastTerminalArguments == L" " + options.cmderTerminalArgs, + "Raw terminal arguments were changed by profile selection"); + } + + struct RegistrationCase { const wchar_t* arguments; const wchar_t* selector; bool single; bool userRoot; }; + const RegistrationCase registrationCases[] = { + {L"/REGISTER USER", L"", false, false}, + {L"conemu /REGISTER USER", L" conemu", false, false}, + {L"windows-terminal /REGISTER USER", L" windows-terminal", false, false}, + {L"conemu /single /REGISTER USER", L" conemu", true, false}, + {L"conemu /REGISTER USER /c", L" conemu", false, true} + }; + allowRegistryWrites = true; + for (const auto& registration : registrationCases) { + registeredCommands.clear(); + const std::wstring arguments = std::wstring(registration.arguments) + + (registration.userRoot ? L" \"" + userRoot + L"\"" : L""); + Check(!Parse(arguments).error && _tWinMain(NULL, NULL, NULL, 0) == 0, + "Terminal-specific registration failed"); + std::wstring expected = L"\"" + testExecutable + L"\"" + registration.selector; + if (registration.single) { expected += L" /single"; } + if (registration.userRoot) { expected += L" /c \"" + userRoot + L"\""; } + expected += L" \"%V\""; + Check(registeredCommands.size() == 4, "Not all Explorer menu commands were registered"); + for (const auto& command : registeredCommands) { + Check(command == expected, "Registered command lost the selected terminal or launcher options"); + } + } + allowRegistryWrites = false; Check(DeleteFileW(userSettings.c_str()) != 0, "Could not remove user settings fixture"); + Check(DeleteFileW(machineConfig.c_str()) != 0, + "Could not remove machine-specific ConEmu settings fixture"); Check(DeleteFileW(settings.c_str()) != 0, "Could not remove shared settings fixture"); Check(DeleteFileW(defaults.c_str()) != 0, "Could not remove default settings fixture"); Check(DeleteFileW((vendor + L"\\ConEmu.xml.default").c_str()) != 0, "Could not remove ConEmu default fixture"); + Check(DeleteFileW((conemu + L"\\ConEmu.exe").c_str()) != 0, "Could not remove ConEmu fixture executable"); + Check(DeleteFileW((conemu + L"\\ConEmu64.exe").c_str()) != 0, "Could not remove ConEmu64 fixture executable"); Check(DeleteFileW((conemu + L"\\ConEmu.xml").c_str()) != 0, "Could not remove ConEmu settings fixture"); Check(DeleteFileW((installationConfig + L"\\user-ConEmu.xml").c_str()) != 0, "Could not remove ConEmu user settings fixture"); + Check(DeleteFileW((installationConfig + L"\\user_windows_terminal_settings.json").c_str()) != 0, + "Could not remove Windows Terminal user settings fixture"); Check(RemoveDirectoryW(installationConfig.c_str()) != 0, "Could not remove installation config fixture"); Check(RemoveDirectoryW((userConfig + L"\\profile.d").c_str()) != 0, "Could not remove user profile directory"); Check(RemoveDirectoryW((userRoot + L"\\bin").c_str()) != 0, "Could not remove user bin directory"); Check(RemoveDirectoryW(userConfig.c_str()) != 0, "Could not remove user config directory"); Check(RemoveDirectoryW(userRoot.c_str()) != 0, "Could not remove user root"); Check(RemoveDirectoryW(settingsDirectory.c_str()) != 0, "Could not remove settings directory"); + Check(DeleteFileW((windowsTerminal + L"\\WindowsTerminal.exe").c_str()) != 0, "Could not remove Windows Terminal fixture executable"); Check(RemoveDirectoryW(windowsTerminal.c_str()) != 0, "Could not remove Windows Terminal fixture"); Check(RemoveDirectoryW(conemu.c_str()) != 0, "Could not remove ConEmu fixture"); Check(RemoveDirectoryW(vendor.c_str()) != 0, "Could not remove vendor fixture"); @@ -262,7 +527,10 @@ int wmain() { try { TestPathBounds(); + TestPathEnvironmentExpansion(); + TestLegacyConfigurationMigration(); TestArgumentParsing(); + Check(!overlappingEnvironmentExpansion, "Environment expansion used overlapping buffers"); std::cout << "Launcher regression tests passed.\n"; return 0; }