Debian Codegraph @

Contrib/Makensisw/utils.cpp

raw
1 /*
2 Copyright (c) 2002 Robert Rainwater
3 Contributors: Justin Frankel, Fritz Elfert, Amir Szekely, Sunil Kamath, Joost Verburg
4
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
20
21 Unicode support by Jim Park -- 08/20/2007
22
23 */
24
25 #include "makensisw.h"
26 #include "resource.h"
27 #include "toolbar.h"
28 #include <shlwapi.h>
29
30 #ifndef MONITOR_DEFAULTTONEAREST
31 #define MONITOR_DEFAULTTONEAREST 2
32 WINUSERAPI HMONITOR WINAPI MonitorFromWindow(HWND hwnd, DWORD dwFlags);
33 #endif
34 #ifndef GRADIENT_FILL_RECT_H
35 #define GRADIENT_FILL_RECT_H 0
36 #if !defined(_WIN32_WINNT) || _WIN32_WINNT-0 < 0x0410
37 WINGDIAPI BOOL WINAPI GradientFill(HDC,TRIVERTEX*,ULONG,PVOID,ULONG,ULONG);
38 #endif
39 #endif
40
41
42 NTOOLTIP g_tip;
43 LRESULT CALLBACK TipHookProc(int nCode, WPARAM wParam, LPARAM lParam);
44
45 TCHAR g_mru_list[MRU_LIST_SIZE][MAX_PATH] = { _T(""), _T(""), _T(""), _T(""), _T("") };
46
47 extern NSCRIPTDATA g_sdata;
48 extern const TCHAR *compressor_names[];
49
50 void MemSafeFree(void*mem) { if (mem) GlobalFree(mem); }
51 void*MemAllocZI(SIZE_T cb) { return GlobalAlloc(GPTR, cb); }
52
53 HMODULE LoadSysLibrary(LPCSTR Mod)
54 {
55 TCHAR buf[MAX_PATH+20], *path;
56 UINT dirmax = MAX_PATH, cch;
57 if ((cch = GetSystemDirectory(buf, dirmax)) >= dirmax) cch = 0;
58 wsprintf(buf + cch, _T("\\%hs.dll"), Mod); // Note: We always append ".dll"
59 path = buf + !cch; // Full path or just the filename
60 return LoadLibrary(path);
61 }
62
63 #ifdef DECLSPEC_NOINLINE
64 DECLSPEC_NOINLINE
65 #endif
66 FARPROC GetSysProcAddr(LPCSTR Mod, LPCSTR FuncName)
67 {
68 return GetProcAddress(LoadSysLibrary(Mod), FuncName);
69 }
70
71 static bool WriteFile(HANDLE hFile, const void*pData, DWORD cb)
72 {
73 DWORD cbio;
74 return WriteFile(hFile, pData, cb, &cbio, 0) && cb == cbio;
75 }
76 bool WriteUTF16LEBOM(HANDLE hFile)
77 {
78 static const unsigned char u16lb[] = {0xFF,0xFE};
79 return WriteFile(hFile, u16lb, sizeof(u16lb));
80 }
81
82 BOOL InitCCExHelper(UINT icc) {
83 INITCOMMONCONTROLSEX icx = { sizeof(icx), icc };
84 BOOL suppw95 = SupportsW95();
85 FARPROC icce = suppw95 ? GetSysProcAddr("COMCTL32", "InitCommonControlsEx") : (FARPROC) InitCommonControlsEx;
86 return (!suppw95 || icce) && ((BOOL(WINAPI*)(const INITCOMMONCONTROLSEX*))icce)(&icx);
87 }
88
89 UINT GetScreenBPP(HWND hWnd) {
90 HDC hDc = GetDC(hWnd);
91 UINT bpp = GetDeviceCaps(hDc, BITSPIXEL) * GetDeviceCaps(hDc, PLANES); // TODO: COLORRES if RASTERCAPS&RC_PALETTE?
92 ReleaseDC(hWnd, hDc);
93 return bpp;
94 }
95
96 int SetArgv(const TCHAR *cmdLine, TCHAR ***argv) {
97 const TCHAR *p;
98 TCHAR *arg, *argSpace;
99 int size, argSpaceSize, inquote, copy, slashes;
100
101 size = 2;
102 for (p = cmdLine; *p != _T('\0'); p++) {
103 if ((*p == _T(' ')) || (*p == _T('\t'))) {
104 size++;
105 while ((*p == _T(' ')) || (*p == _T('\t'))) {
106 p++;
107 }
108 if (*p == _T('\0')) {
109 break;
110 }
111 }
112 }
113
114 argSpaceSize = (size+1) * sizeof(TCHAR *) + (lstrlen(cmdLine) + 1) * sizeof(TCHAR);
115 argSpace = (TCHAR *) MemAlloc(argSpaceSize);
116 *argv = (TCHAR **) argSpace;
117 if (!argSpace)
118 return 0;
119
120 argSpace = (TCHAR *) ((*argv)+size);
121 size--;
122
123 p = cmdLine;
124 int argc;
125 for (argc = 0; argc < size; argc++) {
126 (*argv)[argc] = arg = argSpace;
127 while ((*p == _T(' ')) || (*p == _T('\t'))) {
128 p++;
129 }
130 if (*p == _T('\0')) {
131 break;
132 }
133
134 inquote = 0;
135 slashes = 0;
136 while (1) {
137 copy = 1;
138 while (*p == _T('\\')) {
139 slashes++;
140 p++;
141 }
142 if (*p == _T('"')) {
143 if ((slashes & 1) == 0) {
144 copy = 0;
145 if ((inquote) && (p[1] == _T('"'))) {
146 p++;
147 copy = 1;
148 }
149 else {
150 inquote = !inquote;
151 }
152 }
153 slashes >>= 1;
154 }
155
156 while (slashes) {
157 *arg = _T('\\');
158 arg++;
159 slashes--;
160 }
161
162 if ((*p == _T('\0')) || (!inquote && ((*p == _T(' ')) || (*p == _T('\t'))))) {
163 break;
164 }
165 if (copy != 0) {
166 *arg = *p;
167 arg++;
168 }
169 p++;
170 }
171 *arg = _T('\0');
172 argSpace = arg + 1;
173 }
174 (*argv)[argc] = NULL;
175
176 return argc;
177 }
178
179 void SetTitle(HWND hwnd,const TCHAR *substr) {
180 TCHAR title[64];
181 wsprintf(title,substr ? _T("MakeNSISW - %s") : _T("MakeNSISW"),substr);
182 SetWindowText(hwnd,title);
183 }
184
185 typedef struct { LPCSTR SoundName; int MBFallback; } PLAYAPPSOUNDDATA;
186 static DWORD CALLBACK PlayAppSoundProc(LPVOID ThreadParam) {
187 PLAYAPPSOUNDDATA *p = (PLAYAPPSOUNDDATA*) ThreadParam;
188 BOOL succ = PlaySoundA(p->SoundName, NULL, (SND_APPLICATION|SND_ALIAS|SND_NODEFAULT) & ~SND_ASYNC); // Cannot use SND_ASYNC because we need to detect if the sound played
189 if (!succ && p->MBFallback >= 0) succ = MessageBeep(p->MBFallback);
190 MemFree(p);
191 return succ;
192 }
193
194 void PlayAppSoundAsync(LPCSTR SoundName, int MBFallback) {
195 DWORD tid;
196 PLAYAPPSOUNDDATA *p = (PLAYAPPSOUNDDATA*) MemAlloc(sizeof(PLAYAPPSOUNDDATA));
197 if (p) {
198 p->SoundName = SoundName, p->MBFallback = MBFallback; // Note: The string must be valid until the sound has started because we don't copy it
199 HANDLE hThread = CreateThread(NULL, 0, PlayAppSoundProc, p, 0, SupportsW9X() ? &tid : 0);
200 if (hThread) CloseHandle(hThread); else PlayAppSoundProc(p);
201 }
202 }
203
204 void CopyToClipboard(HWND hwnd) {
205 if (!hwnd || !OpenClipboard(hwnd)) return;
206 LRESULT len = SendMessage(g_sdata.logwnd, WM_GETTEXTLENGTH, 0, 0);
207 HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (++len)*sizeof(TCHAR));
208 if (!mem) { CloseClipboard(); return; }
209 TCHAR *txt = (TCHAR *)GlobalLock(mem);
210 if (!txt) { CloseClipboard(); return; }
211 EmptyClipboard();
212 txt[0] = 0;
213 SendMessage(g_sdata.logwnd, WM_GETTEXT, (WPARAM)(len), (LPARAM)txt);
214 GlobalUnlock(mem);
215 #ifdef _UNICODE
216 SetClipboardData(CF_UNICODETEXT, mem);
217 #else
218 SetClipboardData(CF_TEXT, mem);
219 #endif
220 CloseClipboard();
221 }
222
223 #include <shlobj.h>
224 #if defined(MSFTEDIT_CLASS)
225 #include <tom.h>
226 #define RE_HAS_TOM
227 #define IID_ITextDocument NSIS_IID_ITextDocument
228 static const GUID IID_ITextDocument = { 0x8cc497c0, 0xa1df, 0x11ce, { 0x80,0x98,0x0,0xaa,0x0,0x47,0xbe,0x5d } };
229 #endif
230 void ReleaseLogWindow() {
231 #ifdef RE_HAS_TOM
232 if (g_sdata.pLogTextDoc) ((IUnknown*)g_sdata.pLogTextDoc)->Release();
233 #endif
234 }
235 void InitializeLogWindow() {
236 HWND hRE = g_sdata.logwnd;
237 #ifdef RE_HAS_TOM
238 IUnknown *pTD = 0, *pREO;
239 if (SendMessage(hRE, EM_GETOLEINTERFACE, 0, (LPARAM)&pREO) && pREO) {
240 if (FAILED(pREO->QueryInterface(IID_ITextDocument, (void**) &pTD))) pTD = 0;
241 pREO->Release();
242 }
243 g_sdata.pLogTextDoc = pTD;
244 #endif
245 SendMessage(hRE, EM_SETTEXTMODE, TM_PLAINTEXT, 0);
246 }
247
248 HRESULT RicheditFreeze(void*pITextDocument, SIZE_T Freeze)
249 {
250 HRESULT hr = E_NOTIMPL;
251 #ifdef RE_HAS_TOM
252 ITextDocument*pTD = (ITextDocument*) pITextDocument;
253 if (pTD) {
254 if (Freeze)
255 hr = pTD->Freeze(0);
256 else
257 hr = pTD->Unfreeze(0);
258 }
259 #endif
260 return hr;
261 }
262
263 void SetLogColor(enum LOGCOLOR lc)
264 {
265 enum { em_seteditstyle = (WM_USER + 204), ses_extendbackcolor = 4 };
266 HWND hEd = g_sdata.logwnd;
267 bool sysclr = lc >= LC_SYSCOLOR || !ReadRegSettingDW(REGCOLORIZE, true);
268 static const COLORREF clrs[] = { RGB(0, 50, 0), RGB(210, 255, 210), RGB(50, 30, 0), RGB(255, 220, 190), RGB(50, 0, 0), RGB(255, 210, 210) };
269 CHARFORMAT cf;
270 cf.cbSize = sizeof(cf), cf.dwMask = CFM_COLOR;
271 cf.dwEffects = sysclr ? CFE_AUTOCOLOR : 0;
272 cf.crTextColor = sysclr ? RGB(0, 0, 0) : clrs[(lc * 2) + 0];
273 SendMessage(hEd, em_seteditstyle, sysclr ? 0 : ses_extendbackcolor, ses_extendbackcolor);
274 SendMessage(hEd, EM_SETCHARFORMAT, 0, (LPARAM) &cf);
275 SendMessage(hEd, EM_SETBKGNDCOLOR, sysclr, sysclr ? sysclr /*Irrelevant*/ : clrs[(lc * 2) + 1]);
276 }
277
278 void ClearLog() {
279 SetWindowText(g_sdata.logwnd, _T(""));
280 SendMessage(g_sdata.logwnd, EM_SETZOOM, g_sdata.log_zoom, 100); // Bug #1282: SetWindowText resets zoom.
281 SetLogColor(LC_SYSCOLOR);
282 SendMessage(g_sdata.hwnd, WM_MAKENSIS_UPDATEUISTATE, 0, 0);
283 }
284
285 void LogMessage(HWND hwnd,const TCHAR *str) {
286 HWND hLogWin = g_sdata.logwnd;
287 #ifdef RE_HAS_TOM
288 HRESULT hr = (HRESULT) SendMessage(hwnd, WM_MAKENSIS_FREEZEEDITOR, 0, true); // Force COM calls to UI thread
289 #endif
290 SendMessage(hLogWin, EM_SETSEL, g_sdata.logLength, g_sdata.logLength);
291 SendMessage(hLogWin, EM_REPLACESEL, 0, (LPARAM)str);
292 SendMessage(hLogWin, EM_SCROLLCARET, 0, 0);
293 #ifdef RE_HAS_TOM
294 if (SUCCEEDED(hr)) SendMessage(hwnd, WM_MAKENSIS_FREEZEEDITOR, 0, false);
295 #endif
296 g_sdata.logLength += lstrlen(str);
297 }
298
299 void ErrorMessage(HWND hwnd,const TCHAR *str) {
300 if (!str) return;
301 TCHAR buf[1028];
302 wsprintf(buf, _T("[Error] %s\r\n"), str);
303 LogMessage(hwnd,buf);
304 }
305
306 static void CenterOnParent(HWND hwnd, HWND hParent)
307 {
308 RECT r;
309 GetWindowRect(hwnd, &r);
310 UINT w = (r.right - r.left), h = (r.bottom - r.top), swp = SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE;
311 if (GetWindowRect(hParent, &r))
312 SetWindowPos(hwnd, 0, r.left + ((r.right - r.left)/2) - (w/2), r.top + ((r.bottom - r.top)/2) - (h/2), 0, 0, swp);
313 }
314 void CenterOnParent(HWND hwnd)
315 {
316 CenterOnParent(hwnd, GetWindow(hwnd, GW_OWNER));
317 }
318
319 void SetDialogFocus(HWND hDlg, HWND hCtl)
320 {
321 //blogs.msdn.com/b/oldnewthing/archive/2004/08/02/205624.aspx
322 SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)hCtl, TRUE);
323 }
324
325 HWND GetComboEdit(HWND hCB)
326 {
327 /* CB_GETCOMBOBOXINFO crashes on 64-bit NT 5.x (KB947841).
328 We are left with GetComboBoxInfo(), FindWindowEx()*2 and
329 ChildWindowFromPoint(h,{1,1}) (docs.microsoft.com/en-us/windows/desktop/Controls/subclass-a-combo-box#). */
330 if (!SupportsWNT4() && !SupportsW95())
331 {
332 COMBOBOXINFO cbi;
333 cbi.cbSize = FIELD_OFFSET(COMBOBOXINFO, hwndList) + sizeof(HWND);
334 BOOL succ = GetComboBoxInfo(hCB, &cbi);
335 return succ ? cbi.hwndItem : (HWND)(INT_PTR) succ;
336 }
337 HWND hList = FindWindowEx(hCB, 0, 0, 0);
338 return FindWindowEx(hCB, hList, 0, 0);
339 }
340
341 void EnableDisableItems(int on)
342 {
343 HWND hwndDlg = g_sdata.hwnd;
344 const HWND hCloseBtn = GetDlgItem(hwndDlg, IDCANCEL);
345 const HWND hTestBtn = GetDlgItem(hwndDlg, IDC_TEST);
346 const HMENU hMenu = g_sdata.menu;
347 const UINT mf = (!on ? MF_GRAYED : MF_ENABLED);
348 const UINT nmf = (!on ? MF_ENABLED : MF_GRAYED);
349 const bool compsuccess = !g_sdata.retcode && on;
350
351 if(!on) g_sdata.focused_hwnd = GetFocus();
352
353 if(compsuccess || !on) {
354 EnableWindow(hTestBtn, on);
355 EnableToolBarButton(IDM_TEST, on);
356 EnableMenuItem(hMenu, IDM_TEST, mf);
357 }
358 EnableMenuItem(hMenu, IDM_CANCEL, nmf);
359 EnableWindow(hCloseBtn, false);
360
361 static const PACKEDCMDID_T cmds [] = {
362 PACKCMDID(IDM_EXIT), PACKCMDID(IDM_LOADSCRIPT), PACKCMDID(IDM_EDITSCRIPT),
363 PACKCMDID(IDM_SAVE), PACKCMDID(IDM_CLEARLOG), PACKCMDID(IDM_GUIDGEN),
364 PACKCMDID(IDM_COMPRESSOR), PACKCMDID(IDM_COMPRESSOR_SUBMENU),
365 PACKCMDID(IDM_RECOMPILE), PACKCMDID(IDM_RECOMPILE_TEST)
366 };
367 for (UINT i = 0; i < COUNTOF(cmds); ++i) {
368 UINT id = UNPACKCMDID(cmds[i]);
369 EnableMenuItem(hMenu, id, mf);
370 if (IDM_COPYSELECTED != id && IDM_COMPRESSOR_SUBMENU != id)
371 EnableToolBarButton(id, on);
372 }
373
374 SendMessage(hwndDlg, WM_MAKENSIS_UPDATEUISTATE, 0 ,0);
375 EnableMenuItem(hMenu, IDM_FILE, mf); // Disable the whole File menu because of the MRU list
376 DrawMenuBar(hwndDlg);
377
378 HWND hFocus = g_sdata.focused_hwnd, hOptimal = hTestBtn;
379 if (on && hCloseBtn == hFocus) hFocus = hOptimal;
380 if (!IsWindowEnabled(hFocus)) hFocus = g_sdata.logwnd;
381 SetDialogFocus(hwndDlg, hOptimal);
382 SetDialogFocus(hwndDlg, hFocus);
383 SetTimer(hwndDlg, TID_CONFIGURECLOSEORABORT, 1000, 0);
384 }
385
386 void SetCompressorStats()
387 {
388 DWORD_PTR line_count, i;
389 TCHAR buf[1024];
390 bool found = false;
391
392 line_count = SendMessage(g_sdata.logwnd, EM_GETLINECOUNT, 0, 0);
393 for(i=0; i<line_count; i++) {
394 *((LPWORD)buf) = COUNTOF(buf);
395 LRESULT cchLine = SendMessage(g_sdata.logwnd, EM_GETLINE, (WPARAM)i, (LPARAM)buf);
396 buf[cchLine] = _T('\0');
397 if(found) {
398 DWORD len = lstrlen(TOTAL_SIZE_COMPRESSOR_STAT);
399 lstrcat(g_sdata.compressor_stats,buf);
400 if(!StrCmpN(buf,TOTAL_SIZE_COMPRESSOR_STAT,len)) {
401 break;
402 }
403 }
404 else {
405 DWORD len = lstrlen(EXE_HEADER_COMPRESSOR_STAT);
406 if(!StrCmpN(buf,EXE_HEADER_COMPRESSOR_STAT,len)) {
407 found = true;
408 lstrcpy(g_sdata.compressor_stats,_T("\n\n"));
409 lstrcat(g_sdata.compressor_stats,buf);
410 }
411 }
412 }
413 }
414
415 static void SetUIState_NoScript()
416 {
417 static const PACKEDCMDID_T cmds [] = {
418 PACKCMDID(IDM_RECOMPILE),PACKCMDID(IDM_RECOMPILE_TEST),PACKCMDID(IDM_TEST),
419 PACKCMDID(IDM_BROWSESCR),PACKCMDID(IDM_EDITSCRIPT)
420 };
421 for (UINT i = 0; i < COUNTOF(cmds); ++i)
422 EnableUICommand(UNPACKCMDID(cmds[i]), FALSE);
423 EnableWindow(GetDlgItem(g_sdata.hwnd, IDC_TEST), FALSE);
424 }
425
426 void CompileNSISScript() {
427 DragAcceptFiles(g_sdata.hwnd,FALSE);
428 ClearLog();
429 SetTitle(g_sdata.hwnd,NULL);
430 PostMessage(g_sdata.hwnd, WM_MAKENSIS_UPDATEUISTATE, 0, 0);
431 if (!g_sdata.script[0]) {
432 LogMessage(g_sdata.hwnd,USAGE);
433 SetUIState_NoScript();
434 DragAcceptFiles(g_sdata.hwnd,TRUE);
435 return;
436 }
437 if (!g_sdata.compile_command) {
438 TCHAR *symbols = BuildSymbols();
439 TCHAR compressor[40];
440
441 compressor[0] = _T('\0');
442 if(*g_sdata.compressor_name)
443 wsprintf(compressor,_T("/X\"SetCompressor /FINAL %s\""),g_sdata.compressor_name);
444
445 TCHAR *args = (TCHAR *) GlobalLock(g_sdata.script_cmd_args);
446
447 size_t byteSize = sizeof(TCHAR)*(
448 /* makensis.exe */ lstrlen(EXENAME) + /* space */ 1 +
449 /* script path */ lstrlen(g_sdata.script) + /* space */ 1 +
450 /* script cmd args */ lstrlen(args) + /* space */ 1 +
451 /* defines /Dblah=... */ lstrlen(symbols) + /* space */ 1 +
452 /* /XSetCompressor... */ lstrlen(compressor) + /* space */ 1 +
453 /* /V + UINT8 */ 2 + 3 + /* space */ 1 +
454 /* /NOTIFYHWND + HWND */ COUNTOF(_T("/NOTIFYHWND -4294967295")) + /* space */ 1
455 +6); /* for -- \"\" and NULL */
456
457 g_sdata.compile_command = (TCHAR*) MemAlloc(byteSize);
458
459 wsprintf(
460 g_sdata.compile_command,
461 _T("%s /V%u %s %s /NOTIFYHWND %d %s -- \"%s\""),
462 EXENAME,
463 g_sdata.verbosity,
464 compressor,
465 symbols,
466 g_sdata.hwnd,
467 args,
468 g_sdata.script
469 );
470
471 GlobalUnlock(g_sdata.script_cmd_args);
472 MemFree(symbols);
473 }
474 MemSafeFree(g_sdata.input_script);
475 MemSafeFree(g_sdata.output_exe);
476 g_sdata.input_script = 0;
477 g_sdata.output_exe = 0;
478 g_sdata.warnings = 0;
479 g_sdata.logLength = 0;
480 // Disable buttons during compile
481 DisableItems(g_sdata.hwnd);
482 DWORD tid;
483 g_sdata.thread=CreateThread(NULL,0,MakeNSISProc,0,0,&tid);
484 }
485
486 static DWORD RegWriteString(HKEY hKey, LPCTSTR Name, LPCTSTR Data)
487 {
488 const DWORD cb = (lstrlen(Data) + 1) * sizeof(*Data);
489 return RegSetValueEx(hKey, Name, 0, REG_SZ, (LPBYTE)Data, cb);
490 }
491
492 static DWORD RegReadString(HKEY hKey, LPCTSTR Name, LPTSTR Buf, DWORD cbBufSize) {
493 DWORD ec, rt, cb = cbBufSize, cbCh = sizeof(*Buf);
494 ec = RegQueryValueEx(hKey, Name, NULL, &rt, (BYTE*) Buf, &cb);
495 if (cbBufSize) {
496 #if 0
497 if (rt == REG_DWORD) cb = cbCh * wsprintf(Buf, _T("%d"), *((INT32*)Buf));
498 #endif
499 if (cb+cbCh < cbBufSize) Buf[cb / cbCh] = _T('\0'); // Add a \0 after the data if there is room
500 Buf[(cbBufSize / cbCh) - 1] = _T('\0'); // Always \0 terminate, truncating data if necessary
501 }
502 return ec;
503 }
504
505 DWORD RegOpenKeyForReading(HKEY hRoot, LPCTSTR SubKey, HKEY*pKey) {
506 return RegOpenKeyEx(hRoot, SubKey, 0, KEY_READ, pKey);
507 }
508
509 static bool InternalOpenRegSettingsKey(HKEY root, HKEY &key, bool create) {
510 if (create) {
511 if (RegCreateKey(root, REGKEY, &key) == ERROR_SUCCESS)
512 return true;
513 } else {
514 if (RegOpenKeyForReading(root, REGKEY, &key) == ERROR_SUCCESS)
515 return true;
516 }
517 return false;
518 }
519
520 bool OpenRegSettingsKey(HKEY &hKey, bool create) {
521 return InternalOpenRegSettingsKey(REGSEC, hKey, create)
522 || InternalOpenRegSettingsKey(REGSECDEF, hKey, create);
523 }
524
525 DWORD ReadRegSettingDW(LPCTSTR name, const DWORD defval) {
526 DWORD val = defval, siz = sizeof(val), typ;
527 HKEY hKey;
528 if (OpenRegSettingsKey(hKey)) {
529 if (RegQueryValueEx(hKey,name,NULL,&typ,(LPBYTE)&val,&siz) || REG_DWORD != typ || sizeof(val) != siz)
530 val = defval;
531 RegCloseKey(hKey);
532 }
533 return val;
534 }
535
536 void RestoreWindowPos(HWND hwnd) {
537 HKEY hKey;
538 WINDOWPLACEMENT p;
539 if (OpenRegSettingsKey(hKey)) {
540 DWORD l = sizeof(p);
541 DWORD t;
542 if ((RegQueryValueEx(hKey,REGLOC,NULL,&t,(LPBYTE)&p,&l)==ERROR_SUCCESS)&&(t == REG_BINARY)&&(l==sizeof(p))) {
543 int width, height;
544 int windowWidth, windowHeight;
545
546 width = GetSystemMetrics(SM_CXFULLSCREEN);
547 height = GetSystemMetrics(SM_CYFULLSCREEN);
548 height += GetSystemMetrics(SM_CYCAPTION);
549 windowWidth = p.rcNormalPosition.right-p.rcNormalPosition.left;
550 if(windowWidth > width) {
551 p.rcNormalPosition.left = 0;
552 p.rcNormalPosition.right = width;
553 }
554 else if(p.rcNormalPosition.right > width) {
555 p.rcNormalPosition.left = width - windowWidth;
556 p.rcNormalPosition.right = width;
557 }
558 else if(p.rcNormalPosition.left < 0) {
559 p.rcNormalPosition.left = 0;
560 p.rcNormalPosition.right = windowWidth;
561 }
562
563 windowHeight = p.rcNormalPosition.bottom-p.rcNormalPosition.top;
564 if(windowHeight > height) {
565 p.rcNormalPosition.top = 0;
566 p.rcNormalPosition.bottom = height;
567 }
568 else if(p.rcNormalPosition.bottom > height) {
569 p.rcNormalPosition.top = height - windowHeight;
570 p.rcNormalPosition.bottom = height;
571 }
572 else if(p.rcNormalPosition.top < 0) {
573 p.rcNormalPosition.top = 0;
574 p.rcNormalPosition.bottom = windowHeight;
575 }
576
577 p.length = sizeof(p);
578 SetWindowPlacement(hwnd, &p);
579 }
580 RegCloseKey(hKey);
581 }
582 }
583
584 void SaveWindowPos(HWND hwnd) {
585 HKEY hKey;
586 WINDOWPLACEMENT p;
587 p.length = sizeof(p);
588 if (!GetWindowPlacement(hwnd, &p)) p.length = 0;
589 if (p.length && CreateRegSettingsKey(hKey)) {
590 RegSetValueEx(hKey, REGLOC, 0, REG_BINARY, (LPBYTE)&p, p.length);
591 RegCloseKey(hKey);
592 }
593 }
594
595 void RestoreSymbols() {
596 g_sdata.symbols = LoadSymbolSet(NULL);
597 }
598
599 void SaveSymbols() {
600 SaveSymbolSet(NULL, g_sdata.symbols);
601 }
602
603 #define SYMSET_SUBKEY_MAXLEN (100 + SYMSETNAME_MAXLEN) // REGSYMSUBKEY + [\name]
604 static int CreateSymbolSetSubkeyPath(const TCHAR *name, TCHAR *buffer) {
605 return wsprintf(buffer, name ? _T("%s\\%s") : _T("%s"), REGSYMSUBKEY, name);
606 }
607
608 void FreeSymbolSet(TCHAR **symbols) {
609 if (symbols) {
610 for (SIZE_T i = 0; symbols[i]; ++i)
611 MemSafeFree(symbols[i]);
612 GlobalFree((HGLOBAL) symbols);
613 }
614 }
615
616 void DeleteSymbolSet(const TCHAR *name) {
617 HKEY hKey;
618 if (name && OpenRegSettingsKey(hKey)) {
619 TCHAR subkey[SYMSET_SUBKEY_MAXLEN+1];
620 CreateSymbolSetSubkeyPath(name, subkey);
621 RegDeleteKey(hKey, subkey);
622 RegCloseKey(hKey);
623 }
624 }
625
626 TCHAR** LoadSymbolSet(const TCHAR *name) {
627 HKEY hCfgKey, hSymKey;
628 TCHAR **symbols = NULL;
629 if (OpenRegSettingsKey(hCfgKey)) {
630 TCHAR subkey[SYMSET_SUBKEY_MAXLEN+1];
631 CreateSymbolSetSubkeyPath(name, subkey);
632 if (RegOpenKeyForReading(hCfgKey, subkey, &hSymKey) == ERROR_SUCCESS) {
633 TCHAR bufName[8];
634 for (DWORD i = 0, rt, cbBuf, cbData;;) {
635 cbBuf = sizeof(bufName);
636 if (RegEnumValue(hSymKey, i, bufName, &cbBuf, NULL, &rt, NULL, &cbData) == ERROR_SUCCESS && rt == REG_SZ) {
637 if(symbols) {
638 HGLOBAL newmem = GlobalReAlloc(symbols, (i+2)*sizeof(TCHAR*), GMEM_MOVEABLE|GMEM_ZEROINIT);
639 if (!newmem) FreeSymbolSet(symbols);
640 symbols = (TCHAR**) newmem;
641 }
642 else {
643 symbols = (TCHAR**) GlobalAlloc(GPTR, (i+2)*sizeof(TCHAR*));
644 }
645 if (!symbols) break; // Out of memory, abort!
646 symbols[i] = (TCHAR*) MemAllocZI(cbData += sizeof(TCHAR));
647 if (!symbols[i] || RegReadString(hSymKey, bufName, symbols[i], cbData)) {
648 FreeSymbolSet(symbols);
649 break;
650 }
651 symbols[++i] = NULL; // The symbols array is terminated by a NULL pointer
652 }
653 else
654 break;
655 }
656 RegCloseKey(hSymKey);
657 }
658 RegCloseKey(hCfgKey);
659 }
660 return symbols;
661 }
662
663 void SaveSymbolSet(const TCHAR *name, TCHAR **symbols) {
664 HKEY hCfgKey, hSymKey;
665 if (CreateRegSettingsKey(hCfgKey)) {
666 TCHAR subkey[SYMSET_SUBKEY_MAXLEN+1], bufName[8];
667 CreateSymbolSetSubkeyPath(name, subkey);
668 if (RegOpenKey(hCfgKey, subkey, &hSymKey) == ERROR_SUCCESS) {
669 // Cannot use DeleteSymbolSet because name might be NULL and named sets are stored inside the base symbols key
670 for (DWORD cb;;) {
671 cb = sizeof(bufName);
672 if (RegEnumValue(hSymKey,0, bufName, &cb,NULL,NULL,NULL,NULL)!=ERROR_SUCCESS) break;
673 RegDeleteValue(hSymKey, bufName);
674 }
675 RegCloseKey(hSymKey);
676 }
677 if(symbols) {
678 if (RegCreateKey(hCfgKey, subkey, &hSymKey) == ERROR_SUCCESS) {
679 for (SIZE_T i = 0; symbols[i]; ++i) {
680 wsprintf(bufName, _T("%d"), (INT) i);
681 RegWriteString(hSymKey, bufName, symbols[i]);
682 }
683 RegCloseKey(hSymKey);
684 }
685 }
686 RegCloseKey(hCfgKey);
687 }
688 }
689
690 void ResetObjects() {
691 MemSafeFree(g_sdata.compile_command);
692 g_sdata.compile_command = NULL;
693 g_sdata.warnings = FALSE;
694 g_sdata.retcode = -1;
695 g_sdata.thread = NULL;
696 }
697
698 void ResetSymbols() {
699 FreeSymbolSet(g_sdata.symbols);
700 g_sdata.symbols = NULL;
701 }
702
703 BOOL ShellExecuteWithErrorBox(HWND hWnd, LPCTSTR File, LPCTSTR Parameters) {
704 SHELLEXECUTEINFO sei;
705 sei.cbSize = sizeof(SHELLEXECUTEINFO);
706 sei.fMask = SEE_MASK_FLAG_DDEWAIT;
707 if (!(sei.hwnd = hWnd)) sei.fMask |= SEE_MASK_FLAG_NO_UI;
708 sei.lpVerb = NULL;
709 sei.lpFile = File;
710 sei.lpParameters = Parameters;
711 sei.lpDirectory = NULL;
712 sei.nShow = SW_SHOW;
713 return ShellExecuteEx(&sei);
714 }
715
716 void FreeSpawn(PROCESS_INFORMATION *pPI, HANDLE hRd, HANDLE hWr) {
717 if (pPI) {
718 GetExitCodeProcess(pPI->hProcess, &pPI->dwProcessId);
719 CloseHandle(pPI->hProcess);
720 CloseHandle(pPI->hThread);
721 }
722 CloseHandle(hRd);
723 CloseHandle(hWr);
724 }
725 BOOL InitSpawn(STARTUPINFO &si, HANDLE &hRd, HANDLE &hWr) {
726 OSVERSIONINFO osv;
727 GetVersionEx((osv.dwOSVersionInfoSize = sizeof(osv), &osv));
728 const bool winnt = VER_PLATFORM_WIN32_NT == osv.dwPlatformId;
729
730 memset(&si, 0, sizeof(STARTUPINFO));
731 si.cb = sizeof(STARTUPINFO);
732 GetStartupInfo(&si);
733 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
734 si.wShowWindow = SW_HIDE;
735
736 SECURITY_ATTRIBUTES sa={sizeof(sa)};
737 SECURITY_DESCRIPTOR sd;
738 if (winnt) {
739 InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
740 SetSecurityDescriptorDacl(&sd, true, NULL, false);
741 sa.lpSecurityDescriptor = &sd;
742 }
743 sa.bInheritHandle = true;
744 BOOL okp = CreatePipe(&hRd, &hWr, &sa, 0);
745 si.hStdOutput = hWr, si.hStdError = hWr;
746 si.hStdInput = INVALID_HANDLE_VALUE;
747 return okp;
748 }
749
750 int InitBranding() {
751 const TCHAR *opt = _T(" /version");
752 UINT cch = lstrlen(EXENAME) + lstrlen(opt) + 1;
753 TCHAR *cmd = (TCHAR*) MemAlloc(cch*sizeof(TCHAR));
754 if (!cmd) return 0;
755 lstrcpy(cmd, EXENAME);
756 lstrcat(cmd, opt);
757 STARTUPINFO si;
758 HANDLE newstdout, read_stdout;
759 char szBuf[1024], retval = 0;
760 if (InitSpawn(si, read_stdout, newstdout)) {
761 PROCESS_INFORMATION pi, *ppi = 0;
762 if (CreateProcess(0, cmd, 0, 0, TRUE, CREATE_NEW_CONSOLE, 0, 0, &si, &pi)) {
763 DWORD dwRead = 0;
764 if (WAIT_OBJECT_0 == WaitForSingleObject(pi.hProcess, 10000)) {
765 ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL);
766 retval = 1;
767 }
768 szBuf[dwRead] = 0, ppi = &pi;
769 int len = lstrlenA(szBuf);
770 while(len && ((szBuf[len - 1] == '\n')|(szBuf[len - 1] == '\r'))) szBuf[--len] = '\0';
771 if (!len) retval = 0;
772 g_sdata.branding = (TCHAR*) MemAlloc((len+6)*sizeof(TCHAR)); // LEAKED
773 wsprintf(g_sdata.branding, _T("NSIS %hs"), szBuf);
774 g_sdata.brandingv = (char*) MemAlloc(len+1); // LEAKED
775 lstrcpyA(g_sdata.brandingv, szBuf);
776 }
777 FreeSpawn(ppi, read_stdout, newstdout);
778 }
779 MemFree(cmd);
780 return retval;
781 }
782
783 LRESULT SetTooltipText(HWND hWnd, UINT_PTR Id, LPCTSTR Text) {
784 TOOLINFO ti;
785 ti.cbSize = SizeOfStruct(ti);
786 ti.uFlags = Id > 0x7fff ? TTF_IDISHWND : 0;
787 ti.hwnd = hWnd, ti.uId = Id;
788 ti.hinst = g_sdata.hInstance, ti.lpszText = const_cast<LPTSTR>(Text);
789 return SendMessage(g_tip.tip, TTM_UPDATETIPTEXT, 0, (LPARAM) (LPTOOLINFO) &ti);
790 }
791
792 void UpdateCloseButtonTooltip() {
793 LPCTSTR txt = g_sdata.thread ? _T("") : CLOSEBTN_TIPTEXT;
794 SetTooltipText(g_tip.tip_p, (UINT_PTR) GetDlgItem(g_sdata.hwnd, IDCANCEL), txt);
795 }
796
797 void InitTooltips(HWND h) {
798 if (h == NULL) return;
799 InitCCEx(ICC_BAR_CLASSES);
800 DWORD s = WS_POPUP | WS_BORDER | TTS_ALWAYSTIP, xs = WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
801 g_tip.hook = 0;
802 g_tip.tip_p = h;
803 g_tip.tip = CreateWindowEx(xs, TOOLTIPS_CLASS, NULL, s, 0, 0, 0, 0, h, NULL, HINST_APPLICATION, NULL);
804 if (!g_tip.tip) return;
805 g_tip.hook = SetWindowsHookEx(WH_GETMESSAGE, TipHookProc, NULL, GetCurrentThreadId());
806 AddTip(GetDlgItem(h, IDCANCEL), CLOSEBTN_TIPTEXT);
807 AddTip(GetDlgItem(h, IDC_TEST), TESTBTN_TIPTEXT);
808 AddToolBarTooltips();
809 }
810
811 void DestroyTooltips() {
812 UnhookWindowsHookEx(g_tip.hook);
813 }
814
815 void AddTip(HWND hWnd, LPCTSTR lpszToolTip) {
816 TOOLINFO ti;
817 ti.cbSize = SizeOfStruct(ti);
818 ti.uFlags = TTF_IDISHWND;
819 ti.hwnd = g_tip.tip_p;
820 ti.uId = (UINT_PTR) hWnd;
821 ti.lpszText = const_cast<LPTSTR>(lpszToolTip);
822 SendMessage(g_tip.tip, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);
823 }
824
825 LRESULT CALLBACK TipHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
826 if (nCode < 0) return CallNextHookEx(g_tip.hook, nCode, wParam, lParam);
827 switch (((MSG*)lParam)->message) {
828 case WM_MOUSEMOVE:
829 if (IsChild(g_tip.tip_p,((MSG*)lParam)->hwnd))
830 SendMessage(g_tip.tip, TTM_RELAYEVENT, 0,lParam);
831 break;
832 default:
833 break;
834 }
835 return CallNextHookEx(g_tip.hook, nCode, wParam, lParam);
836 }
837
838 void ShowDocs() {
839 TCHAR pathf[MAX_PATH],*path;
840 GetModuleFileName(NULL,pathf,COUNTOF(pathf));
841 path=_tcsrchr(pathf,_T('\\'));
842 if(path!=NULL) *path=0;
843 lstrcat(pathf,LOCALDOCS);
844 if (!ShellExecuteSilent(g_sdata.hwnd, pathf))
845 OpenUrlInDefaultBrowser(g_sdata.hwnd, DOCURL);
846 }
847
848 TCHAR* BuildSymbols()
849 {
850 TCHAR *buf = NULL;
851
852 if(g_sdata.symbols) {
853 int i=0;
854 while(g_sdata.symbols[i]) {
855 if(buf) {
856 TCHAR *buf3 = (TCHAR*) MemAlloc((lstrlen(buf)+lstrlen(g_sdata.symbols[i])+6)*sizeof(TCHAR));
857 wsprintf(buf3,_T("%s \"/D%s\""),buf,g_sdata.symbols[i]);
858 MemFree(buf);
859 buf = buf3;
860 }
861 else {
862 buf = (TCHAR*) MemAlloc((lstrlen(g_sdata.symbols[i])+5)*sizeof(TCHAR));
863 wsprintf(buf,_T("\"/D%s\""),g_sdata.symbols[i]);
864 }
865 i++;
866 }
867 }
868 else {
869 buf = (TCHAR*) MemAlloc(sizeof(TCHAR));
870 buf[0] = _T('\0');
871 }
872
873 return buf;
874 }
875
876 static inline bool IsValidFile(const TCHAR *fname)
877 {
878 return FileExists(fname);
879 }
880
881 BOOL PopMRUFile(TCHAR* fname)
882 {
883 int i;
884
885 for(i=0; i<MRU_LIST_SIZE; i++) {
886 if(!lstrcmpi(g_mru_list[i], fname)) {
887 break;
888 }
889 }
890
891 if(i < MRU_LIST_SIZE) {
892 int j;
893 for(j = i; j < MRU_LIST_SIZE-1; j++) {
894 lstrcpy(g_mru_list[j],g_mru_list[j+1]);
895 }
896 g_mru_list[MRU_LIST_SIZE-1][0]=_T('\0');
897 return TRUE;
898 }
899 else {
900 return FALSE;
901 }
902 }
903
904 void PushMRUFile(TCHAR* fname)
905 {
906 TCHAR full_file_name[MAX_PATH+1];
907
908 if(!fname || fname[0] == _T('\0') || fname[0] == _T('/') || fname[0] == _T('-')) {
909 return;
910 }
911
912 DWORD rv = GetFullPathName(fname,COUNTOF(full_file_name),full_file_name,NULL);
913 if (rv == 0 || rv >= COUNTOF(full_file_name)) {
914 return;
915 }
916
917 if(IsValidFile(full_file_name)) {
918 int i;
919 PopMRUFile(full_file_name);
920 for(i = MRU_LIST_SIZE - 2; i >= 0; i--) {
921 lstrcpy(g_mru_list[i+1], g_mru_list[i]);
922 }
923 lstrcpy(g_mru_list[0],full_file_name);
924 BuildMRUMenus();
925 }
926 }
927
928 void BuildMRUMenus()
929 {
930 HMENU hMenu = g_sdata.fileSubmenu;
931 int i, n;
932 MENUITEMINFO mii;
933 TCHAR buf[MRU_DISPLAY_LENGTH + 5/*number*/ + 1/*null*/];
934 TCHAR buf2[MRU_DISPLAY_LENGTH - 6];
935 TCHAR buf3[MRU_DISPLAY_LENGTH + 1];
936 mii.cbSize = sizeof(mii);
937
938 for(i = 0; i < MRU_LIST_SIZE; i++) {
939 DeleteMenu(hMenu, IDM_MRU_FILE+i, MF_BYCOMMAND);
940 }
941
942 n = GetMenuItemCount(hMenu);
943
944 // Remove MRU separator
945 int seppos = n - 1;
946 mii.fMask = MIIM_TYPE, mii.cch = 0;
947 if (GetMenuItemInfo(hMenu, seppos, TRUE, &mii)) {
948 if (MFT_SEPARATOR & mii.fType) {
949 DeleteMenu(hMenu, seppos, MF_BYPOSITION);
950 n--;
951 }
952 }
953
954 for(i = 0; i < MRU_LIST_SIZE; i++) {
955 if(g_mru_list[i][0]) {
956 if (seppos) {
957 // We have MRU items so add the separator
958 mii.fMask = MIIM_TYPE;
959 mii.fType = MFT_SEPARATOR;
960 InsertMenuItem(hMenu, n++, TRUE, &mii);
961 seppos = 0;
962 }
963 memset(buf,0,sizeof(buf));
964 mii.fMask = MIIM_ID | MIIM_TYPE | MIIM_STATE;
965 mii.wID = IDM_MRU_FILE+i;
966 mii.fType = MFT_STRING;
967 wsprintf(buf, _T("&%d "), i + 1);
968 if(lstrlen(g_mru_list[i]) > MRU_DISPLAY_LENGTH) {
969 TCHAR *p = _tcsrchr(g_mru_list[i],_T('\\'));
970 if(p) {
971 p++;
972 if(lstrlen(p) > MRU_DISPLAY_LENGTH - 7) {
973 *buf2 = 0;
974 lstrcpyn(buf2,p,MRU_DISPLAY_LENGTH - 9);
975 lstrcat(buf2,_T("..."));
976
977 lstrcpyn(buf3,g_mru_list[i],4);
978 lstrcat(buf,buf3);
979 lstrcat(buf,_T("...\\"));
980 lstrcat(buf,buf2);
981 }
982 else {
983 lstrcpyn(buf3,g_mru_list[i],(MRU_DISPLAY_LENGTH - lstrlen(p) - 3));
984 lstrcat(buf,buf3);
985 lstrcat(buf,_T("...\\"));
986 lstrcat(buf,p);
987 }
988 }
989 else {
990 lstrcpyn(buf3,g_mru_list[i],(MRU_DISPLAY_LENGTH-2));
991 lstrcat(buf,buf3);
992 lstrcat(buf,_T("..."));
993 }
994 }
995 else {
996 lstrcat(buf, g_mru_list[i]);
997 }
998
999 mii.dwTypeData = buf;
1000 mii.cch = lstrlen(buf)+1;
1001 mii.fState = MFS_ENABLED;
1002 InsertMenuItem(hMenu, n++, TRUE, &mii);
1003
1004 }
1005 else {
1006 break;
1007 }
1008 }
1009
1010 hMenu = g_sdata.toolsSubmenu;
1011 mii.fMask = MIIM_STATE;
1012 mii.fState = g_mru_list[0][0] ? MFS_ENABLED : MFS_GRAYED;
1013
1014 SetMenuItemInfo(hMenu, IDM_CLEAR_MRU_LIST,FALSE,&mii);
1015 }
1016
1017 void LoadMRUFile(int position)
1018 {
1019 if (!g_sdata.thread && position >=0 && position < MRU_LIST_SIZE && g_mru_list[position][0]) {
1020 SetScript(g_mru_list[position]);
1021 if(IsValidFile(g_mru_list[position])) {
1022 PushMRUFile(g_mru_list[position]);
1023 }
1024 else {
1025 PopMRUFile(g_mru_list[position]);
1026 BuildMRUMenus();
1027 }
1028 ResetObjects();
1029 CompileNSISScript();
1030 }
1031 }
1032
1033 void RestoreMRUList()
1034 {
1035 HKEY hCfgKey, hMRUKey;
1036 UINT n = 0, i;
1037 if (OpenRegSettingsKey(hCfgKey)) {
1038 if (RegOpenKeyForReading(hCfgKey, REGMRUSUBKEY, &hMRUKey) == ERROR_SUCCESS) {
1039 for(int i=0; i<MRU_LIST_SIZE; i++) {
1040 TCHAR bufName[8];
1041 wsprintf(bufName, _T("%d"), i);
1042 DWORD ec = RegReadString(hMRUKey, bufName, g_mru_list[n], sizeof(g_mru_list[n]));
1043 if(!ec && g_mru_list[n][0] != _T('\0')) {
1044 n++;
1045 }
1046 }
1047 RegCloseKey(hMRUKey);
1048 }
1049 RegCloseKey(hCfgKey);
1050 }
1051 for(i = n; i < MRU_LIST_SIZE; i++) {
1052 g_mru_list[i][0] = _T('\0');
1053 }
1054
1055 BuildMRUMenus();
1056 }
1057
1058 void SaveMRUList()
1059 {
1060 UINT c = 0, i;
1061 for (i = 0; i < MRU_LIST_SIZE; ++i)
1062 if (*g_mru_list[i])
1063 ++c;
1064 HKEY hCfgKey, hMRUKey;
1065 if (CreateRegSettingsKey(hCfgKey)) {
1066 if ((c ? RegCreateKey : RegOpenKey)(hCfgKey, REGMRUSUBKEY, &hMRUKey) == ERROR_SUCCESS) {
1067 for (i = 0; i < MRU_LIST_SIZE; ++i) {
1068 TCHAR bufName[8];
1069 wsprintf(bufName, _T("%d"), i);
1070 if (*g_mru_list[i])
1071 RegWriteString(hMRUKey, bufName, g_mru_list[i]);
1072 else
1073 RegDeleteValue(hMRUKey, bufName);
1074 }
1075 RegCloseKey(hMRUKey);
1076 }
1077 RegCloseKey(hCfgKey);
1078 }
1079 }
1080
1081 void ClearMRUList()
1082 {
1083 for(UINT i=0; i < MRU_LIST_SIZE; ++i) {
1084 g_mru_list[i][0] = _T('\0');
1085 }
1086
1087 BuildMRUMenus();
1088 }
1089
1090 void RestoreCompressor()
1091 {
1092 HKEY hKey;
1093 NCOMPRESSOR v = COMPRESSOR_SCRIPT;
1094 if (OpenRegSettingsKey(hKey)) {
1095 TCHAR compressor_name[32];
1096 if (RegReadString(hKey, REGCOMPRESSOR, compressor_name, sizeof(compressor_name))==ERROR_SUCCESS) {
1097 for(UINT i= (UINT)COMPRESSOR_SCRIPT; i <= (UINT)COMPRESSOR_BEST; i++) {
1098 if(!lstrcmpi(compressor_names[i], compressor_name)) {
1099 v = (NCOMPRESSOR)i;
1100 break;
1101 }
1102 }
1103 }
1104 RegCloseKey(hKey);
1105 }
1106 g_sdata.default_compressor = v;
1107 }
1108
1109 void SaveCompressor()
1110 {
1111 HKEY hKey;
1112 int n = (int)COMPRESSOR_SCRIPT;
1113 NCOMPRESSOR v = g_sdata.default_compressor;
1114
1115 if(v >= COMPRESSOR_SCRIPT && v <= COMPRESSOR_BEST) {
1116 n = (int)v;
1117 }
1118
1119 if (CreateRegSettingsKey(hKey)) {
1120 if (compressor_names[n][0])
1121 RegWriteString(hKey, REGCOMPRESSOR, compressor_names[n]);
1122 else
1123 RegDeleteValue(hKey, REGCOMPRESSOR);
1124 RegCloseKey(hKey);
1125 }
1126 }
1127
1128 bool FileExists(const TCHAR *fname)
1129 {
1130 WIN32_FIND_DATA wfd;
1131 HANDLE h = FindFirstFile(fname,&wfd);
1132 if(INVALID_HANDLE_VALUE != h) {
1133 FindClose(h);
1134 return true;
1135 }
1136 return false;
1137 }
1138
1139 bool OpenUrlInDefaultBrowser(HWND hwnd, LPCSTR Url)
1140 {
1141 return (int)(INT_PTR) ShellExecuteA(hwnd, NULL, Url, NULL, NULL, SW_SHOWNORMAL) > 32;
1142 }
1143
1144 HMENU FindSubMenu(HMENU hMenu, UINT uId)
1145 {
1146 MENUITEMINFO mii;
1147 mii.cbSize = sizeof(MENUITEMINFO);
1148 mii.fMask = MIIM_SUBMENU;
1149 return GetMenuItemInfo(hMenu, uId, FALSE, &mii) ? mii.hSubMenu : 0;
1150 }
1151
1152 static UINT DpiGetClassicSystemDpiY() { HDC hDC = GetDC(NULL); UINT dpi = GetDeviceCaps(hDC, LOGPIXELSY); ReleaseDC(NULL, hDC); return dpi; }
1153 static HRESULT WINAPI DpiFallbackGetDpiForMonitor(HMONITOR hMon, int MDT, UINT*pX, UINT*pY) { return (*pX = *pY = DpiGetClassicSystemDpiY(), S_OK); }
1154 static UINT WINAPI DpiFallbackGetDpiForWindow(HWND hWnd) { return 0; }
1155 static HMONITOR WINAPI DpiFallbackMonitorFromWindow(HWND hWnd, DWORD Flags) { return NULL; }
1156
1157 static UINT DpiNativeGetForMonitor(HMONITOR hMon)
1158 {
1159 static HRESULT(WINAPI*f)(HMONITOR, int, UINT*, UINT*);
1160 if (!f && !((FARPROC&)f = GetSysProcAddr("SHCORE", "GetDpiForMonitor"))) f = DpiFallbackGetDpiForMonitor;
1161 UINT x, y, mdt_effective_dpi = 0;
1162 return SUCCEEDED(f(hMon, mdt_effective_dpi, &x, &y)) ? y : 0;
1163 }
1164 UINT DpiGetForMonitor(HWND hWnd)
1165 {
1166 HMONITOR(WINAPI*monitorfromwindow)(HWND, DWORD);
1167 if (SupportsWNT4() || SupportsW95())
1168 {
1169 static HMONITOR(WINAPI*g)(HWND, DWORD);
1170 if (!g && !((FARPROC&)g = GetSysProcAddr("USER32", "MonitorFromWindow"))) g = DpiFallbackMonitorFromWindow;
1171 monitorfromwindow = g;
1172 }
1173 else
1174 {
1175 monitorfromwindow = MonitorFromWindow;
1176 }
1177 HMONITOR hMon = monitorfromwindow(hWnd, MONITOR_DEFAULTTONEAREST);
1178 return hMon ? DpiNativeGetForMonitor(hMon) : (UINT)(UINT_PTR) hMon;
1179 }
1180
1181 UINT DpiGetForWindow(HWND hWnd)
1182 {
1183 UINT dpi;
1184 if (DpiAwarePerMonitor() || DpiAwarePerMonitor2())
1185 {
1186 static UINT(WINAPI*f)(HWND);
1187 if (!f && !((FARPROC&)f = GetSysProcAddr("USER32", "GetDpiForWindow"))) f = DpiFallbackGetDpiForWindow;
1188 if ((dpi = f(hWnd))) return dpi;
1189 }
1190 if (DpiAwarePerMonitor() && (dpi = DpiGetForMonitor(hWnd))) return dpi;
1191 return DpiGetClassicSystemDpiY();
1192 }
1193
1194 int DpiScaleY(HWND hWnd, int Val)
1195 {
1196 return MulDiv(Val, DpiGetForWindow(hWnd), 96);
1197 }
1198
1199 HFONT CreateFontHelper(INT_PTR Data, int Height, DWORD p1, LPCTSTR Face)
1200 {
1201 WORD w = LOBYTE(p1)<<2, flags = HIBYTE(p1), cs = HIWORD(LOBYTE(p1)), paf = HIWORD(HIBYTE(p1));
1202 if (flags & CFF_DPIPT)
1203 {
1204 UINT dpi = (flags & CFF_DPIFROMHWND) ? DpiGetForWindow((HWND) Data) : (UINT) Data;
1205 Height = -MulDiv(Height, dpi, 72);
1206 }
1207 return CreateFont(Height, 0, 0, 0, w, FALSE, FALSE, FALSE, cs, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, paf, Face);
1208 }
1209
1210 BOOL CALLBACK FontExistsCallback(const LOGFONT*pLF, const TEXTMETRIC*pTM, DWORD Type, LPARAM Cookie)
1211 {
1212 *((BOOL*) Cookie) = TRUE;
1213 return FALSE;
1214 }
1215 BOOL FontExists(LPCTSTR Face)
1216 {
1217 BOOL ret = FALSE;
1218 HDC hDC = GetDC(0);
1219 EnumFonts(hDC, Face, FontExistsCallback, (LPARAM) &ret);
1220 ReleaseDC(0, hDC);
1221 return ret;
1222 }
1223
1224 BOOL FillRectColor(HDC hDC, const RECT &Rect, COLORREF Color)
1225 {
1226 COLORREF orgclr = SetBkColor(hDC, Color);
1227 ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &Rect, _T(""), 0, NULL);
1228 return TRUE|SetBkColor(hDC, orgclr);
1229 }
1230
1231 static BOOL DrawHorzGradient(HDC hDC, const RECT&rect, COLOR16 r1, COLOR16 g1, COLOR16 b1, COLOR16 r2, COLOR16 g2, COLOR16 b2)
1232 {
1233 TRIVERTEX v[2] = { {rect.left, rect.top, r1, g1, b1, 0xffff}, {rect.right, rect.bottom, r2, g2, b2, 0xffff} };
1234 GRADIENT_RECT r = { 0, 1 };
1235 BOOL(WINAPI*gf)(HDC,TRIVERTEX*,ULONG,VOID*,ULONG,ULONG);
1236 if (SupportsWNT4() || SupportsW95())
1237 {
1238 if (!((FARPROC&)gf = GetSysProcAddr("MSIMG32", "GradientFill")))
1239 {
1240 return FillRectColor(hDC, rect, RGB((((UINT)r1+r2)/2)>>8, (((UINT)g1+g2)/2)>>8, (((UINT)b1+b2)/2)>>8)); // TODO: Actually try to draw a gradient
1241 }
1242 }
1243 else
1244 gf = GradientFill;
1245 return gf(hDC, v, 2, &r, 1, GRADIENT_FILL_RECT_H);
1246 }
1247
1248 BOOL DrawHorzGradient(HDC hDC, LONG l, LONG t, LONG r, LONG b, COLORREF c1, COLORREF c2)
1249 {
1250 RECT rect = { l, t, r, b };
1251 return DrawHorzGradient(hDC, rect, (WORD)GetRValue(c1)<<8, (WORD)GetGValue(c1)<<8, (WORD)GetBValue(c1)<<8, (WORD)GetRValue(c2)<<8, (WORD)GetGValue(c2)<<8, (WORD)GetBValue(c2)<<8);
1252 }
1253
1254 long DlgUnitToPixelX(HWND hDlg, long x) { RECT r = { x, 0, 0, 0 }; MapDialogRect(hDlg, &r); return r.left; }
1255 long DlgUnitToPixelY(HWND hDlg, long y) { RECT r = { 0, y, 0, 0 }; MapDialogRect(hDlg, &r); return r.top; }
1256
1257 #ifndef SP_GRIPPER
1258 #ifndef HTHEME
1259 #define HTHEME HTHEME_OLDSDK
1260 struct OLDSDK_TYPE_HTHEME {int unused;}; typedef struct OLDSDK_TYPE_HTHEME* HTHEME;
1261 #endif
1262 #define SP_GRIPPER 3
1263 #endif
1264 struct VisualStyles {
1265 VisualStyles() : m_OpenThemeData(NULL) {}
1266 static HTHEME WINAPI Compat_OpenThemeData(HWND hWnd, LPCWSTR Class) { return NULL; }
1267 HTHEME OpenThemeData(HWND hWnd, LPCWSTR Class) { return (InitUXTheme(), m_OpenThemeData(hWnd, Class)); }
1268 void InitUXTheme()
1269 {
1270 if (m_OpenThemeData) return ;
1271 HMODULE hUXT = LoadSysLibrary("UXTHEME");
1272 if (!((FARPROC&) m_OpenThemeData = GetProcAddress(hUXT, "OpenThemeData"))) m_OpenThemeData = Compat_OpenThemeData;
1273 (FARPROC&) CloseThemeData = GetProcAddress(hUXT, "CloseThemeData");
1274 (FARPROC&) DrawThemeBackground = GetProcAddress(hUXT, "DrawThemeBackground");
1275 }
1276
1277 HTHEME(WINAPI*m_OpenThemeData)(HWND,LPCWSTR);
1278 HRESULT(WINAPI*CloseThemeData)(HTHEME);
1279 HRESULT(WINAPI*DrawThemeBackground)(HTHEME,HDC,int,int,LPCRECT,LPCRECT);
1280 } VS;
1281
1282 void DrawGripper(HWND hWnd, HDC hDC, const RECT&r)
1283 {
1284 HTHEME hTheme = VS.OpenThemeData(hWnd, L"STATUS");
1285 if (hTheme)
1286 {
1287 VS.DrawThemeBackground(hTheme, hDC, SP_GRIPPER, 0, &r, NULL);
1288 VS.CloseThemeData(hTheme);
1289 }
1290 else
1291 {
1292 DrawFrameControl(hDC, const_cast<LPRECT>(&r), DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
1293 }
1294 }
1295
1296 bool RicheditHasSelection(HWND hRE)
1297 {
1298 CHARRANGE tr;
1299 SendMessage(hRE, EM_EXGETSEL, 0, (LPARAM) &tr);
1300 return tr.cpMax - tr.cpMin <= 0 ? FALSE : TRUE;
1301 }
1302
1303 void EnableUICommand(UINT Id, INT_PTR Enabled)
1304 {
1305 EnableToolBarButton(Id, !!Enabled);
1306 EnableMenuItem(g_sdata.menu, Id, Enabled ? MF_ENABLED : MF_GRAYED);
1307 }