Setup.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. //---------------------------------------------------------------------------
  25. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  26. _T("Session Manager\\Environment")
  27. // when the PATH registry key is over aprox 2048 characters,
  28. // PATH as well as WINDIR variables are actually not set, breaking the system
  29. #define MAX_PATH_LEN 2000
  30. /* Command line options. */
  31. UnicodeString LastPathError;
  32. //---------------------------------------------------------------------------
  33. // Display the error "err_msg".
  34. void err_out(LPCTSTR err_msg)
  35. {
  36. LastPathError = err_msg;
  37. }
  38. //---------------------------------------------------------------------------
  39. // Display "base_err_msg" followed by the description of the system error
  40. // identified by "sys_err".
  41. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  42. {
  43. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  44. }
  45. //---------------------------------------------------------------------------
  46. // Works as "strcmp" but the comparison is not case sensitive.
  47. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  48. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  49. if (*str1 == L'\0')
  50. return 0;
  51. return tolower(*str1) - tolower(*str2);
  52. }
  53. //---------------------------------------------------------------------------
  54. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  55. // not present). The returned value must be freed with "free".
  56. LPTSTR unquote(LPCTSTR str){
  57. int last_pos;
  58. LPTSTR ret;
  59. size_t new_len;
  60. last_pos = _tcslen(str) - 1;
  61. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  62. new_len= (_tcslen(str) - 1);
  63. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  64. lstrcpyn(ret, &str[1], new_len);
  65. }
  66. else
  67. ret = _tcsdup(str);
  68. return ret;
  69. }
  70. //---------------------------------------------------------------------------
  71. // Find "what" in the ";" separated string "str" and returns a pointer to
  72. // the first letter of "what" in the string. If "next" is not "NULL" it
  73. // points to the first letter after "what" (excluding the trailing ";").
  74. // If "what" isn't find the functions returns "NULL".
  75. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  76. LPTSTR tok_buff;
  77. LPTSTR curr_tok;
  78. LPTSTR curr_tok_dup;
  79. BOOL path_eq;
  80. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  81. int pos = -1;
  82. LPTSTR ret;
  83. tok_buff = _tcsdup(str);
  84. curr_tok = _tcstok(tok_buff, _T(";"));
  85. while (pos == -1 && curr_tok){
  86. curr_tok_dup = unquote(curr_tok);
  87. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  88. GetShortPathName(curr_tok_dup, sh_path2,
  89. LENOF(sh_path2)) &&
  90. (tcharicmp(sh_path1, sh_path2) == 0);
  91. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  92. pos = curr_tok - tok_buff;
  93. }
  94. free(curr_tok_dup);
  95. curr_tok = _tcstok(NULL, _T(";"));
  96. if (pos != -1 && next){
  97. if (curr_tok)
  98. *next = str + (curr_tok - tok_buff);
  99. else
  100. *next = str + _tcslen(str);
  101. }
  102. }
  103. free(tok_buff);
  104. if (pos != -1)
  105. ret = str + pos;
  106. else
  107. ret = NULL;
  108. return ret;
  109. }
  110. //---------------------------------------------------------------------------
  111. void path_reg_propagate()
  112. {
  113. DWORD send_message_result;
  114. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  115. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  116. 5000, &send_message_result);
  117. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  118. {
  119. err_out_sys(_T("Cannot propagate the new enviroment to ")
  120. _T("other processes. The new value will be ")
  121. _T("avaible after a reboot."), GetLastError());
  122. SimpleErrorDialog(LastPathError);
  123. LastPathError = L"";
  124. }
  125. }
  126. //---------------------------------------------------------------------------
  127. // Add "path" to the registry. Return "TRUE" if the path has been added or
  128. // was already in the registry, "FALSE" otherwise.
  129. BOOL add_path_reg(LPCTSTR path){
  130. HKEY key;
  131. LONG ret;
  132. DWORD data_size;
  133. LPTSTR reg_str;
  134. BOOL func_ret = TRUE;
  135. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  136. KEY_WRITE | KEY_READ, &key);
  137. if (ret != ERROR_SUCCESS){
  138. err_out_sys(_T("Cannot open registry."), ret);
  139. return FALSE;
  140. }
  141. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  142. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  143. includes '\0'. */
  144. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  145. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  146. &data_size);
  147. if (ret != ERROR_SUCCESS){
  148. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  149. func_ret = FALSE;
  150. }
  151. else{
  152. if (!find_reg_str(reg_str, path, NULL)){
  153. _tcscat(reg_str, _T(";"));
  154. _tcscat(reg_str, path);
  155. size_t len = _tcslen(reg_str);
  156. if (len >= MAX_PATH_LEN)
  157. {
  158. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  159. func_ret = FALSE;
  160. }
  161. else
  162. {
  163. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  164. (LPBYTE)reg_str,
  165. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  166. if (ret != ERROR_SUCCESS){
  167. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  168. func_ret = FALSE;
  169. }
  170. /* Is this needed to make the new key avaible? */
  171. RegFlushKey(key);
  172. SetLastError(0);
  173. path_reg_propagate();
  174. }
  175. }
  176. }
  177. RegCloseKey(key);
  178. free(reg_str);
  179. return func_ret;
  180. }
  181. //---------------------------------------------------------------------------
  182. // Removes "path" from the registry. Return "TRUE" if the path has been
  183. // removed or it wasn't in the registry, "FALSE" otherwise.
  184. BOOL remove_path_reg(LPCTSTR path){
  185. HKEY key;
  186. LONG ret;
  187. DWORD data_size;
  188. LPTSTR reg_str;
  189. LPTSTR reg_str2;
  190. BOOL func_ret = TRUE;
  191. LPTSTR next;
  192. LPTSTR del_part;
  193. int last_pos;
  194. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  195. KEY_WRITE | KEY_READ, &key);
  196. if (ret != ERROR_SUCCESS){
  197. err_out_sys(_T("Cannot open registry."), ret);
  198. return FALSE;
  199. }
  200. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  201. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  202. includes '\0'. */
  203. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  204. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  205. (LPBYTE)reg_str, &data_size);
  206. if (ret != ERROR_SUCCESS){
  207. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  208. func_ret = FALSE;
  209. }
  210. else{
  211. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  212. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  213. *del_part = '\0';
  214. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  215. last_pos = _tcslen(reg_str2) - 1;
  216. if (last_pos != -1 && reg_str2[last_pos] == ';')
  217. reg_str2[last_pos] = '\0';
  218. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  219. (LPBYTE)reg_str2,
  220. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  221. if (ret != ERROR_SUCCESS){
  222. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  223. func_ret = FALSE;
  224. }
  225. free(reg_str2);
  226. /* Is this needed to make the new key avaible? */
  227. RegFlushKey(key);
  228. SetLastError(0);
  229. path_reg_propagate();
  230. }
  231. }
  232. RegCloseKey(key);
  233. free(reg_str);
  234. return func_ret;
  235. }
  236. //---------------------------------------------------------------------------
  237. //---------------------------------------------------------------------------
  238. void __fastcall AddSearchPath(const UnicodeString Path)
  239. {
  240. if (!add_path_reg(Path.c_str()))
  241. {
  242. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  243. }
  244. }
  245. //---------------------------------------------------------------------------
  246. void __fastcall RemoveSearchPath(const UnicodeString Path)
  247. {
  248. if (!remove_path_reg(Path.c_str()))
  249. {
  250. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  251. }
  252. }
  253. //---------------------------------------------------------------------------
  254. void __fastcall RegisterAsUrlHandler()
  255. {
  256. try
  257. {
  258. bool Success;
  259. bool User = true;
  260. TRegistry * Registry = new TRegistry();
  261. try
  262. {
  263. do
  264. {
  265. Success = true;
  266. User = !User;
  267. try
  268. {
  269. assert(Configuration != NULL);
  270. UnicodeString FileName = Application->ExeName;
  271. UnicodeString BaseKey;
  272. Registry->Access = KEY_WRITE;
  273. if (User)
  274. {
  275. Registry->RootKey = HKEY_CURRENT_USER;
  276. BaseKey = _T("Software\\Classes\\");
  277. }
  278. else
  279. {
  280. Registry->RootKey = HKEY_CLASSES_ROOT;
  281. BaseKey = _T("");
  282. }
  283. UnicodeString Protocol;
  284. for (int Index = 0; Index <= 1; Index++)
  285. {
  286. Protocol = (Index == 0) ? L"SCP" : L"SFTP";
  287. if (Registry->OpenKey(BaseKey + Protocol, true))
  288. {
  289. Registry->WriteString(L"", FMTLOAD(PROTOCOL_URL_DESC, (Protocol)));
  290. Registry->WriteString(L"URL Protocol", L"");
  291. Registry->WriteInteger(L"EditFlags", 0x02);
  292. Registry->WriteInteger(L"BrowserFlags", 0x08);
  293. if (Registry->OpenKey(L"DefaultIcon", true))
  294. {
  295. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (FileName)));
  296. Registry->CloseKey();
  297. }
  298. else
  299. {
  300. Abort();
  301. }
  302. }
  303. else
  304. {
  305. Abort();
  306. }
  307. if (Registry->OpenKey(BaseKey + Protocol, false) &&
  308. Registry->OpenKey(L"shell", true) &&
  309. Registry->OpenKey(L"open", true) &&
  310. Registry->OpenKey(L"command", true))
  311. {
  312. Registry->WriteString(L"", FORMAT(L"\"%s\" /unsafe \"%%1\"", (FileName)));
  313. Registry->CloseKey();
  314. }
  315. else
  316. {
  317. Abort();
  318. }
  319. }
  320. }
  321. catch(...)
  322. {
  323. Success = false;
  324. }
  325. }
  326. while (!Success && !User);
  327. }
  328. __finally
  329. {
  330. delete Registry;
  331. }
  332. }
  333. catch(Exception & E)
  334. {
  335. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR));
  336. }
  337. }
  338. //---------------------------------------------------------------------------
  339. void __fastcall TemporaryDirectoryCleanup()
  340. {
  341. bool Continue = true;
  342. TStrings * Folders = NULL;
  343. try
  344. {
  345. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  346. {
  347. Folders = WinConfiguration->FindTemporaryFolders();
  348. Continue = (Folders != NULL);
  349. if (Continue)
  350. {
  351. TQueryButtonAlias Aliases[1];
  352. Aliases[0].Button = qaRetry;
  353. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  354. TMessageParams Params(mpNeverAskAgainCheck);
  355. Params.Aliases = Aliases;
  356. Params.AliasesCount = LENOF(Aliases);
  357. unsigned int Answer = MoreMessageDialog(
  358. FMTLOAD(CLEANTEMP_CONFIRM, (Folders->Count)), Folders,
  359. qtWarning, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  360. if (Answer == qaNeverAskAgain)
  361. {
  362. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  363. Answer = qaYes;
  364. }
  365. else if (Answer == qaRetry)
  366. {
  367. for (int Index = 0; Index < Folders->Count; Index++)
  368. {
  369. ShellExecute(Application->Handle, NULL,
  370. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  371. }
  372. }
  373. Continue = (Answer == qaYes);
  374. }
  375. }
  376. if (Continue)
  377. {
  378. try
  379. {
  380. WinConfiguration->CleanupTemporaryFolders(Folders);
  381. }
  382. catch (Exception &E)
  383. {
  384. ShowExtendedException(&E);
  385. }
  386. }
  387. }
  388. __finally
  389. {
  390. delete Folders;
  391. }
  392. }
  393. //-------------------------------------------- -------------------------------
  394. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  395. {
  396. int MajorVer = Version / (10000*100*100);
  397. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  398. int Release = (Version % (10000*100)) / (10000);
  399. UnicodeString Result;
  400. if (Release > 0)
  401. {
  402. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  403. }
  404. else
  405. {
  406. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  407. }
  408. return Result;
  409. }
  410. //---------------------------------------------------------------------------
  411. UnicodeString __fastcall CampaignUrl(UnicodeString AURL)
  412. {
  413. // see also TWebHelpSystem::ShowHelp
  414. const wchar_t FragmentSeparator = L'#';
  415. UnicodeString URL = ::CutToChar(AURL, FragmentSeparator, false);
  416. if (URL.Pos(L"?") == 0)
  417. {
  418. URL += L"?";
  419. }
  420. else
  421. {
  422. URL += L"&";
  423. }
  424. int CurrentCompoundVer = Configuration->CompoundVersion;
  425. AnsiString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  426. URL += FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  427. AddToList(URL, AURL, FragmentSeparator);
  428. return URL;
  429. }
  430. //---------------------------------------------------------------------------
  431. UnicodeString __fastcall GetUsageData()
  432. {
  433. return Configuration->Usage->Serialize();
  434. }
  435. //---------------------------------------------------------------------------
  436. void __fastcall QueryUpdates()
  437. {
  438. bool Complete = false;
  439. try
  440. {
  441. UnicodeString Response;
  442. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  443. int CurrentCompoundVer = Configuration->CompoundVersion;
  444. UnicodeString CurrentVersionStr =
  445. FORMAT(L"%d.%d.%d.%d",
  446. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  447. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  448. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  449. THttp * CheckForUpdatesHTTP = new THttp(Application);
  450. try
  451. {
  452. UnicodeString URL = LoadStr(UPDATES_URL) +
  453. FORMAT(L"?v=%s&lang=%s", (CurrentVersionStr,
  454. IntToHex(__int64(GUIConfiguration->Locale), 4)));
  455. bool Beta;
  456. if (WinConfiguration->IsBeta)
  457. {
  458. Beta = true;
  459. }
  460. else
  461. {
  462. switch (Updates.BetaVersions)
  463. {
  464. case asAuto:
  465. Beta = WinConfiguration->AnyBetaInVersionHistory;
  466. break;
  467. case asOn:
  468. Beta = true;
  469. break;
  470. default:
  471. Beta = false;
  472. break;
  473. }
  474. }
  475. if (Beta)
  476. {
  477. URL += L"&beta=1";
  478. }
  479. URL += L"&dotnet=" + Updates.DotNetVersion;
  480. URL += L"&console=" + Updates.ConsoleVersion;
  481. UnicodeString Proxy;
  482. switch (Updates.ConnectionType)
  483. {
  484. case ctAuto:
  485. AutodetectProxyUrl(Proxy);
  486. break;
  487. case ctProxy:
  488. Proxy = FORMAT(L"%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  489. break;
  490. }
  491. CheckForUpdatesHTTP->Proxy = Proxy;
  492. CheckForUpdatesHTTP->URL = URL;
  493. if (Configuration->CollectUsage)
  494. {
  495. UTF8String UtfUsage = UTF8String(GetUsageData());
  496. CheckForUpdatesHTTP->Stream->Write(UtfUsage.c_str(), UtfUsage.Length());
  497. CheckForUpdatesHTTP->Post();
  498. }
  499. else
  500. {
  501. CheckForUpdatesHTTP->Action();
  502. }
  503. // sanity check
  504. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  505. {
  506. Abort();
  507. }
  508. UTF8String UtfResponse;
  509. UtfResponse.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  510. CheckForUpdatesHTTP->Stream->Read(UtfResponse.c_str(), UtfResponse.Length());
  511. Response = UnicodeString(UtfResponse);
  512. }
  513. __finally
  514. {
  515. delete CheckForUpdatesHTTP;
  516. }
  517. bool Changed = !Updates.HaveResults;
  518. Updates.LastCheck = Now();
  519. Updates.HaveResults = true;
  520. TUpdatesData PrevResults = Updates.Results;
  521. Updates.Results.Reset();
  522. Updates.Results.ForVersion = CurrentCompoundVer;
  523. while (!Response.IsEmpty())
  524. {
  525. UnicodeString Line = ::CutToChar(Response, L'\n', false);
  526. UnicodeString Name = ::CutToChar(Line, L'=', false);
  527. if (AnsiSameText(Name, "Version"))
  528. {
  529. int MajorVer = StrToInt(::CutToChar(Line, L'.', false));
  530. int MinorVer = StrToInt(::CutToChar(Line, L'.', false));
  531. int Release = StrToInt(::CutToChar(Line, L'.', false));
  532. int Build = StrToInt(::CutToChar(Line, L'.', false));
  533. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  534. Changed |= (NewVersion != PrevResults.Version);
  535. if (NewVersion <= CurrentCompoundVer)
  536. {
  537. NewVersion = 0;
  538. }
  539. Updates.Results.Version = NewVersion;
  540. Complete = true;
  541. }
  542. else if (AnsiSameText(Name, L"Message"))
  543. {
  544. Changed |= (PrevResults.Message != Line);
  545. Updates.Results.Message = Line;
  546. }
  547. else if (AnsiSameText(Name, L"Critical"))
  548. {
  549. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  550. Changed |= (PrevResults.Critical != NewCritical);
  551. Updates.Results.Critical = NewCritical;
  552. }
  553. else if (AnsiSameText(Name, L"Release"))
  554. {
  555. Changed |= (PrevResults.Release != Line);
  556. Updates.Results.Release = Line;
  557. }
  558. else if (AnsiSameText(Name, L"Disabled"))
  559. {
  560. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  561. Changed |= (PrevResults.Disabled != NewDisabled);
  562. Updates.Results.Disabled = NewDisabled;
  563. Complete = true;
  564. }
  565. else if (AnsiSameText(Name, L"Url"))
  566. {
  567. Changed |= (PrevResults.Url != Line);
  568. Updates.Results.Url = Line;
  569. }
  570. else if (AnsiSameText(Name, L"UrlButton"))
  571. {
  572. Changed |= (PrevResults.UrlButton != Line);
  573. Updates.Results.UrlButton = Line;
  574. }
  575. }
  576. if (Changed)
  577. {
  578. Updates.ShownResults = false;
  579. }
  580. WinConfiguration->Updates = Updates;
  581. }
  582. catch(Exception & E)
  583. {
  584. throw ExtException(&E, LoadStr(CHECK_FOR_UPDATES_ERROR));
  585. }
  586. if (Complete)
  587. {
  588. Configuration->Usage->Reset();
  589. }
  590. else
  591. {
  592. throw Exception(LoadStr(CHECK_FOR_UPDATES_ERROR));
  593. }
  594. }
  595. //---------------------------------------------------------------------------
  596. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  597. TQueryType & Type, bool Force)
  598. {
  599. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  600. assert(Updates.HaveResults);
  601. if (Updates.HaveResults)
  602. {
  603. if (Updates.Results.Disabled)
  604. {
  605. if (Force)
  606. {
  607. Message = LoadStr(UPDATE_DISABLED)+L"%s";
  608. }
  609. }
  610. else
  611. {
  612. New = (Updates.Results.Version > 0);
  613. if (New)
  614. {
  615. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  616. if (!Updates.Results.Release.IsEmpty())
  617. {
  618. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  619. }
  620. Message = FMTLOAD(NEW_VERSION3, (Version, L"%s"));
  621. }
  622. else
  623. {
  624. Message = LoadStr(NO_NEW_VERSION) + L"%s";
  625. }
  626. }
  627. if (!Updates.Results.Message.IsEmpty())
  628. {
  629. Message = FORMAT(Message,
  630. (FMTLOAD(UPDATE_MESSAGE,
  631. (ReplaceStr(Updates.Results.Message, L"|", L"\n")))));
  632. }
  633. else
  634. {
  635. Message = FORMAT(Message, (L""));
  636. }
  637. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  638. }
  639. else
  640. {
  641. New = false;
  642. }
  643. }
  644. //---------------------------------------------------------------------------
  645. void __fastcall CheckForUpdates(bool CachedResults)
  646. {
  647. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  648. Busy(true);
  649. try
  650. {
  651. if (ActiveForm)
  652. {
  653. assert(ActiveForm->Enabled);
  654. ActiveForm->Enabled = false;
  655. }
  656. bool Again = false;
  657. do
  658. {
  659. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  660. bool Cached = !Again && Updates.HaveResults &&
  661. (double(Updates.Period) > 0) &&
  662. (Updates.Results.ForVersion == Configuration->CompoundVersion) &&
  663. CachedResults;
  664. if (!Cached)
  665. {
  666. QueryUpdates();
  667. // reread new data
  668. Updates = WinConfiguration->Updates;
  669. }
  670. Again = false;
  671. if (!Updates.ShownResults)
  672. {
  673. Updates.ShownResults = true;
  674. WinConfiguration->Updates = Updates;
  675. }
  676. assert(Updates.HaveResults);
  677. UnicodeString Message;
  678. bool New;
  679. TQueryType Type;
  680. GetUpdatesMessage(Message, New, Type, true);
  681. if (Updates.HaveResults)
  682. {
  683. Message += L"\n\n" +
  684. FMTLOAD(UPDATE_LAST,
  685. (FormatDateTime("ddddd", Updates.LastCheck)));
  686. if (double(Updates.Period) > 0)
  687. {
  688. Message += L"\n" +
  689. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  690. }
  691. }
  692. // add FLAGMASK(Cached, qaRetry) to enable "check again" button
  693. // for cached results
  694. int Answers = qaOK |
  695. FLAGMASK(New, qaCancel | qaAll) |
  696. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  697. TQueryButtonAlias Aliases[4];
  698. Aliases[0].Button = qaRetry;
  699. Aliases[0].Alias = LoadStr(CHECK_AGAIN_BUTTON);
  700. Aliases[1].Button = qaYes;
  701. if (Updates.Results.UrlButton.IsEmpty())
  702. {
  703. Aliases[1].Alias = LoadStr(UPDATE_URL_BUTTON);
  704. }
  705. else
  706. {
  707. Aliases[1].Alias = Updates.Results.UrlButton;
  708. }
  709. Aliases[2].Button = qaAll;
  710. Aliases[2].Alias = LoadStr(WHATS_NEW_BUTTON);
  711. Aliases[3].Button = qaOK;
  712. Aliases[3].Alias = LoadStr(DOWNLOAD_BUTTON);
  713. TMessageParams Params;
  714. Params.Aliases = Aliases;
  715. // alias "ok" button to "download" only if we have new version
  716. Params.AliasesCount = (New ? 4 : 3);
  717. unsigned int Answer =
  718. MessageDialog(Message, Type,
  719. Answers, HELP_UPDATES, &Params);
  720. switch (Answer)
  721. {
  722. case qaOK:
  723. if (New)
  724. {
  725. OpenBrowser(LoadStr(DOWNLOAD_URL));
  726. }
  727. break;
  728. case qaYes:
  729. OpenBrowser(Updates.Results.Url);
  730. break;
  731. case qaAll:
  732. OpenBrowser(LoadStr(HISTORY_URL));
  733. break;
  734. case qaRetry:
  735. Again = true;
  736. break;
  737. }
  738. }
  739. while (Again);
  740. }
  741. __finally
  742. {
  743. if (ActiveForm)
  744. {
  745. ActiveForm->Enabled = true;
  746. }
  747. Busy(false);
  748. }
  749. }
  750. //---------------------------------------------------------------------------
  751. class TUpdateThread : public TCompThread
  752. {
  753. public:
  754. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  755. protected:
  756. virtual void __fastcall Execute();
  757. TThreadMethod FOnUpdatesChecked;
  758. };
  759. //---------------------------------------------------------------------------
  760. TUpdateThread * UpdateThread = NULL;
  761. //---------------------------------------------------------------------------
  762. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  763. TCompThread(false),
  764. FOnUpdatesChecked(OnUpdatesChecked)
  765. {
  766. }
  767. //---------------------------------------------------------------------------
  768. void __fastcall TUpdateThread::Execute()
  769. {
  770. try
  771. {
  772. QueryUpdates();
  773. if (FOnUpdatesChecked != NULL)
  774. {
  775. Synchronize(FOnUpdatesChecked);
  776. }
  777. }
  778. catch(...)
  779. {
  780. // ignore errors
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  785. {
  786. assert(UpdateThread == NULL);
  787. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  788. }
  789. //---------------------------------------------------------------------------
  790. void __fastcall StopUpdateThread()
  791. {
  792. if (UpdateThread != NULL)
  793. {
  794. SAFE_DESTROY(UpdateThread);
  795. }
  796. }
  797. //---------------------------------------------------------------------------
  798. void __fastcall SetupInitialize()
  799. {
  800. WinConfiguration->UpdateJumpList();
  801. }
  802. //---------------------------------------------------------------------------
  803. static bool __fastcall AddJumpListCategory(TStrings * Names,
  804. UnicodeString AdditionalParams, TStringList * Removed,
  805. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  806. int IconIndex)
  807. {
  808. bool Result = false;
  809. IObjectCollection * Collection = NULL;
  810. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  811. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  812. {
  813. try
  814. {
  815. int Count = 0;
  816. for (int Index = 0; Index < Names->Count; Index++)
  817. {
  818. IShellLink * Link =
  819. CreateDesktopSessionShortCut(
  820. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  821. wchar_t Desc[2048];
  822. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  823. {
  824. if (Removed->IndexOf(Desc) < 0)
  825. {
  826. try
  827. {
  828. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  829. Count++;
  830. }
  831. __finally
  832. {
  833. Link->Release();
  834. }
  835. }
  836. else
  837. {
  838. Names->Delete(Index);
  839. Index--;
  840. }
  841. }
  842. }
  843. if (Count > 0)
  844. {
  845. IObjectArray * Array;
  846. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  847. {
  848. try
  849. {
  850. Result = SUCCEEDED(
  851. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  852. }
  853. __finally
  854. {
  855. Array->Release();
  856. }
  857. }
  858. }
  859. }
  860. __finally
  861. {
  862. Collection->Release();
  863. }
  864. }
  865. return Result;
  866. }
  867. //---------------------------------------------------------------------------
  868. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  869. {
  870. ICustomDestinationList * DestinationList = NULL;
  871. IObjectArray * RemovedArray = NULL;
  872. TStringList * Removed = NULL;
  873. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  874. try
  875. {
  876. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  877. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  878. {
  879. unsigned int MinSlots;
  880. if (SUCCEEDED(DestinationList->BeginList(&MinSlots, IID_IObjectArray, (void**)&RemovedArray)) &&
  881. (RemovedArray != NULL))
  882. {
  883. Removed = new TStringList();
  884. unsigned int RemovedCount;
  885. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  886. {
  887. RemovedCount = 0;
  888. }
  889. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  890. {
  891. IShellLink * Link;
  892. wchar_t Desc[2048];
  893. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  894. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  895. {
  896. Removed->Add(Desc);
  897. }
  898. }
  899. AddJumpListCategory(
  900. WorkspaceNames, L"", Removed, DestinationList,
  901. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  902. AddJumpListCategory(
  903. SessionNames, L"/UploadIfAny", Removed, DestinationList,
  904. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  905. if (DestinationList != NULL)
  906. {
  907. DestinationList->CommitList();
  908. }
  909. }
  910. }
  911. }
  912. __finally
  913. {
  914. SetErrorMode(OldErrMode);
  915. if (RemovedArray != NULL)
  916. {
  917. RemovedArray->Release();
  918. }
  919. if (DestinationList != NULL)
  920. {
  921. DestinationList->Release();
  922. }
  923. delete Removed;
  924. }
  925. }
  926. //---------------------------------------------------------------------------
  927. bool __fastcall AnyOtherInstanceOfSelf()
  928. {
  929. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  930. bool Result = false;
  931. try
  932. {
  933. unsigned int Process = GetCurrentProcessId();
  934. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  935. PROCESSENTRY32 ProcessEntry;
  936. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  937. if (Process32First(Snapshot, &ProcessEntry))
  938. {
  939. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  940. {
  941. // we should check if the process is running in the same session,
  942. // but for that we probably need some special priviledges
  943. if ((Process != ProcessEntry.th32ProcessID) &&
  944. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  945. {
  946. Result = true;
  947. }
  948. }
  949. }
  950. }
  951. __finally
  952. {
  953. CloseHandle(Snapshot);
  954. }
  955. return Result;
  956. }