Setup.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. //---------------------------------------------------------------------------
  2. // Part of this code is
  3. // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
  4. //---------------------------------------------------------------------------
  5. #include <vcl.h>
  6. #pragma hdrstop
  7. #include <stdio.h>
  8. #include <tchar.h>
  9. #include <shlobj.h>
  10. #include <tlhelp32.h>
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <Exceptions.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <TcpIp.hpp>
  17. #include <CompThread.hpp>
  18. #include <FileInfo.h>
  19. #include "WinConfiguration.h"
  20. #include "WinInterface.h"
  21. #include "Tools.h"
  22. #include "Setup.h"
  23. #include <StrUtils.hpp>
  24. #include "ProgParams.h"
  25. //---------------------------------------------------------------------------
  26. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  27. _T("Session Manager\\Environment")
  28. // when the PATH registry key is over aprox 2048 characters,
  29. // PATH as well as WINDIR variables are actually not set, breaking the system
  30. #define MAX_PATH_LEN 2000
  31. /* Command line options. */
  32. UnicodeString LastPathError;
  33. //---------------------------------------------------------------------------
  34. // Display the error "err_msg".
  35. void err_out(LPCTSTR err_msg)
  36. {
  37. LastPathError = err_msg;
  38. }
  39. //---------------------------------------------------------------------------
  40. // Display "base_err_msg" followed by the description of the system error
  41. // identified by "sys_err".
  42. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  43. {
  44. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  45. }
  46. //---------------------------------------------------------------------------
  47. // Works as "strcmp" but the comparison is not case sensitive.
  48. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  49. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  50. if (*str1 == L'\0')
  51. return 0;
  52. return tolower(*str1) - tolower(*str2);
  53. }
  54. //---------------------------------------------------------------------------
  55. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  56. // not present). The returned value must be freed with "free".
  57. LPTSTR unquote(LPCTSTR str){
  58. int last_pos;
  59. LPTSTR ret;
  60. size_t new_len;
  61. last_pos = _tcslen(str) - 1;
  62. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  63. new_len= (_tcslen(str) - 1);
  64. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  65. lstrcpyn(ret, &str[1], new_len);
  66. }
  67. else
  68. ret = _tcsdup(str);
  69. return ret;
  70. }
  71. //---------------------------------------------------------------------------
  72. // Find "what" in the ";" separated string "str" and returns a pointer to
  73. // the first letter of "what" in the string. If "next" is not "NULL" it
  74. // points to the first letter after "what" (excluding the trailing ";").
  75. // If "what" isn't find the functions returns "NULL".
  76. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  77. LPTSTR tok_buff;
  78. LPTSTR curr_tok;
  79. LPTSTR curr_tok_dup;
  80. BOOL path_eq;
  81. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  82. int pos = -1;
  83. LPTSTR ret;
  84. tok_buff = _tcsdup(str);
  85. curr_tok = _tcstok(tok_buff, _T(";"));
  86. while (pos == -1 && curr_tok){
  87. curr_tok_dup = unquote(curr_tok);
  88. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  89. GetShortPathName(curr_tok_dup, sh_path2,
  90. LENOF(sh_path2)) &&
  91. (tcharicmp(sh_path1, sh_path2) == 0);
  92. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  93. pos = curr_tok - tok_buff;
  94. }
  95. free(curr_tok_dup);
  96. curr_tok = _tcstok(NULL, _T(";"));
  97. if (pos != -1 && next){
  98. if (curr_tok)
  99. *next = str + (curr_tok - tok_buff);
  100. else
  101. *next = str + _tcslen(str);
  102. }
  103. }
  104. free(tok_buff);
  105. if (pos != -1)
  106. ret = str + pos;
  107. else
  108. ret = NULL;
  109. return ret;
  110. }
  111. //---------------------------------------------------------------------------
  112. void path_reg_propagate()
  113. {
  114. DWORD send_message_result;
  115. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  116. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  117. 5000, &send_message_result);
  118. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  119. {
  120. err_out_sys(_T("Cannot propagate the new enviroment to ")
  121. _T("other processes. The new value will be ")
  122. _T("avaible after a reboot."), GetLastError());
  123. SimpleErrorDialog(LastPathError);
  124. LastPathError = L"";
  125. }
  126. }
  127. //---------------------------------------------------------------------------
  128. // Add "path" to the registry. Return "TRUE" if the path has been added or
  129. // was already in the registry, "FALSE" otherwise.
  130. BOOL add_path_reg(LPCTSTR path){
  131. HKEY key;
  132. LONG ret;
  133. DWORD data_size;
  134. LPTSTR reg_str;
  135. BOOL func_ret = TRUE;
  136. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  137. KEY_WRITE | KEY_READ, &key);
  138. if (ret != ERROR_SUCCESS){
  139. err_out_sys(_T("Cannot open registry."), ret);
  140. return FALSE;
  141. }
  142. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  143. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  144. includes '\0'. */
  145. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  146. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  147. &data_size);
  148. if (ret != ERROR_SUCCESS){
  149. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  150. func_ret = FALSE;
  151. }
  152. else{
  153. if (!find_reg_str(reg_str, path, NULL)){
  154. _tcscat(reg_str, _T(";"));
  155. _tcscat(reg_str, path);
  156. size_t len = _tcslen(reg_str);
  157. if (len >= MAX_PATH_LEN)
  158. {
  159. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  160. func_ret = FALSE;
  161. }
  162. else
  163. {
  164. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  165. (LPBYTE)reg_str,
  166. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  167. if (ret != ERROR_SUCCESS){
  168. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  169. func_ret = FALSE;
  170. }
  171. /* Is this needed to make the new key avaible? */
  172. RegFlushKey(key);
  173. SetLastError(0);
  174. path_reg_propagate();
  175. }
  176. }
  177. }
  178. RegCloseKey(key);
  179. free(reg_str);
  180. return func_ret;
  181. }
  182. //---------------------------------------------------------------------------
  183. // Removes "path" from the registry. Return "TRUE" if the path has been
  184. // removed or it wasn't in the registry, "FALSE" otherwise.
  185. BOOL remove_path_reg(LPCTSTR path){
  186. HKEY key;
  187. LONG ret;
  188. DWORD data_size;
  189. LPTSTR reg_str;
  190. LPTSTR reg_str2;
  191. BOOL func_ret = TRUE;
  192. LPTSTR next;
  193. LPTSTR del_part;
  194. int last_pos;
  195. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  196. KEY_WRITE | KEY_READ, &key);
  197. if (ret != ERROR_SUCCESS){
  198. err_out_sys(_T("Cannot open registry."), ret);
  199. return FALSE;
  200. }
  201. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  202. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  203. includes '\0'. */
  204. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  205. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  206. (LPBYTE)reg_str, &data_size);
  207. if (ret != ERROR_SUCCESS){
  208. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  209. func_ret = FALSE;
  210. }
  211. else{
  212. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  213. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  214. *del_part = '\0';
  215. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  216. last_pos = _tcslen(reg_str2) - 1;
  217. if (last_pos != -1 && reg_str2[last_pos] == ';')
  218. reg_str2[last_pos] = '\0';
  219. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  220. (LPBYTE)reg_str2,
  221. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  222. if (ret != ERROR_SUCCESS){
  223. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  224. func_ret = FALSE;
  225. }
  226. free(reg_str2);
  227. /* Is this needed to make the new key avaible? */
  228. RegFlushKey(key);
  229. SetLastError(0);
  230. path_reg_propagate();
  231. }
  232. }
  233. RegCloseKey(key);
  234. free(reg_str);
  235. return func_ret;
  236. }
  237. //---------------------------------------------------------------------------
  238. //---------------------------------------------------------------------------
  239. void __fastcall AddSearchPath(const UnicodeString Path)
  240. {
  241. if (!add_path_reg(Path.c_str()))
  242. {
  243. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  244. }
  245. }
  246. //---------------------------------------------------------------------------
  247. void __fastcall RemoveSearchPath(const UnicodeString Path)
  248. {
  249. if (!remove_path_reg(Path.c_str()))
  250. {
  251. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  252. }
  253. }
  254. //---------------------------------------------------------------------------
  255. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  256. //---------------------------------------------------------------------------
  257. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  258. {
  259. if (Registry->OpenKey(Key, false))
  260. {
  261. std::auto_ptr<TStrings> List(new TStringList());
  262. Registry->GetValueNames(List.get());
  263. bool CanDelete = true;
  264. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  265. {
  266. UnicodeString ValueName = List->Strings[Index];
  267. if (!AllowRootValues)
  268. {
  269. CanDelete = false;
  270. }
  271. if ((ValueName != L"") &&
  272. (ValueName != L"URL Protocol") &&
  273. (ValueName != L"EditFlags") &&
  274. (ValueName != L"BrowserFlags"))
  275. {
  276. CanDelete = false;
  277. }
  278. }
  279. List->Clear();
  280. Registry->GetKeyNames(List.get());
  281. Registry->CloseKey();
  282. if (CanDelete)
  283. {
  284. for (int Index = 0; Index < List->Count; Index++)
  285. {
  286. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  287. }
  288. // will fail, if not all subkeys got removed
  289. Registry->DeleteKey(Key);
  290. }
  291. }
  292. }
  293. //---------------------------------------------------------------------------
  294. static void __fastcall RegisterProtocol(TRegistry * Registry,
  295. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  296. {
  297. if (Description.IsEmpty())
  298. {
  299. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  300. }
  301. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  302. if (Force || !Registry->KeyExists(ProtocolKey))
  303. {
  304. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  305. {
  306. Registry->WriteString(L"", Description);
  307. Registry->WriteString(L"URL Protocol", L"");
  308. Registry->WriteInteger(L"EditFlags", 0x02);
  309. Registry->WriteInteger(L"BrowserFlags", 0x08);
  310. if (Registry->OpenKey(L"DefaultIcon", true))
  311. {
  312. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  313. Registry->CloseKey();
  314. }
  315. else
  316. {
  317. Abort();
  318. }
  319. }
  320. else
  321. {
  322. Abort();
  323. }
  324. }
  325. }
  326. //---------------------------------------------------------------------------
  327. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  328. const UnicodeString & Protocol)
  329. {
  330. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  331. }
  332. //---------------------------------------------------------------------------
  333. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  334. {
  335. std::auto_ptr<TRegistry> Registry(new TRegistry());
  336. Registry->Access = KEY_WRITE | KEY_READ;
  337. Registry->RootKey = RootKey;
  338. return Registry.release();
  339. }
  340. //---------------------------------------------------------------------------
  341. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  342. const UnicodeString & Protocol, UnicodeString Description = "")
  343. {
  344. std::auto_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  345. RegisterProtocol(Registry.get(), Protocol, Description, true);
  346. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  347. Registry->OpenKey(L"shell", true) &&
  348. Registry->OpenKey(L"open", true) &&
  349. Registry->OpenKey(L"command", true))
  350. {
  351. Registry->WriteString(L"", FORMAT(L"\"%s\" /unsafe \"%%1\"", (Application->ExeName)));
  352. Registry->CloseKey();
  353. }
  354. else
  355. {
  356. Abort();
  357. }
  358. }
  359. //---------------------------------------------------------------------------
  360. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  361. {
  362. try
  363. {
  364. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  365. // get rid of any HKCU registraction that would overrite the HKLM one
  366. std::auto_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  367. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  368. {
  369. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  370. }
  371. }
  372. catch (Exception & E)
  373. {
  374. try
  375. {
  376. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  377. }
  378. catch(Exception & E)
  379. {
  380. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  381. }
  382. }
  383. }
  384. //---------------------------------------------------------------------------
  385. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  386. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  387. {
  388. std::auto_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  389. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  390. if (Registry->OpenKey(DefaultIconKey, false))
  391. {
  392. UnicodeString Value = Registry->ReadString(L"");
  393. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  394. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  395. {
  396. Registry->DeleteValue(L"");
  397. }
  398. Registry->CloseKey();
  399. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  400. }
  401. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  402. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  403. {
  404. UnicodeString Value = Registry->ReadString(L"");
  405. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  406. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  407. {
  408. Registry->DeleteValue(L"");
  409. }
  410. Registry->CloseKey();
  411. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  412. }
  413. if (UnregisterProtocol)
  414. {
  415. ::UnregisterProtocol(Registry.get(), Protocol);
  416. }
  417. }
  418. //---------------------------------------------------------------------------
  419. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  420. {
  421. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  422. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  423. }
  424. //---------------------------------------------------------------------------
  425. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  426. {
  427. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  428. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  429. }
  430. //---------------------------------------------------------------------------
  431. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  432. {
  433. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  434. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  435. // add WebDAV
  436. }
  437. //---------------------------------------------------------------------------
  438. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  439. //---------------------------------------------------------------------------
  440. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  441. {
  442. // Register protocol, if it does not exist yet.
  443. // Prior to Windows 8, we need to register ourselves as legacy handler to
  444. // become the default handler. On Windows 8, it's automatic as long as no other
  445. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  446. RegisterAsUrlHandler(RootKey, Protocol);
  447. // see http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
  448. std::auto_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  449. // create capabilities record
  450. // this has to be a separate branch from WinSCP one, as by its presence we
  451. // enforce registry storage usage, and the capabilities branch may exist
  452. // even if we are using INI file
  453. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  454. if (!Registry->OpenKey(CapabilitiesKey, true))
  455. {
  456. Abort();
  457. }
  458. UnicodeString Description = LoadStr(REGISTERED_APP_DESC);
  459. Registry->WriteString(L"ApplicationDescription", Description);
  460. if (!Registry->OpenKey(L"UrlAssociations", true))
  461. {
  462. Abort();
  463. }
  464. Registry->WriteString(Protocol, GenericUrlHandler);
  465. Registry->CloseKey();
  466. // register application
  467. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  468. {
  469. Abort();
  470. }
  471. Registry->WriteString(AppNameString(), CapabilitiesKey);
  472. Registry->CloseKey();
  473. }
  474. //---------------------------------------------------------------------------
  475. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  476. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  477. {
  478. std::auto_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  479. // unregister the protocol
  480. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  481. // remove capabilities record
  482. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  483. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  484. if (Registry->OpenKey(UrlAssociationsKey, false))
  485. {
  486. Registry->DeleteValue(Protocol);
  487. Registry->CloseKey();
  488. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  489. }
  490. if (Registry->OpenKey(CapabilitiesKey, false))
  491. {
  492. if (!Registry->HasSubKeys())
  493. {
  494. Registry->DeleteValue(L"ApplicationDescription");
  495. }
  496. Registry->CloseKey();
  497. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  498. }
  499. if (!Registry->KeyExists(CapabilitiesKey))
  500. {
  501. // unregister application
  502. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  503. {
  504. Registry->DeleteValue(AppNameString());
  505. Registry->CloseKey();
  506. }
  507. }
  508. }
  509. //---------------------------------------------------------------------------
  510. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  511. {
  512. // register URL handler, if it does not exist yet
  513. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  514. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  515. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  516. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  517. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  518. }
  519. //---------------------------------------------------------------------------
  520. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  521. {
  522. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  523. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  524. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  525. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  526. // we should not really need the "force" flag here, but why not
  527. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  528. }
  529. //---------------------------------------------------------------------------
  530. static void __fastcall RegisterForDefaultPrograms()
  531. {
  532. try
  533. {
  534. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  535. // make sure we unregister any legacy protocol handler for CU,
  536. // this is needed for Windows Vista+7
  537. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  538. }
  539. catch (Exception & E)
  540. {
  541. try
  542. {
  543. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  544. }
  545. catch (Exception & E)
  546. {
  547. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  548. }
  549. }
  550. }
  551. //---------------------------------------------------------------------------
  552. static void __fastcall NotifyChangedAssociations()
  553. {
  554. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  555. }
  556. //---------------------------------------------------------------------------
  557. void __fastcall RegisterForDefaultProtocols()
  558. {
  559. if (IsWinVista())
  560. {
  561. RegisterForDefaultPrograms();
  562. }
  563. else
  564. {
  565. RegisterAsNonBrowserUrlHandler(UnicodeString());
  566. }
  567. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  568. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  569. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  570. // add WebDAV
  571. NotifyChangedAssociations();
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall UnregisterForProtocols()
  575. {
  576. UnregisterAsUrlHandlers(UnicodeString(), false);
  577. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  578. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  579. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  580. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  581. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  582. NotifyChangedAssociations();
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall LaunchAdvancedAssociationUI()
  586. {
  587. assert(IsWinVista());
  588. RegisterForDefaultPrograms();
  589. NotifyChangedAssociations();
  590. // sleep recommended by http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  591. Sleep(1000);
  592. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  593. HRESULT Result =
  594. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  595. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  596. if (SUCCEEDED(Result))
  597. {
  598. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  599. AppAssocRegUI->Release();
  600. }
  601. }
  602. //---------------------------------------------------------------------------
  603. void __fastcall TemporaryDirectoryCleanup()
  604. {
  605. bool Continue = true;
  606. TStrings * Folders = NULL;
  607. try
  608. {
  609. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  610. {
  611. Folders = WinConfiguration->FindTemporaryFolders();
  612. Continue = (Folders != NULL);
  613. if (Continue)
  614. {
  615. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  616. TQueryButtonAlias Aliases[1];
  617. Aliases[0].Button = qaRetry;
  618. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  619. TMessageParams Params(mpNeverAskAgainCheck);
  620. Params.Aliases = Aliases;
  621. Params.AliasesCount = LENOF(Aliases);
  622. unsigned int Answer = MoreMessageDialog(
  623. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  624. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  625. if (Answer == qaNeverAskAgain)
  626. {
  627. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  628. Answer = qaYes;
  629. }
  630. else if (Answer == qaRetry)
  631. {
  632. for (int Index = 0; Index < Folders->Count; Index++)
  633. {
  634. ShellExecute(Application->Handle, NULL,
  635. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  636. }
  637. }
  638. Continue = (Answer == qaYes);
  639. }
  640. }
  641. if (Continue)
  642. {
  643. try
  644. {
  645. WinConfiguration->CleanupTemporaryFolders(Folders);
  646. }
  647. catch (Exception &E)
  648. {
  649. ShowExtendedException(&E);
  650. }
  651. }
  652. }
  653. __finally
  654. {
  655. delete Folders;
  656. }
  657. }
  658. //-------------------------------------------- -------------------------------
  659. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  660. {
  661. int MajorVer = Version / (10000*100*100);
  662. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  663. int Release = (Version % (10000*100)) / (10000);
  664. UnicodeString Result;
  665. if (Release > 0)
  666. {
  667. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  668. }
  669. else
  670. {
  671. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  672. }
  673. return Result;
  674. }
  675. //---------------------------------------------------------------------------
  676. UnicodeString __fastcall CampaignUrl(UnicodeString AURL)
  677. {
  678. // see also TWebHelpSystem::ShowHelp
  679. const wchar_t FragmentSeparator = L'#';
  680. UnicodeString URL = ::CutToChar(AURL, FragmentSeparator, false);
  681. if (URL.Pos(L"?") == 0)
  682. {
  683. URL += L"?";
  684. }
  685. else
  686. {
  687. URL += L"&";
  688. }
  689. int CurrentCompoundVer = Configuration->CompoundVersion;
  690. AnsiString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  691. URL += FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  692. AddToList(URL, AURL, FragmentSeparator);
  693. return URL;
  694. }
  695. //---------------------------------------------------------------------------
  696. UnicodeString __fastcall GetUsageData()
  697. {
  698. return Configuration->Usage->Serialize();
  699. }
  700. //---------------------------------------------------------------------------
  701. void __fastcall QueryUpdates()
  702. {
  703. bool Complete = false;
  704. try
  705. {
  706. UnicodeString Response;
  707. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  708. int CurrentCompoundVer = Configuration->CompoundVersion;
  709. UnicodeString CurrentVersionStr =
  710. FORMAT(L"%d.%d.%d.%d",
  711. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  712. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  713. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  714. THttp * CheckForUpdatesHTTP = new THttp(Application);
  715. try
  716. {
  717. UnicodeString URL = LoadStr(UPDATES_URL) +
  718. FORMAT(L"?v=%s&lang=%s", (CurrentVersionStr,
  719. IntToHex(__int64(GUIConfiguration->Locale), 4)));
  720. bool Beta;
  721. if (WinConfiguration->IsBeta)
  722. {
  723. Beta = true;
  724. }
  725. else
  726. {
  727. switch (Updates.BetaVersions)
  728. {
  729. case asAuto:
  730. Beta = WinConfiguration->AnyBetaInVersionHistory;
  731. break;
  732. case asOn:
  733. Beta = true;
  734. break;
  735. default:
  736. Beta = false;
  737. break;
  738. }
  739. }
  740. if (Beta)
  741. {
  742. URL += L"&beta=1";
  743. }
  744. URL += L"&dotnet=" + Updates.DotNetVersion;
  745. URL += L"&console=" + Updates.ConsoleVersion;
  746. UnicodeString Proxy;
  747. switch (Updates.ConnectionType)
  748. {
  749. case ctAuto:
  750. AutodetectProxyUrl(Proxy);
  751. break;
  752. case ctProxy:
  753. Proxy = FORMAT(L"%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  754. break;
  755. }
  756. CheckForUpdatesHTTP->Proxy = Proxy;
  757. CheckForUpdatesHTTP->URL = URL;
  758. if (Configuration->CollectUsage)
  759. {
  760. UTF8String UtfUsage = UTF8String(GetUsageData());
  761. CheckForUpdatesHTTP->Stream->Write(UtfUsage.c_str(), UtfUsage.Length());
  762. CheckForUpdatesHTTP->Post();
  763. }
  764. else
  765. {
  766. CheckForUpdatesHTTP->Action();
  767. }
  768. // sanity check
  769. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  770. {
  771. Abort();
  772. }
  773. UTF8String UtfResponse;
  774. UtfResponse.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  775. CheckForUpdatesHTTP->Stream->Read(UtfResponse.c_str(), UtfResponse.Length());
  776. Response = UnicodeString(UtfResponse);
  777. }
  778. __finally
  779. {
  780. delete CheckForUpdatesHTTP;
  781. }
  782. bool Changed = !Updates.HaveResults;
  783. Updates.LastCheck = Now();
  784. Updates.HaveResults = true;
  785. TUpdatesData PrevResults = Updates.Results;
  786. Updates.Results.Reset();
  787. Updates.Results.ForVersion = CurrentCompoundVer;
  788. while (!Response.IsEmpty())
  789. {
  790. UnicodeString Line = ::CutToChar(Response, L'\n', false);
  791. UnicodeString Name = ::CutToChar(Line, L'=', false);
  792. if (AnsiSameText(Name, "Version"))
  793. {
  794. int MajorVer = StrToInt(::CutToChar(Line, L'.', false));
  795. int MinorVer = StrToInt(::CutToChar(Line, L'.', false));
  796. int Release = StrToInt(::CutToChar(Line, L'.', false));
  797. int Build = StrToInt(::CutToChar(Line, L'.', false));
  798. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  799. Changed |= (NewVersion != PrevResults.Version);
  800. if (NewVersion <= CurrentCompoundVer)
  801. {
  802. NewVersion = 0;
  803. }
  804. Updates.Results.Version = NewVersion;
  805. Complete = true;
  806. }
  807. else if (AnsiSameText(Name, L"Message"))
  808. {
  809. Changed |= (PrevResults.Message != Line);
  810. Updates.Results.Message = Line;
  811. }
  812. else if (AnsiSameText(Name, L"Critical"))
  813. {
  814. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  815. Changed |= (PrevResults.Critical != NewCritical);
  816. Updates.Results.Critical = NewCritical;
  817. }
  818. else if (AnsiSameText(Name, L"Release"))
  819. {
  820. Changed |= (PrevResults.Release != Line);
  821. Updates.Results.Release = Line;
  822. }
  823. else if (AnsiSameText(Name, L"Disabled"))
  824. {
  825. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  826. Changed |= (PrevResults.Disabled != NewDisabled);
  827. Updates.Results.Disabled = NewDisabled;
  828. Complete = true;
  829. }
  830. else if (AnsiSameText(Name, L"Url"))
  831. {
  832. Changed |= (PrevResults.Url != Line);
  833. Updates.Results.Url = Line;
  834. }
  835. else if (AnsiSameText(Name, L"UrlButton"))
  836. {
  837. Changed |= (PrevResults.UrlButton != Line);
  838. Updates.Results.UrlButton = Line;
  839. }
  840. }
  841. if (Changed)
  842. {
  843. Updates.ShownResults = false;
  844. }
  845. WinConfiguration->Updates = Updates;
  846. if (!Complete)
  847. {
  848. EXCEPTION;
  849. }
  850. Configuration->Usage->Reset();
  851. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  852. }
  853. catch(Exception & E)
  854. {
  855. Configuration->Usage->Inc(L"UpdateChecksFailed");
  856. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  857. }
  858. }
  859. //---------------------------------------------------------------------------
  860. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  861. TQueryType & Type, bool Force)
  862. {
  863. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  864. assert(Updates.HaveResults);
  865. if (Updates.HaveResults)
  866. {
  867. if (Updates.Results.Disabled)
  868. {
  869. New = false;
  870. if (Force)
  871. {
  872. Message = LoadStr(UPDATE_DISABLED);
  873. }
  874. }
  875. else
  876. {
  877. New = (Updates.Results.Version > 0);
  878. if (New)
  879. {
  880. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  881. if (!Updates.Results.Release.IsEmpty())
  882. {
  883. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  884. }
  885. Message = FMTLOAD(NEW_VERSION4, (Version));
  886. }
  887. else
  888. {
  889. Message = LoadStr(NO_NEW_VERSION);
  890. }
  891. }
  892. if (!Message.IsEmpty())
  893. {
  894. Message = MainInstructions(Message);
  895. }
  896. if (!Updates.Results.Message.IsEmpty())
  897. {
  898. Message +=
  899. FMTLOAD(UPDATE_MESSAGE,
  900. (ReplaceStr(Updates.Results.Message, L"|", L"\n")));
  901. }
  902. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  903. }
  904. else
  905. {
  906. New = false;
  907. }
  908. }
  909. //---------------------------------------------------------------------------
  910. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  911. {
  912. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  913. OpenBrowser(LoadStr(HISTORY_URL));
  914. }
  915. //---------------------------------------------------------------------------
  916. void __fastcall CheckForUpdates(bool CachedResults)
  917. {
  918. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  919. TOperationVisualizer Visualizer;
  920. try
  921. {
  922. if (ActiveForm)
  923. {
  924. assert(ActiveForm->Enabled);
  925. ActiveForm->Enabled = false;
  926. }
  927. bool Again = false;
  928. do
  929. {
  930. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  931. bool Cached = !Again && Updates.HaveResults &&
  932. (double(Updates.Period) > 0) &&
  933. (Updates.Results.ForVersion == Configuration->CompoundVersion) &&
  934. CachedResults;
  935. if (!Cached)
  936. {
  937. QueryUpdates();
  938. // reread new data
  939. Updates = WinConfiguration->Updates;
  940. }
  941. Again = false;
  942. if (!Updates.ShownResults)
  943. {
  944. Updates.ShownResults = true;
  945. WinConfiguration->Updates = Updates;
  946. }
  947. assert(Updates.HaveResults);
  948. UnicodeString Message;
  949. bool New;
  950. TQueryType Type;
  951. GetUpdatesMessage(Message, New, Type, true);
  952. Configuration->Usage->Inc(L"UpdateDisplays");
  953. if (New)
  954. {
  955. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  956. }
  957. if (Updates.HaveResults)
  958. {
  959. bool ShowLast = Cached;
  960. bool ShowNext = (double(Updates.Period) > 0);
  961. if (ShowLast || ShowNext)
  962. {
  963. Message += L"\n";
  964. if (ShowLast)
  965. {
  966. Message += L"\n" +
  967. FMTLOAD(UPDATE_LAST,
  968. (FormatDateTime("ddddd", Updates.LastCheck)));
  969. }
  970. if (ShowNext)
  971. {
  972. Message += L"\n" +
  973. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  974. }
  975. }
  976. }
  977. // add FLAGMASK(Cached, qaRetry) to enable "check again" button
  978. // for cached results
  979. int Answers = qaOK |
  980. FLAGMASK(New, qaCancel | qaAll) |
  981. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  982. TQueryButtonAlias Aliases[4];
  983. Aliases[0].Button = qaRetry;
  984. Aliases[0].Alias = LoadStr(CHECK_AGAIN_BUTTON);
  985. Aliases[1].Button = qaYes;
  986. if (Updates.Results.UrlButton.IsEmpty())
  987. {
  988. Aliases[1].Alias = LoadStr(UPDATE_URL_BUTTON);
  989. }
  990. else
  991. {
  992. Aliases[1].Alias = Updates.Results.UrlButton;
  993. }
  994. Aliases[2].Button = qaAll;
  995. Aliases[2].Alias = LoadStr(WHATS_NEW_BUTTON);
  996. Aliases[2].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  997. Aliases[3].Button = qaOK;
  998. Aliases[3].Alias = LoadStr(DOWNLOAD_BUTTON);
  999. TMessageParams Params;
  1000. Params.Aliases = Aliases;
  1001. // alias "ok" button to "download" only if we have new version
  1002. Params.AliasesCount = (New ? 4 : 3);
  1003. unsigned int Answer =
  1004. MessageDialog(Message, Type,
  1005. Answers, HELP_UPDATES, &Params);
  1006. switch (Answer)
  1007. {
  1008. case qaOK:
  1009. if (New)
  1010. {
  1011. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1012. OpenBrowser(LoadStr(UPGRADE_URL));
  1013. }
  1014. break;
  1015. case qaYes:
  1016. OpenBrowser(Updates.Results.Url);
  1017. break;
  1018. case qaAll:
  1019. FAIL;
  1020. break;
  1021. case qaRetry:
  1022. Again = true;
  1023. break;
  1024. }
  1025. }
  1026. while (Again);
  1027. }
  1028. __finally
  1029. {
  1030. if (ActiveForm)
  1031. {
  1032. ActiveForm->Enabled = true;
  1033. }
  1034. }
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. class TUpdateThread : public TCompThread
  1038. {
  1039. public:
  1040. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1041. protected:
  1042. virtual void __fastcall Execute();
  1043. TThreadMethod FOnUpdatesChecked;
  1044. };
  1045. //---------------------------------------------------------------------------
  1046. TUpdateThread * UpdateThread = NULL;
  1047. //---------------------------------------------------------------------------
  1048. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1049. TCompThread(false),
  1050. FOnUpdatesChecked(OnUpdatesChecked)
  1051. {
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TUpdateThread::Execute()
  1055. {
  1056. try
  1057. {
  1058. QueryUpdates();
  1059. if (FOnUpdatesChecked != NULL)
  1060. {
  1061. Synchronize(FOnUpdatesChecked);
  1062. }
  1063. }
  1064. catch(...)
  1065. {
  1066. // ignore errors
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1071. {
  1072. assert(UpdateThread == NULL);
  1073. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall StopUpdateThread()
  1077. {
  1078. if (UpdateThread != NULL)
  1079. {
  1080. SAFE_DESTROY(UpdateThread);
  1081. }
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall SetupInitialize()
  1085. {
  1086. WinConfiguration->UpdateJumpList();
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1090. UnicodeString AdditionalParams, TStringList * Removed,
  1091. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1092. int IconIndex)
  1093. {
  1094. bool Result = false;
  1095. IObjectCollection * Collection = NULL;
  1096. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1097. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1098. {
  1099. try
  1100. {
  1101. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1102. int Count = 0;
  1103. for (int Index = 0; Index < Names->Count; Index++)
  1104. {
  1105. IShellLink * Link =
  1106. CreateDesktopSessionShortCut(
  1107. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1108. wchar_t Desc[2048];
  1109. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1110. {
  1111. if (Removed->IndexOf(Desc) < 0)
  1112. {
  1113. try
  1114. {
  1115. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1116. Count++;
  1117. }
  1118. __finally
  1119. {
  1120. Link->Release();
  1121. }
  1122. }
  1123. else
  1124. {
  1125. Names->Delete(Index);
  1126. Index--;
  1127. }
  1128. }
  1129. }
  1130. if (Count > 0)
  1131. {
  1132. IObjectArray * Array;
  1133. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1134. {
  1135. try
  1136. {
  1137. Result = SUCCEEDED(
  1138. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1139. }
  1140. __finally
  1141. {
  1142. Array->Release();
  1143. }
  1144. }
  1145. }
  1146. }
  1147. __finally
  1148. {
  1149. Collection->Release();
  1150. }
  1151. }
  1152. return Result;
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1156. {
  1157. ICustomDestinationList * DestinationList = NULL;
  1158. IObjectArray * RemovedArray = NULL;
  1159. TStringList * Removed = NULL;
  1160. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1161. try
  1162. {
  1163. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1164. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1165. {
  1166. unsigned int MinSlots;
  1167. unsigned int * PMinSlots = &MinSlots;
  1168. void ** PRemovedArray = (void**)&RemovedArray;
  1169. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1170. if (SUCCEEDED(Result) && ALWAYS_TRUE(RemovedArray != NULL))
  1171. {
  1172. Removed = new TStringList();
  1173. unsigned int RemovedCount;
  1174. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1175. {
  1176. RemovedCount = 0;
  1177. }
  1178. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1179. {
  1180. IShellLink * Link;
  1181. wchar_t Desc[2048];
  1182. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1183. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1184. {
  1185. Removed->Add(Desc);
  1186. }
  1187. }
  1188. AddJumpListCategory(
  1189. WorkspaceNames, L"", Removed, DestinationList,
  1190. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1191. AddJumpListCategory(
  1192. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1193. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1194. if (DestinationList != NULL)
  1195. {
  1196. DestinationList->CommitList();
  1197. }
  1198. }
  1199. }
  1200. }
  1201. __finally
  1202. {
  1203. SetErrorMode(OldErrMode);
  1204. if (RemovedArray != NULL)
  1205. {
  1206. RemovedArray->Release();
  1207. }
  1208. if (DestinationList != NULL)
  1209. {
  1210. DestinationList->Release();
  1211. }
  1212. delete Removed;
  1213. }
  1214. }
  1215. //---------------------------------------------------------------------------
  1216. bool __fastcall AnyOtherInstanceOfSelf()
  1217. {
  1218. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1219. bool Result = false;
  1220. try
  1221. {
  1222. unsigned int Process = GetCurrentProcessId();
  1223. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1224. PROCESSENTRY32 ProcessEntry;
  1225. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1226. if (Process32First(Snapshot, &ProcessEntry))
  1227. {
  1228. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1229. {
  1230. // we should check if the process is running in the same session,
  1231. // but for that we probably need some special priviledges
  1232. if ((Process != ProcessEntry.th32ProcessID) &&
  1233. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1234. {
  1235. Result = true;
  1236. }
  1237. }
  1238. }
  1239. }
  1240. __finally
  1241. {
  1242. CloseHandle(Snapshot);
  1243. }
  1244. return Result;
  1245. }