Debian Codegraph @

bypy/windows/portable.cpp

raw
1 /*
2 * portable.cpp
3 * Copyright (C) 2020 Kovid Goyal <kovid at kovidgoyal.net>
4 *
5 * Distributed under terms of the GPL3 license.
6 */
7
8 #ifndef UNICODE
9 #define UNICODE
10 #endif
11
12 #ifndef _UNICODE
13 #define _UNICODE
14 #endif
15
16 #include <Windows.h>
17 #include <tchar.h>
18 #include <wchar.h>
19 #include <stdio.h>
20 #include <string>
21 #include <stdlib.h>
22
23 #define BUFSIZE 4096
24
25
26 // error handling {{{
27 static void
28 show_error(LPCWSTR msg) {
29 MessageBeep(MB_ICONERROR);
30 MessageBoxW(NULL, msg, L"Error", MB_OK | MB_ICONERROR);
31 }
32
33 static void
34 show_detailed_error(LPCWSTR preamble, LPCWSTR msg, int code) {
35 LPTSTR buf;
36 buf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, sizeof(TCHAR) * (_tcslen(msg) + _tcslen(preamble) + 80));
37
38 _snwprintf_s(buf, LocalSize(buf) / sizeof(TCHAR), _TRUNCATE, L"%s\r\n %s (Error Code: %d)\r\n", preamble, msg, code);
39
40 show_error(buf);
41 LocalFree(buf);
42 }
43
44 static void
45 show_last_error_crt(LPCWSTR preamble) {
46 TCHAR buf[BUFSIZE];
47 int err = 0;
48
49 _get_errno(&err);
50 _tcserror_s(buf, BUFSIZE, err);
51 show_detailed_error(preamble, buf, err);
52 }
53
54 static void
55 show_last_error(LPCWSTR preamble) {
56 TCHAR *msg = NULL;
57 DWORD dw = GetLastError();
58
59 FormatMessage(
60 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
61 NULL,
62 dw,
63 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
64 (LPTSTR)&msg,
65 0,
66 NULL);
67
68 show_detailed_error(preamble, msg, (int)dw);
69 }
70
71
72 // }}}
73
74
75 static bool
76 get_app_dir(std::wstring &ans, std::wstring &exe_name) {
77 DWORD sz;
78 static wchar_t drive[_MAX_DRIVE] = {0};
79 static wchar_t buf[BUFSIZE] = {0}, dirpath[_MAX_DIR] = {0}, fname[_MAX_FNAME] = {0}, ext[_MAX_EXT] = {0};
80
81 sz = GetModuleFileName(NULL, buf, BUFSIZE);
82
83 if (sz == 0 || sz > BUFSIZE - 1) {
84 show_error(L"Failed to get path to portable launcher");
85 return false;
86 }
87
88 errno_t err = _wsplitpath_s(buf, drive, _MAX_DRIVE, dirpath, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT);
89
90 if (err != 0) {
91 show_last_error_crt(L"Failed to split path to portable launcher");
92 return false;
93 }
94 ans.append(drive);
95 ans.append(dirpath);
96 if (ans.length() > 58) {
97 std::wstring msg;
98 msg.append(L"Path to Calibre Portable (");
99 msg.append(ans);
100 msg.append(L") too long. It must be less than 59 characters.");
101 show_error(msg.c_str());
102 return false;
103 }
104 exe_name.append(fname);
105 exe_name.erase(exe_name.length() - sizeof("portable"), sizeof("portable"));
106 exe_name.append(ext);
107 return true;
108 }
109
110
111 static void
112 quote_argv(const std::wstring &arg, std::wstring &cmd_line) {
113 if (!arg.empty() && arg.find_first_of(L" \t\n\v\"") == arg.npos) {
114 cmd_line.append(arg);
115 return;
116 }
117 cmd_line.push_back(L'"');
118
119 for (auto iterator = arg.begin();; ++iterator) {
120 unsigned num_back_slashes = 0;
121
122 while (iterator != arg.end() && *iterator == L'\\') {
123 ++iterator;
124 ++num_back_slashes;
125 }
126
127 if (iterator == arg.end()) {
128 //
129 // Escape all backslashes, but let the terminating
130 // double quotation mark we add below be interpreted
131 // as a metacharacter.
132 //
133
134 cmd_line.append(num_back_slashes * 2, L'\\');
135 break;
136 } else if (*iterator == L'"') {
137 //
138 // Escape all backslashes and the following
139 // double quotation mark.
140 //
141
142 cmd_line.append(num_back_slashes * 2 + 1, L'\\');
143 cmd_line.push_back(*iterator);
144 } else {
145 //
146 // Backslashes aren't special here.
147 //
148
149 cmd_line.append(num_back_slashes, L'\\');
150 cmd_line.push_back(*iterator);
151 }
152 }
153
154 cmd_line.push_back(L'"');
155 }
156
157 static int
158 launch_exe(LPCWSTR exe_path, const std::wstring &cmd_line, LPCWSTR config_dir) {
159 DWORD dwFlags = 0;
160 STARTUPINFO si;
161 PROCESS_INFORMATION pi;
162 if (cmd_line.length() > BUFSIZE - 4) {
163 show_error(L"Path to executable in portable folder too long.");
164 return 1;
165 }
166
167 if (!SetEnvironmentVariableW(L"CALIBRE_CONFIG_DIRECTORY", config_dir)) {
168 show_last_error(L"Failed to set environment variables");
169 return 1;
170 }
171
172 if (!SetEnvironmentVariableW(L"CALIBRE_PORTABLE_BUILD", exe_path)) {
173 show_last_error(L"Failed to set environment variables");
174 return 1;
175 }
176
177 dwFlags = CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP;
178
179 ZeroMemory(&si, sizeof(si));
180 si.cb = sizeof(si);
181 ZeroMemory(&pi, sizeof(pi));
182 static wchar_t mutable_cmdline[BUFSIZE] = {0};
183 cmd_line.copy(mutable_cmdline, BUFSIZE - 1);
184
185 if (!CreateProcess(
186 NULL,
187 mutable_cmdline,
188 NULL, // Process handle not inheritable
189 NULL, // Thread handle not inheritable
190 FALSE, // Set handle inheritance to FALSE
191 dwFlags, // Creation flags http://msdn.microsoft.com/en-us/library/ms684863(v=vs.85).aspx
192 NULL, // Use parent's environment block
193 NULL, // Use parent's starting directory
194 &si, // Pointer to STARTUPINFO structure
195 &pi // Pointer to PROCESS_INFORMATION structure
196 )) {
197 std::wstring message(L"Failed to launch: ");
198 message.append(mutable_cmdline);
199 show_last_error(message.c_str());
200 }
201
202 // Close process and thread handles.
203 CloseHandle(pi.hProcess);
204 CloseHandle(pi.hThread);
205 return 0;
206 }
207
208
209 int WINAPI
210 wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR orig_cmd_line, int nCmdShow) {
211 std::wstring exe, config_dir, cmd_line, application_dir, exe_name;
212
213 if (!get_app_dir(application_dir, exe_name)) return 1;
214 config_dir.append(application_dir);
215 config_dir.append(L"Calibre Settings");
216 exe.append(application_dir);
217 exe.append(L"Calibre\\");
218 exe.append(exe_name);
219
220 int argc;
221 wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
222 if (argv == NULL) {
223 show_last_error(L"Failed to convert cmdline to argv array");
224 return 1;
225 }
226 quote_argv(exe, cmd_line);
227 for (int i = 1; i < argc; i++) {
228 std::wstring arg(argv[i]);
229 cmd_line.push_back(L' ');
230 quote_argv(arg, cmd_line);
231 }
232 LocalFree(argv);
233 return launch_exe(exe.c_str(), cmd_line.c_str(), config_dir.c_str());
234 }