Setup.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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. }
  847. catch(Exception & E)
  848. {
  849. throw ExtException(&E, LoadStr(CHECK_FOR_UPDATES_ERROR));
  850. }
  851. if (Complete)
  852. {
  853. Configuration->Usage->Reset();
  854. }
  855. else
  856. {
  857. throw Exception(LoadStr(CHECK_FOR_UPDATES_ERROR));
  858. }
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  862. TQueryType & Type, bool Force)
  863. {
  864. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  865. assert(Updates.HaveResults);
  866. if (Updates.HaveResults)
  867. {
  868. if (Updates.Results.Disabled)
  869. {
  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. Busy(true);
  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(DOWNLOAD_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. Busy(false);
  1035. }
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. class TUpdateThread : public TCompThread
  1039. {
  1040. public:
  1041. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1042. protected:
  1043. virtual void __fastcall Execute();
  1044. TThreadMethod FOnUpdatesChecked;
  1045. };
  1046. //---------------------------------------------------------------------------
  1047. TUpdateThread * UpdateThread = NULL;
  1048. //---------------------------------------------------------------------------
  1049. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1050. TCompThread(false),
  1051. FOnUpdatesChecked(OnUpdatesChecked)
  1052. {
  1053. }
  1054. //---------------------------------------------------------------------------
  1055. void __fastcall TUpdateThread::Execute()
  1056. {
  1057. try
  1058. {
  1059. QueryUpdates();
  1060. if (FOnUpdatesChecked != NULL)
  1061. {
  1062. Synchronize(FOnUpdatesChecked);
  1063. }
  1064. }
  1065. catch(...)
  1066. {
  1067. // ignore errors
  1068. }
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1072. {
  1073. assert(UpdateThread == NULL);
  1074. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. void __fastcall StopUpdateThread()
  1078. {
  1079. if (UpdateThread != NULL)
  1080. {
  1081. SAFE_DESTROY(UpdateThread);
  1082. }
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. void __fastcall SetupInitialize()
  1086. {
  1087. WinConfiguration->UpdateJumpList();
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1091. UnicodeString AdditionalParams, TStringList * Removed,
  1092. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1093. int IconIndex)
  1094. {
  1095. bool Result = false;
  1096. IObjectCollection * Collection = NULL;
  1097. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1098. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1099. {
  1100. try
  1101. {
  1102. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1103. int Count = 0;
  1104. for (int Index = 0; Index < Names->Count; Index++)
  1105. {
  1106. IShellLink * Link =
  1107. CreateDesktopSessionShortCut(
  1108. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1109. wchar_t Desc[2048];
  1110. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1111. {
  1112. if (Removed->IndexOf(Desc) < 0)
  1113. {
  1114. try
  1115. {
  1116. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1117. Count++;
  1118. }
  1119. __finally
  1120. {
  1121. Link->Release();
  1122. }
  1123. }
  1124. else
  1125. {
  1126. Names->Delete(Index);
  1127. Index--;
  1128. }
  1129. }
  1130. }
  1131. if (Count > 0)
  1132. {
  1133. IObjectArray * Array;
  1134. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1135. {
  1136. try
  1137. {
  1138. Result = SUCCEEDED(
  1139. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1140. }
  1141. __finally
  1142. {
  1143. Array->Release();
  1144. }
  1145. }
  1146. }
  1147. }
  1148. __finally
  1149. {
  1150. Collection->Release();
  1151. }
  1152. }
  1153. return Result;
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1157. {
  1158. ICustomDestinationList * DestinationList = NULL;
  1159. IObjectArray * RemovedArray = NULL;
  1160. TStringList * Removed = NULL;
  1161. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1162. try
  1163. {
  1164. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1165. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1166. {
  1167. unsigned int MinSlots;
  1168. unsigned int * PMinSlots = &MinSlots;
  1169. void ** PRemovedArray = (void**)&RemovedArray;
  1170. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1171. if (SUCCEEDED(Result) && ALWAYS_TRUE(RemovedArray != NULL))
  1172. {
  1173. Removed = new TStringList();
  1174. unsigned int RemovedCount;
  1175. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1176. {
  1177. RemovedCount = 0;
  1178. }
  1179. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1180. {
  1181. IShellLink * Link;
  1182. wchar_t Desc[2048];
  1183. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1184. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1185. {
  1186. Removed->Add(Desc);
  1187. }
  1188. }
  1189. AddJumpListCategory(
  1190. WorkspaceNames, L"", Removed, DestinationList,
  1191. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1192. AddJumpListCategory(
  1193. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1194. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1195. if (DestinationList != NULL)
  1196. {
  1197. DestinationList->CommitList();
  1198. }
  1199. }
  1200. }
  1201. }
  1202. __finally
  1203. {
  1204. SetErrorMode(OldErrMode);
  1205. if (RemovedArray != NULL)
  1206. {
  1207. RemovedArray->Release();
  1208. }
  1209. if (DestinationList != NULL)
  1210. {
  1211. DestinationList->Release();
  1212. }
  1213. delete Removed;
  1214. }
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. bool __fastcall AnyOtherInstanceOfSelf()
  1218. {
  1219. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1220. bool Result = false;
  1221. try
  1222. {
  1223. unsigned int Process = GetCurrentProcessId();
  1224. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1225. PROCESSENTRY32 ProcessEntry;
  1226. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1227. if (Process32First(Snapshot, &ProcessEntry))
  1228. {
  1229. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1230. {
  1231. // we should check if the process is running in the same session,
  1232. // but for that we probably need some special priviledges
  1233. if ((Process != ProcessEntry.th32ProcessID) &&
  1234. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1235. {
  1236. Result = true;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. __finally
  1242. {
  1243. CloseHandle(Snapshot);
  1244. }
  1245. return Result;
  1246. }