cmder/launcher/src/CmderLauncher.cpp

478 lines
14 KiB
C++
Raw Normal View History

#include <windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include "resource.h"
#include <vector>
2018-03-13 23:38:27 +08:00
#include <shlobj.h>
2018-03-14 06:40:07 +08:00
#include <regex>
#include <iostream>
#pragma comment(lib, "Shlwapi.lib")
#ifndef UNICODE
#error "Must be compiled with unicode support."
#endif
#define USE_TASKBAR_API (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define MB_TITLE L"Cmder Launcher"
#define SHELL_MENU_REGISTRY_PATH_BACKGROUND L"Directory\\Background\\shell\\Cmder"
#define SHELL_MENU_REGISTRY_PATH_LISTITEM L"Directory\\shell\\Cmder"
#define streqi(a, b) (_wcsicmp((a), (b)) == 0)
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define FAIL_ON_ERROR(x) { DWORD ec; if ((ec = (x)) != ERROR_SUCCESS) { ShowErrorAndExit(ec, __WFUNCTION__, __LINE__); } }
void ShowErrorAndExit(DWORD ec, const wchar_t * func, int line)
{
wchar_t * buffer;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2016-04-14 02:16:58 +08:00
NULL, ec, 0, (LPWSTR)&buffer, 0, NULL) == 0)
{
buffer = L"Unknown error. FormatMessage failed.";
}
wchar_t message[1024];
swprintf_s(message, L"%s\nFunction: %s\nLine: %d", buffer, func, line);
LocalFree(buffer);
MessageBox(NULL, message, MB_TITLE, MB_OK | MB_ICONERROR);
exit(1);
}
typedef struct _option
{
std::wstring name;
bool hasVal;
std::wstring value;
bool set;
} option;
typedef std::pair<std::wstring, std::wstring> optpair;
2015-08-19 07:13:22 +08:00
bool FileExists(const wchar_t * filePath)
{
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
2018-03-13 23:38:27 +08:00
void StartCmder(std::wstring path = L"", bool is_single_mode = false, std::wstring taskName = L"", std::wstring cfgRoot = L"")
{
#if USE_TASKBAR_API
wchar_t appId[MAX_PATH] = { 0 };
#endif
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 };
2018-03-13 23:38:27 +08:00
wchar_t defaultCfgPath[MAX_PATH] = { 0 };
wchar_t conEmuPath[MAX_PATH] = { 0 };
2018-03-13 23:38:27 +08:00
wchar_t configDirPath[MAX_PATH] = { 0 };
wchar_t userConfigDirPath[MAX_PATH] = { 0 };
wchar_t userBinDirPath[MAX_PATH] = { 0 };
wchar_t userProfiledDirPath[MAX_PATH] = { 0 };
wchar_t args[MAX_PATH * 2 + 256] = { 0 };
2018-03-13 23:38:27 +08:00
std::wstring cmderStart = path;
std::wstring cmderTask = taskName;
std::copy(cfgRoot.begin(), cfgRoot.end(), userConfigDirPath);
userConfigDirPath[cfgRoot.length()] = 0;
GetModuleFileName(NULL, exeDir, sizeof(exeDir));
#if USE_TASKBAR_API
wcscpy_s(appId, exeDir);
#endif
PathRemoveFileSpec(exeDir);
PathCombine(icoPath, exeDir, L"icons\\cmder.ico");
2018-03-13 23:38:27 +08:00
PathCombine(configDirPath, exeDir, L"config");
if (wcscmp(userConfigDirPath, L"") == 0)
{
PathCombine(userConfigDirPath, exeDir, L"config");
}
else
{
PathCombine(userBinDirPath, userConfigDirPath, L"bin");
SHCreateDirectoryEx(0, userBinDirPath, 0);
PathCombine(userConfigDirPath, userConfigDirPath, L"config");
SHCreateDirectoryEx(0, userConfigDirPath, 0);
PathCombine(userProfiledDirPath, userConfigDirPath, L"profile.d");
SHCreateDirectoryEx(0, userProfiledDirPath, 0);
}
// Set path to vendored ConEmu config file
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
// Set path to Cmder default ConEmu config file
PathCombine(defaultCfgPath, exeDir, L"config\\ConEmu.xml");
// Check for machine-specific then user config source file.
2018-03-13 23:38:27 +08:00
PathCombine(cpuCfgPath, userConfigDirPath, L"ConEmu-%COMPUTERNAME%.xml");
2016-10-03 07:34:40 +08:00
ExpandEnvironmentStrings(cpuCfgPath, cpuCfgPath, sizeof(cpuCfgPath) / sizeof(cpuCfgPath[0]));
2018-03-13 23:38:27 +08:00
PathCombine(userCfgPath, userConfigDirPath, L"user-ConEmu.xml");
2016-04-14 02:16:58 +08:00
if (PathFileExists(cpuCfgPath)) {
2018-03-13 23:38:27 +08:00
if (PathFileExists(cfgPath)) {
if (!CopyFile(cfgPath, cpuCfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy ConEmu.xml file to ConEmu-%COMPUTERNAME%.xml backup location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy ConEmu.xml file to ConEmu-%COMPUTERNAME%.xml backup location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
else
{
if (!CopyFile(cpuCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy ConEmu-%COMPUTERNAME%.xml file to vendored ConEmu.xml location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy ConEmu-%COMPUTERNAME%.xml file to vendored ConEmu.xml location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
}
else if (PathFileExists(userCfgPath)) {
2018-03-13 23:38:27 +08:00
if (PathFileExists(cfgPath)) {
if (!CopyFile(cfgPath, userCfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy ConEmu.xml file to backup location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy ConEmu.xml file to backup location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
else
{
if (!CopyFile(userCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy ConEmu.xml file to vendored ConEmu.xml location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy ConEmu.xml file to vendored ConEmu.xml location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
}
else if (PathFileExists(cfgPath)) {
if (!CopyFile(cfgPath, userCfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy ConEmu.xml file to user-conemu.xml backup location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy ConEmu.xml file to user-conemu.xml backup location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
else {
2018-03-13 23:38:27 +08:00
if (!CopyFile(defaultCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
2018-03-14 06:40:07 +08:00
? L"Failed to copy Cmder default ConEmu.xml file to vendored ConEmu.xml location! Restart Cmder as Administrator."
2018-03-13 23:38:27 +08:00
: L"Failed to copy Cmder default ConEmu.xml file to vendored ConEmu.xml location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
SYSTEM_INFO sysInfo;
GetNativeSystemInfo(&sysInfo);
if (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu64.exe");
}
else {
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");
}
2018-03-13 23:38:27 +08:00
if (streqi(cmderStart.c_str(), L""))
2016-04-14 02:16:58 +08:00
{
TCHAR buff[MAX_PATH];
const DWORD ret = GetEnvironmentVariable(L"USERPROFILE", buff, MAX_PATH);
2018-03-13 23:38:27 +08:00
cmderStart = buff;
2016-04-14 02:16:58 +08:00
}
if (is_single_mode)
{
2018-03-13 23:38:27 +08:00
if (!streqi(cmderTask.c_str(), L"")) {
swprintf_s(args, L"%s /single /Icon \"%s\" /Title Cmder /dir \"%s\" /run {%s}", args, icoPath, cmderStart.c_str(), cmderTask.c_str());
}
else {
swprintf_s(args, L"%s /single /Icon \"%s\" /Title Cmder /dir \"%s\"", args, icoPath, cmderStart.c_str());
}
}
else
{
2018-03-13 23:38:27 +08:00
if (!streqi(cmderTask.c_str(), L"")) {
swprintf_s(args, L"/Icon \"%s\" /Title Cmder /dir \"%s\" /run {%s}", icoPath, cmderStart.c_str(), cmderTask.c_str());
}
else {
swprintf_s(args, L"%s /Icon \"%s\" /Title Cmder /dir \"%s\"", args, icoPath, cmderStart.c_str());
}
}
2018-01-09 02:22:42 +08:00
SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
2018-03-13 23:38:27 +08:00
if (wcscmp(userConfigDirPath, configDirPath) != 0)
{
SetEnvironmentVariable(L"CMDER_USER_CONFIG", userConfigDirPath);
SetEnvironmentVariable(L"CMDER_USER_BIN", userBinDirPath);
}
2018-01-09 02:22:42 +08:00
// Ensure EnvironmentVariables are propagated.
STARTUPINFO si = { 0 };
2018-03-13 23:38:27 +08:00
si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
si.lpTitle = appId;
si.dwFlags = STARTF_TITLEISAPPID;
#endif
PROCESS_INFORMATION pi;
if (!CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) {
2018-01-09 02:22:42 +08:00
MessageBox(NULL, _T("Unable to create the ConEmu process!"), _T("Error"), MB_OK);
return;
}
LRESULT lr = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 5000, NULL);
2016-04-14 02:16:58 +08:00
lr = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"Environment", SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 5000, NULL); // For Windows >= 8
}
bool IsUserOnly(std::wstring opt)
{
bool userOnly;
if (streqi(opt.c_str(), L"ALL"))
{
userOnly = false;
}
else if (streqi(opt.c_str(), L"USER"))
{
userOnly = true;
}
else
{
MessageBox(NULL, L"Unrecognized option for /REGISTER or /UNREGISTER. Must be either ALL or USER.", MB_TITLE, MB_OK);
exit(1);
}
return userOnly;
}
HKEY GetRootKey(std::wstring opt)
{
HKEY root;
if (IsUserOnly(opt))
{
2016-04-14 02:16:58 +08:00
FAIL_ON_ERROR(RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &root, NULL));
}
else
{
root = HKEY_CLASSES_ROOT;
}
return root;
}
void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
// First, get the paths we will use
wchar_t exePath[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, exePath, sizeof(exePath));
2018-03-14 06:40:07 +08:00
wchar_t commandStr[MAX_PATH + 20] = { 0 };
swprintf_s(commandStr, L"\"%s\" \"%%V\"", exePath);
2018-03-14 06:40:07 +08:00
// Now that we have `commandStr`, it's OK to change `exePath`...
PathRemoveFileSpec(exePath);
2018-03-14 06:40:07 +08:00
PathCombine(icoPath, exePath, L"icons\\cmder.ico");
2018-03-14 06:40:07 +08:00
// Now set the registry keys
HKEY root = GetRootKey(opt);
2018-03-14 06:40:07 +08:00
HKEY cmderKey;
FAIL_ON_ERROR(RegCreateKeyEx(root, keyBaseName, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
2018-03-14 06:40:07 +08:00
FAIL_ON_ERROR(RegSetValue(cmderKey, L"", REG_SZ, L"Cmder Here", NULL));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"NoWorkingDirectory", 0, REG_SZ, (BYTE *)L"", 2));
2018-03-14 06:40:07 +08:00
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"Icon", 0, REG_SZ, (BYTE *)icoPath, wcslen(icoPath) * sizeof(wchar_t)));
2018-03-14 06:40:07 +08:00
HKEY command;
FAIL_ON_ERROR(RegCreateKeyEx(cmderKey, L"command", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL));
2018-03-14 06:40:07 +08:00
FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL));
2018-03-14 06:40:07 +08:00
RegCloseKey(command);
RegCloseKey(cmderKey);
RegCloseKey(root);
}
void UnregisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
HKEY root = GetRootKey(opt);
HKEY cmderKey;
2016-04-14 02:16:58 +08:00
FAIL_ON_ERROR(RegCreateKeyEx(root, keyBaseName, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
2014-08-27 06:52:49 +08:00
FAIL_ON_ERROR(RegDeleteTree(cmderKey, NULL));
RegCloseKey(cmderKey);
RegCloseKey(root);
}
2018-03-13 23:38:27 +08:00
struct cmderOptions
{
std::wstring cmderCfgRoot = L"";
std::wstring cmderStart = L"";
std::wstring cmderTask = L"";
std::wstring cmderRegScope = L"USER";
bool cmderSingle = false;
bool registerApp = false;
bool unRegisterApp = false;
bool error = false;
};
cmderOptions GetOption()
{
cmderOptions cmderOptions;
LPWSTR *szArgList;
int argCount;
szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);
for (int i = 1; i < argCount; i++)
{
// MessageBox(NULL, szArgList[i], L"Arglist contents", MB_OK);
if (_wcsicmp(L"/c", szArgList[i]) == 0)
{
TCHAR userProfile[MAX_PATH];
const DWORD ret = GetEnvironmentVariable(L"USERPROFILE", userProfile, MAX_PATH);
wchar_t cmderCfgRoot[MAX_PATH] = { 0 };
PathCombine(cmderCfgRoot, userProfile, L"cmder_cfg");
cmderOptions.cmderCfgRoot = cmderCfgRoot;
if (szArgList[i + 1] != NULL && szArgList[i + 1][0] != '/') {
cmderOptions.cmderCfgRoot = szArgList[i + 1];
i++;
}
}
else if (_wcsicmp(L"/start", szArgList[i]) == 0)
{
if (PathFileExists(szArgList[i + 1]))
{
cmderOptions.cmderStart = szArgList[i + 1];
i++;
}
else {
MessageBox(NULL, szArgList[i + 1], L"/START - Folder doses not exist!", MB_OK);
}
}
else if (_wcsicmp(L"/task", szArgList[i]) == 0)
{
cmderOptions.cmderTask = szArgList[i + 1];
i++;
}
else if (_wcsicmp(L"/single", szArgList[i]) == 0)
{
cmderOptions.cmderSingle = true;
}
else if (_wcsicmp(L"/register", szArgList[i]) == 0)
{
cmderOptions.registerApp = true;
cmderOptions.unRegisterApp = false;
if (szArgList[i + 1] != NULL)
2018-03-14 06:40:07 +08:00
{
2018-03-13 23:38:27 +08:00
if (_wcsicmp(L"all", szArgList[i + 1]) == 0 || _wcsicmp(L"user", szArgList[i + 1]) == 0)
{
cmderOptions.cmderRegScope = szArgList[i + 1];
i++;
}
}
}
else if (_wcsicmp(L"/unregister", szArgList[i]) == 0)
{
cmderOptions.unRegisterApp = true;
cmderOptions.registerApp = false;
if (szArgList[i + 1] != NULL)
{
if (_wcsicmp(L"all", szArgList[i + 1]) == 0 || _wcsicmp(L"user", szArgList[i + 1]) == 0)
{
cmderOptions.cmderRegScope = szArgList[i + 1];
i++;
}
}
}
else if (cmderOptions.cmderStart == L"" && PathFileExists(szArgList[i]))
{
cmderOptions.cmderStart = szArgList[i];
}
else {
MessageBox(NULL, L"Unrecognized parameter.\n\nValid options:\n\n /c [CMDER User Root Path]\n\n /task [ConEmu Task Name]\n\n [/start [Start in Path] | [Start in Path]]\n\n /single\n\nor\n\n /register [USER | ALL]\n\nor\n\n /unregister [USER | ALL]\n", MB_TITLE, MB_OK);
cmderOptions.error = true;
}
}
LocalFree(szArgList);
return cmderOptions;
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
2018-03-13 23:38:27 +08:00
cmderOptions cmderOptions = GetOption();
2018-03-14 06:40:07 +08:00
if (cmderOptions.registerApp == true) {
2018-03-13 23:38:27 +08:00
RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
RegisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
2018-03-14 06:40:07 +08:00
else if (cmderOptions.unRegisterApp == true)
{
2018-03-13 23:38:27 +08:00
UnregisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
UnregisterShellMenu(cmderOptions.cmderRegScope, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
2018-03-13 23:38:27 +08:00
else if (cmderOptions.error == true)
2017-06-17 22:29:06 +08:00
{
2018-03-13 23:38:27 +08:00
return 1;
}
else
{
2018-03-13 23:38:27 +08:00
StartCmder(cmderOptions.cmderStart, cmderOptions.cmderSingle, cmderOptions.cmderTask, cmderOptions.cmderCfgRoot);
}
2018-03-14 06:40:07 +08:00
return 0;
2014-01-22 02:25:24 +08:00
}