forked from Bush2021/chrome_plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.h
553 lines (488 loc) · 16 KB
/
utils.h
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
#ifndef UTILS_H_
#define UTILS_H_
#include <algorithm>
#include <cctype>
#include <functional>
#include <string>
#include <vector>
#include <windows.h>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#include "FastSearch.h"
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/app/chrome_command_ids.h?q=chrome_command_ids.h&ss=chromium%2Fchromium%2Fsrc
#define IDC_NEW_TAB 34014
#define IDC_CLOSE_TAB 34015
#define IDC_SELECT_NEXT_TAB 34016
#define IDC_SELECT_PREVIOUS_TAB 34017
#define IDC_SELECT_TAB_0 34018
#define IDC_SELECT_TAB_1 34019
#define IDC_SELECT_TAB_2 34020
#define IDC_SELECT_TAB_3 34021
#define IDC_SELECT_TAB_4 34022
#define IDC_SELECT_TAB_5 34023
#define IDC_SELECT_TAB_6 34024
#define IDC_SELECT_TAB_7 34025
#define IDC_SELECT_LAST_TAB 34026
#define IDC_SHOW_TRANSLATE 35009
#define IDC_UPGRADE_DIALOG 40024
#define IDC_FULLSCREEN 34030
#define IDC_CLOSE_FIND_OR_STOP 37003
#define IDC_WINDOW_CLOSE_OTHER_TABS 35023
// String manipulation function.
std::wstring Format(const wchar_t* format, va_list args) {
std::vector<wchar_t> buffer;
size_t length = _vscwprintf(format, args);
buffer.resize((length + 1) * sizeof(wchar_t));
_vsnwprintf_s(&buffer[0], length + 1, length, format, args);
return std::wstring(&buffer[0]);
}
std::wstring Format(const wchar_t* format, ...) {
va_list args;
va_start(args, format);
auto str = Format(format, args);
va_end(args);
return str;
}
std::string wstring_to_string(const std::wstring& wstr) {
std::string strTo;
auto szTo = new char[wstr.length() + 1];
szTo[wstr.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo,
static_cast<int>(wstr.length()), nullptr, nullptr);
strTo = szTo;
delete[] szTo;
return strTo;
}
// Specify the delimiter and wrapper to split the string.
std::vector<std::wstring> StringSplit(const std::wstring& str,
const wchar_t delim,
const std::wstring& enclosure) {
std::vector<std::wstring> result;
std::wstring::size_type start = 0;
std::wstring::size_type end = str.find(delim);
while (end != std::wstring::npos) {
std::wstring name = str.substr(start, end - start);
if (!enclosure.empty() && !name.empty() &&
name.front() == enclosure.front()) {
name.erase(0, 1);
}
if (!enclosure.empty() && !name.empty() &&
name.back() == enclosure.back()) {
name.erase(name.size() - 1);
}
result.push_back(name);
start = end + 1;
end = str.find(delim, start);
}
if (start < str.length()) {
std::wstring name = str.substr(start);
if (!enclosure.empty() && !name.empty() &&
name.front() == enclosure.front()) {
name.erase(0, 1);
}
if (!enclosure.empty() && !name.empty() &&
name.back() == enclosure.back()) {
name.erase(name.size() - 1);
}
result.push_back(name);
}
return result;
}
// Compression html.
std::string& ltrim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
[](int ch) { return !std::isspace(ch); }));
return s;
}
std::string& rtrim(std::string& s) {
s.erase(std::find_if(s.rbegin(), s.rend(),
[](int ch) { return !std::isspace(ch); })
.base(),
s.end());
return s;
}
std::string& trim(std::string& s) {
return ltrim(rtrim(s));
}
std::vector<std::string> split(const std::string& text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
std::string temp = text.substr(start, end - start);
tokens.push_back(temp);
start = end + 1;
}
std::string temp = text.substr(start);
tokens.push_back(temp);
return tokens;
}
void compression_html(std::string& html) {
auto lines = split(html, '\n');
html.clear();
for (auto& line : lines) {
html += "\n";
html += trim(line);
}
}
bool ReplaceStringInPlace(std::string& subject,
const std::string& search,
const std::string& replace) {
bool find = false;
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
find = true;
}
return find;
}
bool ReplaceStringInPlace(std::wstring& subject,
const std::wstring& search,
const std::wstring& replace) {
bool find = false;
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::wstring::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
find = true;
}
return find;
}
std::wstring QuoteSpaceIfNeeded(const std::wstring& str) {
if (str.find(L' ') == std::wstring::npos)
return std::move(str);
std::wstring escaped(L"\"");
for (auto c : str) {
if (c == L'"')
escaped += L'"';
escaped += c;
}
escaped += L'"';
return std::move(escaped);
}
std::wstring JoinArgsString(std::vector<std::wstring> lines,
const std::wstring& delimiter) {
std::wstring text;
bool first = true;
for (auto& line : lines) {
if (!first)
text += delimiter;
else
first = false;
text += QuoteSpaceIfNeeded(line);
}
return text;
}
// Memory and module search functions.
// Search memory.
uint8_t* memmem(uint8_t* src, int n, const uint8_t* sub, int m) {
return (uint8_t*)FastSearch(src, n, sub, m);
}
uint8_t* SearchModuleRaw(HMODULE module, const uint8_t* sub, int m) {
uint8_t* buffer = (uint8_t*)module;
PIMAGE_NT_HEADERS nt_header =
(PIMAGE_NT_HEADERS)(buffer + ((PIMAGE_DOS_HEADER)buffer)->e_lfanew);
PIMAGE_SECTION_HEADER section =
(PIMAGE_SECTION_HEADER)((char*)nt_header + sizeof(DWORD) +
sizeof(IMAGE_FILE_HEADER) +
nt_header->FileHeader.SizeOfOptionalHeader);
for (int i = 0; i < nt_header->FileHeader.NumberOfSections; ++i) {
if (strcmp((const char*)section[i].Name, ".text") == 0) {
return memmem(buffer + section[i].PointerToRawData,
section[i].SizeOfRawData, sub, m);
break;
}
}
return nullptr;
}
uint8_t* SearchModuleRaw2(HMODULE module, const uint8_t* sub, int m) {
uint8_t* buffer = (uint8_t*)module;
PIMAGE_NT_HEADERS nt_header =
(PIMAGE_NT_HEADERS)(buffer + ((PIMAGE_DOS_HEADER)buffer)->e_lfanew);
PIMAGE_SECTION_HEADER section =
(PIMAGE_SECTION_HEADER)((char*)nt_header + sizeof(DWORD) +
sizeof(IMAGE_FILE_HEADER) +
nt_header->FileHeader.SizeOfOptionalHeader);
for (int i = 0; i < nt_header->FileHeader.NumberOfSections; ++i) {
if (strcmp((const char*)section[i].Name, ".rdata") == 0) {
return memmem(buffer + section[i].PointerToRawData,
section[i].SizeOfRawData, sub, m);
break;
}
}
return nullptr;
}
// bool WriteMemory(PBYTE BaseAddress, PBYTE Buffer, DWORD nSize) {
// DWORD ProtectFlag = 0;
// if (VirtualProtectEx(GetCurrentProcess(), BaseAddress, nSize,
// PAGE_EXECUTE_READWRITE, &ProtectFlag)) {
// memcpy(BaseAddress, Buffer, nSize);
// FlushInstructionCache(GetCurrentProcess(), BaseAddress, nSize);
// VirtualProtectEx(GetCurrentProcess(), BaseAddress, nSize, ProtectFlag,
// &ProtectFlag);
// return true;
// }
// return false;
// }
// Path and file manipulation functions.
// Get the directory where the application is located.
std::wstring GetAppDir() {
wchar_t path[MAX_PATH];
::GetModuleFileName(nullptr, path, MAX_PATH);
::PathRemoveFileSpec(path);
return path;
}
bool isEndWith(const wchar_t* s, const wchar_t* sub) {
if (!s || !sub)
return false;
size_t len1 = wcslen(s);
size_t len2 = wcslen(sub);
if (len2 > len1)
return false;
return !_memicmp(s + len1 - len2, sub, len2 * sizeof(wchar_t));
}
const std::wstring kIniPath = GetAppDir() + L"\\chrome++.ini";
// Prase the INI file.
std::wstring GetIniString(const std::wstring& section,
const std::wstring& key,
const std::wstring& default_value) {
std::vector<TCHAR> buffer(100);
DWORD bytesread = 0;
do {
bytesread = ::GetPrivateProfileStringW(
section.c_str(), key.c_str(), default_value.c_str(), buffer.data(),
(DWORD)buffer.size(), kIniPath.c_str());
if (bytesread >= buffer.size() - 1) {
buffer.resize(buffer.size() * 2);
} else {
break;
}
} while (true);
return std::wstring(buffer.data());
}
// Canonicalize the path.
std::wstring CanonicalizePath(const std::wstring& path) {
TCHAR temp[MAX_PATH];
::PathCanonicalize(temp, path.data());
return std::wstring(temp);
}
// Get the absolute path.
std::wstring GetAbsolutePath(const std::wstring& path) {
wchar_t buffer[MAX_PATH];
::GetFullPathNameW(path.c_str(), MAX_PATH, buffer, nullptr);
return buffer;
}
// Expand environment variables in the path.
std::wstring ExpandEnvironmentPath(const std::wstring& path) {
std::vector<wchar_t> buffer(MAX_PATH);
size_t ExpandedLength = ::ExpandEnvironmentStrings(path.c_str(), &buffer[0],
(DWORD)buffer.size());
if (ExpandedLength > buffer.size()) {
buffer.resize(ExpandedLength);
ExpandedLength = ::ExpandEnvironmentStrings(path.c_str(), &buffer[0],
(DWORD)buffer.size());
}
return std::wstring(&buffer[0], 0, ExpandedLength);
}
// Debug log function.
void DebugLog(const wchar_t* format, ...) {
// va_list args;
// va_start(args, format);
// auto str = Format(format, args);
// va_end(args);
// str = Format(L"[chrome++] %s\n", str.c_str());
// std::string nstr = wstring_to_string(str);
// const char* cstr = nstr.c_str();
// FILE* fp = nullptr;
// std::wstring logPath = GetAppDir() + L"\\Chrome++_Debug.log";
// _wfopen_s(&fp, logPath.c_str(), L"a+");
// if (fp) {
// fwrite(cstr, strlen(cstr), 1, fp);
// fclose(fp);
// }
}
// Window and message processing functions.
HWND GetTopWnd(HWND hwnd) {
while (::GetParent(hwnd) && ::IsWindowVisible(::GetParent(hwnd))) {
hwnd = ::GetParent(hwnd);
}
return hwnd;
}
void ExecuteCommand(int id, HWND hwnd = 0) {
if (hwnd == 0)
hwnd = GetForegroundWindow();
// hwnd = GetTopWnd(hwnd);
// hwnd = GetForegroundWindow();
// PostMessage(hwnd, WM_SYSCOMMAND, id, 0);
::SendMessageTimeoutW(hwnd, WM_SYSCOMMAND, id, 0, 0, 1000, 0);
}
HANDLE RunExecute(const wchar_t* command, WORD show = SW_SHOW) {
int nArgs = 0;
std::vector<std::wstring> command_line;
LPWSTR* szArglist = CommandLineToArgvW(command, &nArgs);
for (int i = 0; i < nArgs; ++i) {
command_line.push_back(QuoteSpaceIfNeeded(szArglist[i]));
}
LocalFree(szArglist);
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.lpFile = command_line[0].c_str();
ShExecInfo.nShow = show;
std::wstring parameter;
for (size_t i = 1; i < command_line.size(); ++i) {
parameter += command_line[i];
parameter += L" ";
}
if (command_line.size() > 1) {
ShExecInfo.lpParameters = parameter.c_str();
}
if (ShellExecuteEx(&ShExecInfo)) {
return ShExecInfo.hProcess;
}
return nullptr;
}
bool IsFullScreen(HWND hwnd) {
RECT windowRect;
return (GetWindowRect(hwnd, &windowRect) &&
(windowRect.left == 0 && windowRect.top == 0 &&
windowRect.right == GetSystemMetrics(SM_CXSCREEN) &&
windowRect.bottom == GetSystemMetrics(SM_CYSCREEN)));
}
// Keyboard and mouse input functions.
// Send the combined key operation.
// class SendKeys {
// public:
// template <typename... T>
// SendKeys(T... keys) {
// std::vector<int> keys_ = {keys...};
// for (auto& key : keys_) {
// INPUT input = {0};
// input.type = INPUT_KEYBOARD;
// input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
// input.ki.wVk = key;
// // Correct the mouse message
// switch (key) {
// case VK_MBUTTON:
// input.type = INPUT_MOUSE;
// input.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
// break;
// }
// inputs_.push_back(input);
// }
// SendInput((UINT)inputs_.size(), &inputs_[0], sizeof(INPUT));
// }
// ~SendKeys() {
// for (auto& input : inputs_) {
// input.ki.dwFlags |= KEYEVENTF_KEYUP;
// // Correct the mouse message
// switch (input.ki.wVk) {
// case VK_MBUTTON:
// input.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
// break;
// }
// }
// SendInput((UINT)inputs_.size(), &inputs_[0], sizeof(INPUT));
// }
// private:
// std::vector<INPUT> inputs_;
// };
inline void SendMouseMove(int x, int y) {
INPUT input = {0};
input.type = INPUT_MOUSE;
input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
input.mi.dx = (x * 65536) / GetSystemMetrics(SM_CXSCREEN);
input.mi.dy = (y * 65536) / GetSystemMetrics(SM_CYSCREEN);
input.mi.dwExtraInfo = MAGIC_CODE;
SendInput(1, &input, sizeof(INPUT));
}
template <typename... T>
void SendKey(T&&... keys) {
std::vector<typename std::common_type<T...>::type> keys_ = {
std::forward<T>(keys)...};
std::vector<INPUT> inputs{};
inputs.reserve(keys_.size() * 2);
for (auto& key : keys_) {
INPUT input = {0};
// Adjust mouse messages
switch (key) {
case VK_RBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = GetSystemMetrics(SM_SWAPBUTTON) == TRUE
? MOUSEEVENTF_LEFTDOWN
: MOUSEEVENTF_RIGHTDOWN;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
case VK_LBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = GetSystemMetrics(SM_SWAPBUTTON) == TRUE
? MOUSEEVENTF_RIGHTDOWN
: MOUSEEVENTF_LEFTDOWN;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
case VK_MBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
default:
input.type = INPUT_KEYBOARD;
input.ki.wVk = (WORD)key;
input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
input.ki.dwExtraInfo = MAGIC_CODE;
break;
}
inputs.emplace_back(std::move(input));
}
for (auto& key : keys_) {
INPUT input = {0};
// Adjust mouse messages
switch (key) {
case VK_RBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = GetSystemMetrics(SM_SWAPBUTTON) == TRUE
? MOUSEEVENTF_LEFTUP
: MOUSEEVENTF_RIGHTUP;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
case VK_LBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = GetSystemMetrics(SM_SWAPBUTTON) == TRUE
? MOUSEEVENTF_RIGHTUP
: MOUSEEVENTF_LEFTUP;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
case VK_MBUTTON:
input.type = INPUT_MOUSE;
input.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
input.mi.dwExtraInfo = MAGIC_CODE;
break;
default:
input.type = INPUT_KEYBOARD;
input.ki.dwFlags = KEYEVENTF_KEYUP;
input.ki.wVk = (WORD)key;
input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP;
input.ki.dwExtraInfo = MAGIC_CODE;
break;
}
inputs.emplace_back(std::move(input));
}
SendInput((UINT)inputs.size(), &inputs[0], sizeof(INPUT));
}
// Send a single key operation.
void SendOneMouse(int mouse) {
// Swap the left and right mouse buttons (if defined).
if (::GetSystemMetrics(SM_SWAPBUTTON) == TRUE) {
if (mouse == MOUSEEVENTF_RIGHTDOWN)
mouse = MOUSEEVENTF_LEFTDOWN;
else if (mouse == MOUSEEVENTF_RIGHTUP)
mouse = MOUSEEVENTF_LEFTUP;
}
INPUT input[1];
memset(input, 0, sizeof(input));
input[0].type = INPUT_MOUSE;
input[0].mi.dwFlags = mouse;
input[0].mi.dwExtraInfo = MAGIC_CODE;
::SendInput(1, input, sizeof(INPUT));
}
#endif // UTILS_H_