Setup.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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 <TextsCore.h>
  16. #include <HelpWin.h>
  17. #include <Http.h>
  18. #include <CompThread.hpp>
  19. #include <FileInfo.h>
  20. #include "WinConfiguration.h"
  21. #include "WinInterface.h"
  22. #include "Tools.h"
  23. #include "Setup.h"
  24. #include <StrUtils.hpp>
  25. #include "ProgParams.h"
  26. #include <Consts.hpp>
  27. #include <GUITools.h>
  28. #include <PuttyTools.h>
  29. #include <VCLCommon.h>
  30. #include <WebBrowserEx.hpp>
  31. #include <DateUtils.hpp>
  32. //---------------------------------------------------------------------------
  33. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  34. _T("Session Manager\\Environment")
  35. // when the PATH registry key is over aprox 2048 characters,
  36. // PATH as well as WINDIR variables are actually not set, breaking the system
  37. #define MAX_PATH_LEN 2000
  38. /* Command line options. */
  39. UnicodeString LastPathError;
  40. //---------------------------------------------------------------------------
  41. // Display the error "err_msg".
  42. void err_out(LPCTSTR err_msg)
  43. {
  44. LastPathError = err_msg;
  45. }
  46. //---------------------------------------------------------------------------
  47. // Display "base_err_msg" followed by the description of the system error
  48. // identified by "sys_err".
  49. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  50. {
  51. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  52. }
  53. //---------------------------------------------------------------------------
  54. // Works as "strcmp" but the comparison is not case sensitive.
  55. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  56. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  57. if (*str1 == L'\0')
  58. return 0;
  59. return tolower(*str1) - tolower(*str2);
  60. }
  61. //---------------------------------------------------------------------------
  62. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  63. // not present). The returned value must be freed with "free".
  64. LPTSTR unquote(LPCTSTR str){
  65. int last_pos;
  66. LPTSTR ret;
  67. size_t new_len;
  68. last_pos = _tcslen(str) - 1;
  69. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  70. new_len= (_tcslen(str) - 1);
  71. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  72. lstrcpyn(ret, &str[1], new_len);
  73. }
  74. else
  75. ret = _tcsdup(str);
  76. return ret;
  77. }
  78. //---------------------------------------------------------------------------
  79. // Find "what" in the ";" separated string "str" and returns a pointer to
  80. // the first letter of "what" in the string. If "next" is not "NULL" it
  81. // points to the first letter after "what" (excluding the trailing ";").
  82. // If "what" isn't find the functions returns "NULL".
  83. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  84. LPTSTR tok_buff;
  85. LPTSTR curr_tok;
  86. LPTSTR curr_tok_dup;
  87. BOOL path_eq;
  88. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  89. int pos = -1;
  90. LPTSTR ret;
  91. tok_buff = _tcsdup(str);
  92. curr_tok = _tcstok(tok_buff, _T(";"));
  93. while (pos == -1 && curr_tok){
  94. curr_tok_dup = unquote(curr_tok);
  95. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  96. GetShortPathName(curr_tok_dup, sh_path2,
  97. LENOF(sh_path2)) &&
  98. (tcharicmp(sh_path1, sh_path2) == 0);
  99. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  100. pos = curr_tok - tok_buff;
  101. }
  102. free(curr_tok_dup);
  103. curr_tok = _tcstok(NULL, _T(";"));
  104. if (pos != -1 && next){
  105. if (curr_tok)
  106. *next = str + (curr_tok - tok_buff);
  107. else
  108. *next = str + _tcslen(str);
  109. }
  110. }
  111. free(tok_buff);
  112. if (pos != -1)
  113. ret = str + pos;
  114. else
  115. ret = NULL;
  116. return ret;
  117. }
  118. //---------------------------------------------------------------------------
  119. void path_reg_propagate()
  120. {
  121. DWORD send_message_result;
  122. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  123. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  124. 5000, &send_message_result);
  125. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  126. {
  127. err_out_sys(_T("Cannot propagate the new enviroment to ")
  128. _T("other processes. The new value will be ")
  129. _T("avaible after a reboot."), GetLastError());
  130. SimpleErrorDialog(LastPathError);
  131. LastPathError = L"";
  132. }
  133. }
  134. //---------------------------------------------------------------------------
  135. // Add "path" to the registry. Return "TRUE" if the path has been added or
  136. // was already in the registry, "FALSE" otherwise.
  137. BOOL add_path_reg(LPCTSTR path){
  138. HKEY key;
  139. LONG ret;
  140. DWORD data_size;
  141. LPTSTR reg_str;
  142. BOOL func_ret = TRUE;
  143. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  144. KEY_WRITE | KEY_READ, &key);
  145. if (ret != ERROR_SUCCESS){
  146. err_out_sys(_T("Cannot open registry."), ret);
  147. return FALSE;
  148. }
  149. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  150. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  151. includes '\0'. */
  152. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  153. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  154. &data_size);
  155. if (ret != ERROR_SUCCESS){
  156. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  157. func_ret = FALSE;
  158. }
  159. else{
  160. if (!find_reg_str(reg_str, path, NULL)){
  161. _tcscat(reg_str, _T(";"));
  162. _tcscat(reg_str, path);
  163. size_t len = _tcslen(reg_str);
  164. if (len >= MAX_PATH_LEN)
  165. {
  166. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  167. func_ret = FALSE;
  168. }
  169. else
  170. {
  171. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  172. (LPBYTE)reg_str,
  173. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  174. if (ret != ERROR_SUCCESS){
  175. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  176. func_ret = FALSE;
  177. }
  178. /* Is this needed to make the new key avaible? */
  179. RegFlushKey(key);
  180. SetLastError(0);
  181. path_reg_propagate();
  182. }
  183. }
  184. }
  185. RegCloseKey(key);
  186. free(reg_str);
  187. return func_ret;
  188. }
  189. //---------------------------------------------------------------------------
  190. // Removes "path" from the registry. Return "TRUE" if the path has been
  191. // removed or it wasn't in the registry, "FALSE" otherwise.
  192. BOOL remove_path_reg(LPCTSTR path){
  193. HKEY key;
  194. LONG ret;
  195. DWORD data_size;
  196. LPTSTR reg_str;
  197. LPTSTR reg_str2;
  198. BOOL func_ret = TRUE;
  199. LPTSTR next;
  200. LPTSTR del_part;
  201. int last_pos;
  202. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  203. KEY_WRITE | KEY_READ, &key);
  204. if (ret != ERROR_SUCCESS){
  205. err_out_sys(_T("Cannot open registry."), ret);
  206. return FALSE;
  207. }
  208. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  209. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  210. includes '\0'. */
  211. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  212. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  213. (LPBYTE)reg_str, &data_size);
  214. if (ret != ERROR_SUCCESS){
  215. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  216. func_ret = FALSE;
  217. }
  218. else{
  219. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  220. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  221. *del_part = '\0';
  222. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  223. last_pos = _tcslen(reg_str2) - 1;
  224. if (last_pos != -1 && reg_str2[last_pos] == ';')
  225. reg_str2[last_pos] = '\0';
  226. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  227. (LPBYTE)reg_str2,
  228. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  229. if (ret != ERROR_SUCCESS){
  230. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  231. func_ret = FALSE;
  232. }
  233. free(reg_str2);
  234. /* Is this needed to make the new key avaible? */
  235. RegFlushKey(key);
  236. SetLastError(0);
  237. path_reg_propagate();
  238. }
  239. }
  240. RegCloseKey(key);
  241. free(reg_str);
  242. return func_ret;
  243. }
  244. //---------------------------------------------------------------------------
  245. //---------------------------------------------------------------------------
  246. void __fastcall AddSearchPath(const UnicodeString Path)
  247. {
  248. if (!add_path_reg(Path.c_str()))
  249. {
  250. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  251. }
  252. }
  253. //---------------------------------------------------------------------------
  254. void __fastcall RemoveSearchPath(const UnicodeString Path)
  255. {
  256. if (!remove_path_reg(Path.c_str()))
  257. {
  258. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  259. }
  260. }
  261. //---------------------------------------------------------------------------
  262. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  263. //---------------------------------------------------------------------------
  264. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  265. {
  266. if (Registry->OpenKey(Key, false))
  267. {
  268. std::unique_ptr<TStrings> List(new TStringList());
  269. Registry->GetValueNames(List.get());
  270. bool CanDelete = true;
  271. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  272. {
  273. UnicodeString ValueName = List->Strings[Index];
  274. if (!AllowRootValues)
  275. {
  276. CanDelete = false;
  277. }
  278. if ((ValueName != L"") &&
  279. (ValueName != L"URL Protocol") &&
  280. (ValueName != L"EditFlags") &&
  281. (ValueName != L"BrowserFlags"))
  282. {
  283. CanDelete = false;
  284. }
  285. }
  286. List->Clear();
  287. Registry->GetKeyNames(List.get());
  288. Registry->CloseKey();
  289. if (CanDelete)
  290. {
  291. for (int Index = 0; Index < List->Count; Index++)
  292. {
  293. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  294. }
  295. // will fail, if not all subkeys got removed
  296. Registry->DeleteKey(Key);
  297. }
  298. }
  299. }
  300. //---------------------------------------------------------------------------
  301. static void __fastcall RegisterProtocol(TRegistry * Registry,
  302. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  303. {
  304. if (Description.IsEmpty())
  305. {
  306. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  307. }
  308. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  309. if (Force || !Registry->KeyExists(ProtocolKey))
  310. {
  311. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  312. {
  313. Registry->WriteString(L"", Description);
  314. Registry->WriteString(L"URL Protocol", L"");
  315. Registry->WriteInteger(L"EditFlags", 0x02);
  316. Registry->WriteInteger(L"BrowserFlags", 0x08);
  317. if (Registry->OpenKey(L"DefaultIcon", true))
  318. {
  319. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  320. Registry->CloseKey();
  321. }
  322. else
  323. {
  324. Abort();
  325. }
  326. }
  327. else
  328. {
  329. Abort();
  330. }
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  335. const UnicodeString & Protocol)
  336. {
  337. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  338. }
  339. //---------------------------------------------------------------------------
  340. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  341. {
  342. std::unique_ptr<TRegistry> Registry(new TRegistry());
  343. Registry->Access = KEY_WRITE | KEY_READ;
  344. Registry->RootKey = RootKey;
  345. return Registry.release();
  346. }
  347. //---------------------------------------------------------------------------
  348. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  349. const UnicodeString & Protocol, UnicodeString Description = L"")
  350. {
  351. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  352. RegisterProtocol(Registry.get(), Protocol, Description, true);
  353. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  354. Registry->OpenKey(L"shell", true) &&
  355. Registry->OpenKey(L"open", true) &&
  356. Registry->OpenKey(L"command", true))
  357. {
  358. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  359. Registry->CloseKey();
  360. }
  361. else
  362. {
  363. Abort();
  364. }
  365. }
  366. //---------------------------------------------------------------------------
  367. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  368. {
  369. try
  370. {
  371. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  372. // get rid of any HKCU registraction that would overrite the HKLM one
  373. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  374. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  375. {
  376. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  377. }
  378. }
  379. catch (Exception & E)
  380. {
  381. try
  382. {
  383. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  384. }
  385. catch(Exception & E)
  386. {
  387. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  388. }
  389. }
  390. }
  391. //---------------------------------------------------------------------------
  392. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  393. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  394. {
  395. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  396. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  397. if (Registry->OpenKey(DefaultIconKey, false))
  398. {
  399. UnicodeString Value = Registry->ReadString(L"");
  400. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  401. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  402. {
  403. Registry->DeleteValue(L"");
  404. }
  405. Registry->CloseKey();
  406. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  407. }
  408. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  409. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  410. {
  411. UnicodeString Value = Registry->ReadString(L"");
  412. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  413. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  414. {
  415. Registry->DeleteValue(L"");
  416. }
  417. Registry->CloseKey();
  418. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  419. }
  420. if (UnregisterProtocol)
  421. {
  422. ::UnregisterProtocol(Registry.get(), Protocol);
  423. }
  424. }
  425. //---------------------------------------------------------------------------
  426. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  427. {
  428. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  429. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  430. }
  431. //---------------------------------------------------------------------------
  432. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  433. {
  434. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  435. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  436. }
  437. //---------------------------------------------------------------------------
  438. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  439. {
  440. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  441. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  442. }
  443. //---------------------------------------------------------------------------
  444. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  445. //---------------------------------------------------------------------------
  446. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  447. {
  448. // Register protocol, if it does not exist yet.
  449. // Prior to Windows 8, we need to register ourselves as legacy handler to
  450. // become the default handler. On Windows 8, it's automatic as long as no other
  451. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  452. RegisterAsUrlHandler(RootKey, Protocol);
  453. // see http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
  454. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  455. // create capabilities record
  456. // this has to be a separate branch from WinSCP one, as by its presence we
  457. // enforce registry storage usage, and the capabilities branch may exist
  458. // even if we are using INI file
  459. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  460. if (!Registry->OpenKey(CapabilitiesKey, true))
  461. {
  462. Abort();
  463. }
  464. UnicodeString Description = LoadStr(REGISTERED_APP_DESC2);
  465. Registry->WriteString(L"ApplicationDescription", Description);
  466. if (!Registry->OpenKey(L"UrlAssociations", true))
  467. {
  468. Abort();
  469. }
  470. Registry->WriteString(Protocol, GenericUrlHandler);
  471. Registry->CloseKey();
  472. // register application
  473. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  474. {
  475. Abort();
  476. }
  477. Registry->WriteString(AppNameString(), CapabilitiesKey);
  478. Registry->CloseKey();
  479. }
  480. //---------------------------------------------------------------------------
  481. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  482. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  483. {
  484. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  485. // unregister the protocol
  486. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  487. // remove capabilities record
  488. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  489. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  490. if (Registry->OpenKey(UrlAssociationsKey, false))
  491. {
  492. Registry->DeleteValue(Protocol);
  493. Registry->CloseKey();
  494. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  495. }
  496. if (Registry->OpenKey(CapabilitiesKey, false))
  497. {
  498. if (!Registry->HasSubKeys())
  499. {
  500. Registry->DeleteValue(L"ApplicationDescription");
  501. }
  502. Registry->CloseKey();
  503. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  504. }
  505. if (!Registry->KeyExists(CapabilitiesKey))
  506. {
  507. // unregister application
  508. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  509. {
  510. Registry->DeleteValue(AppNameString());
  511. Registry->CloseKey();
  512. }
  513. }
  514. }
  515. //---------------------------------------------------------------------------
  516. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  517. {
  518. // register URL handler, if it does not exist yet
  519. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  520. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  521. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  522. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  523. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  524. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  525. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  526. // deliberately not including WebDAV/http,
  527. // it's unlikely that anyone would like to change http handler
  528. // to non-browser application
  529. }
  530. //---------------------------------------------------------------------------
  531. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  532. {
  533. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  534. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  535. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  536. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  537. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  538. UnregisterProtocolForDefaultPrograms(RootKey, SshProtocol, ForceHandlerUnregistration);
  539. // we should not really need the "force" flag here, but why not
  540. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  541. }
  542. //---------------------------------------------------------------------------
  543. static void __fastcall RegisterForDefaultPrograms()
  544. {
  545. try
  546. {
  547. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  548. // make sure we unregister any legacy protocol handler for CU,
  549. // this is needed for Windows Vista+7
  550. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  551. }
  552. catch (Exception & E)
  553. {
  554. try
  555. {
  556. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  557. }
  558. catch (Exception & E)
  559. {
  560. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  561. }
  562. }
  563. }
  564. //---------------------------------------------------------------------------
  565. static void __fastcall NotifyChangedAssociations()
  566. {
  567. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  568. }
  569. //---------------------------------------------------------------------------
  570. void __fastcall RegisterForDefaultProtocols()
  571. {
  572. if (IsWinVista())
  573. {
  574. RegisterForDefaultPrograms();
  575. }
  576. else
  577. {
  578. RegisterAsNonBrowserUrlHandler(UnicodeString());
  579. }
  580. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  581. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  582. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  583. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  584. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase());
  585. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase());
  586. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  587. NotifyChangedAssociations();
  588. }
  589. //---------------------------------------------------------------------------
  590. void __fastcall UnregisterForProtocols()
  591. {
  592. UnregisterAsUrlHandlers(UnicodeString(), false);
  593. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  594. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  595. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  596. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  597. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase(), true);
  598. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase(), true);
  599. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  600. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  601. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  602. NotifyChangedAssociations();
  603. }
  604. //---------------------------------------------------------------------------
  605. void __fastcall LaunchAdvancedAssociationUI()
  606. {
  607. DebugAssert(IsWinVista());
  608. RegisterForDefaultPrograms();
  609. NotifyChangedAssociations();
  610. // sleep recommended by http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  611. Sleep(1000);
  612. if (IsWin10())
  613. {
  614. ExecuteShell(L"control.exe", L"/name Microsoft.DefaultPrograms");
  615. }
  616. else
  617. {
  618. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  619. HRESULT Result =
  620. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  621. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  622. if (SUCCEEDED(Result))
  623. {
  624. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  625. AppAssocRegUI->Release();
  626. }
  627. }
  628. }
  629. //---------------------------------------------------------------------------
  630. void __fastcall TemporaryDirectoryCleanup()
  631. {
  632. bool Continue = true;
  633. TStrings * Folders = NULL;
  634. try
  635. {
  636. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  637. {
  638. Folders = WinConfiguration->FindTemporaryFolders();
  639. Continue = (Folders != NULL);
  640. if (Continue)
  641. {
  642. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  643. TQueryButtonAlias Aliases[1];
  644. Aliases[0].Button = qaRetry;
  645. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  646. TMessageParams Params(mpNeverAskAgainCheck);
  647. Params.Aliases = Aliases;
  648. Params.AliasesCount = LENOF(Aliases);
  649. unsigned int Answer = MoreMessageDialog(
  650. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  651. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  652. if (Answer == qaNeverAskAgain)
  653. {
  654. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  655. Answer = qaYes;
  656. }
  657. else if (Answer == qaRetry)
  658. {
  659. for (int Index = 0; Index < Folders->Count; Index++)
  660. {
  661. ShellExecute(Application->Handle, NULL,
  662. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  663. }
  664. }
  665. Continue = (Answer == qaYes);
  666. }
  667. }
  668. if (Continue)
  669. {
  670. try
  671. {
  672. WinConfiguration->CleanupTemporaryFolders(Folders);
  673. }
  674. catch (Exception &E)
  675. {
  676. ShowExtendedException(&E);
  677. }
  678. }
  679. }
  680. __finally
  681. {
  682. delete Folders;
  683. }
  684. }
  685. //-------------------------------------------- -------------------------------
  686. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  687. {
  688. int MajorVer = Version / (10000*100*100);
  689. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  690. int Release = (Version % (10000*100)) / (10000);
  691. UnicodeString Result;
  692. if (Release > 0)
  693. {
  694. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  695. }
  696. else
  697. {
  698. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  699. }
  700. return Result;
  701. }
  702. //---------------------------------------------------------------------------
  703. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  704. {
  705. int CurrentCompoundVer = Configuration->CompoundVersion;
  706. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  707. // Beware that these parameters may get truncated if URL is too long,
  708. // such as with ERROR_REPORT_URL2
  709. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  710. return AppendUrlParams(URL, Params);
  711. }
  712. //---------------------------------------------------------------------------
  713. UnicodeString __fastcall GetUsageData()
  714. {
  715. return Configuration->Usage->Serialize();
  716. }
  717. //---------------------------------------------------------------------------
  718. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  719. {
  720. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  721. UnicodeString CurrentVersionStr =
  722. FORMAT(L"%d.%d.%d.%d",
  723. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  724. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  725. UnicodeString Params =
  726. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  727. (CurrentVersionStr,
  728. GUIConfiguration->LocaleHex,
  729. int(IsInstalled())));
  730. if (Configuration->IsUnofficial)
  731. {
  732. Params += L"&unofficial=1";
  733. }
  734. return AppendUrlParams(URL, Params);
  735. }
  736. //---------------------------------------------------------------------------
  737. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  738. {
  739. bool Beta;
  740. if (WinConfiguration->IsBeta)
  741. {
  742. Beta = true;
  743. }
  744. else
  745. {
  746. switch (WinConfiguration->Updates.BetaVersions)
  747. {
  748. case asAuto:
  749. Beta = WinConfiguration->AnyBetaInVersionHistory;
  750. break;
  751. case asOn:
  752. Beta = true;
  753. break;
  754. default:
  755. Beta = false;
  756. break;
  757. }
  758. }
  759. if (Beta || Force)
  760. {
  761. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  762. }
  763. return URL;
  764. }
  765. //---------------------------------------------------------------------------
  766. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  767. {
  768. std::unique_ptr<THttp> Http(new THttp());
  769. UnicodeString ProxyHost;
  770. int ProxyPort = 0;
  771. switch (Updates.ConnectionType)
  772. {
  773. case ctAuto:
  774. if (AutodetectProxy(ProxyHost, ProxyPort))
  775. {
  776. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  777. }
  778. break;
  779. case ctProxy:
  780. ProxyHost = Updates.ProxyHost;
  781. ProxyPort = Updates.ProxyPort;
  782. Configuration->Usage->Inc(L"UpdateProxyManual");
  783. break;
  784. }
  785. Http->ProxyHost = ProxyHost;
  786. Http->ProxyPort = ProxyPort;
  787. return Http.release();
  788. }
  789. //---------------------------------------------------------------------------
  790. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  791. {
  792. bool Complete = false;
  793. UnicodeString Response;
  794. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  795. try
  796. {
  797. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  798. URL = WantBetaUrl(URL, false);
  799. URL += L"&dotnet=" + Updates.DotNetVersion;
  800. URL += L"&console=" + Updates.ConsoleVersion;
  801. UnicodeString LocaleVersion = WinConfiguration->LocaleVersion();
  802. if (!LocaleVersion.IsEmpty())
  803. {
  804. URL += L"&localever=" + LocaleVersion;
  805. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  806. }
  807. if (!Updates.AuthenticationEmail.IsEmpty())
  808. {
  809. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  810. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  811. }
  812. CheckForUpdatesHTTP->URL = URL;
  813. // sanity check
  814. CheckForUpdatesHTTP->ResponseLimit = 102400;
  815. if (CollectUsage)
  816. {
  817. UnicodeString Usage = GetUsageData();
  818. CheckForUpdatesHTTP->Post(Usage);
  819. }
  820. else
  821. {
  822. CheckForUpdatesHTTP->Get();
  823. }
  824. Response = CheckForUpdatesHTTP->Response;
  825. }
  826. __finally
  827. {
  828. delete CheckForUpdatesHTTP;
  829. }
  830. int CurrentCompoundVer = Configuration->CompoundVersion;
  831. bool Changed = !Updates.HaveResults;
  832. Updates.LastCheck = Now();
  833. Updates.HaveResults = true;
  834. TUpdatesData PrevResults = Updates.Results;
  835. Updates.Results.Reset();
  836. Updates.Results.ForVersion = CurrentCompoundVer;
  837. while (!Response.IsEmpty())
  838. {
  839. UnicodeString Line = CutToChar(Response, L'\n', false);
  840. UnicodeString Name = CutToChar(Line, L'=', false);
  841. if (AnsiSameText(Name, "Version"))
  842. {
  843. int MajorVer = StrToInt(CutToChar(Line, L'.', false));
  844. int MinorVer = StrToInt(CutToChar(Line, L'.', false));
  845. int Release = StrToInt(CutToChar(Line, L'.', false));
  846. int Build = StrToInt(CutToChar(Line, L'.', false));
  847. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  848. Changed |= (NewVersion != PrevResults.Version);
  849. if (NewVersion <= CurrentCompoundVer)
  850. {
  851. NewVersion = 0;
  852. }
  853. Updates.Results.Version = NewVersion;
  854. Complete = true;
  855. }
  856. else if (AnsiSameText(Name, L"Message"))
  857. {
  858. Changed |= (PrevResults.Message != Line);
  859. Updates.Results.Message = Line;
  860. }
  861. else if (AnsiSameText(Name, L"Critical"))
  862. {
  863. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  864. Changed |= (PrevResults.Critical != NewCritical);
  865. Updates.Results.Critical = NewCritical;
  866. }
  867. else if (AnsiSameText(Name, L"Release"))
  868. {
  869. Changed |= (PrevResults.Release != Line);
  870. Updates.Results.Release = Line;
  871. }
  872. else if (AnsiSameText(Name, L"Disabled"))
  873. {
  874. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  875. Changed |= (PrevResults.Disabled != NewDisabled);
  876. Updates.Results.Disabled = NewDisabled;
  877. Complete = true;
  878. }
  879. else if (AnsiSameText(Name, L"Url"))
  880. {
  881. Changed |= (PrevResults.Url != Line);
  882. Updates.Results.Url = Line;
  883. }
  884. else if (AnsiSameText(Name, L"UrlButton"))
  885. {
  886. Changed |= (PrevResults.UrlButton != Line);
  887. Updates.Results.UrlButton = Line;
  888. }
  889. else if (AnsiSameText(Name, L"NewsUrl"))
  890. {
  891. Changed |= (PrevResults.NewsUrl != Line);
  892. Updates.Results.NewsUrl = Line;
  893. }
  894. else if (AnsiSameText(Name, L"NewsSize"))
  895. {
  896. TSize NewsSize;
  897. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  898. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  899. Changed |= (PrevResults.NewsSize != NewsSize);
  900. Updates.Results.NewsSize = NewsSize;
  901. }
  902. else if (AnsiSameText(Name, L"DownloadUrl"))
  903. {
  904. Changed |= (PrevResults.DownloadUrl != Line);
  905. Updates.Results.DownloadUrl = Line;
  906. }
  907. else if (AnsiSameText(Name, L"DownloadSize"))
  908. {
  909. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  910. }
  911. else if (AnsiSameText(Name, L"DownloadSha256"))
  912. {
  913. Updates.Results.DownloadSha256 = Line;
  914. }
  915. else if (AnsiSameText(Name, L"AuthenticationError"))
  916. {
  917. Changed |= (PrevResults.AuthenticationError != Line);
  918. Updates.Results.AuthenticationError = Line;
  919. }
  920. else if (AnsiSameText(Name, L"OpenGettingStarted"))
  921. {
  922. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  923. }
  924. else if (AnsiSameText(Name, L"DownloadingUrl"))
  925. {
  926. Updates.Results.DownloadingUrl = Line;
  927. }
  928. else if (AnsiSameText(Name, L"TipsSize"))
  929. {
  930. TSize TipsSize;
  931. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  932. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  933. Updates.Results.TipsSize = TipsSize;
  934. }
  935. else if (AnsiSameText(Name, L"TipsUrl"))
  936. {
  937. Updates.Results.TipsUrl = Line;
  938. }
  939. else if (AnsiSameText(Name, L"Tips"))
  940. {
  941. Updates.Results.Tips = Line;
  942. }
  943. else if (AnsiSameText(Name, L"TipsIntervalDays"))
  944. {
  945. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  946. if (TipsIntervalDays < 0)
  947. {
  948. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  949. }
  950. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  951. }
  952. else if (AnsiSameText(Name, L"TipsIntervalRuns"))
  953. {
  954. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  955. if (TipsIntervalRuns < 0)
  956. {
  957. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  958. }
  959. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  960. }
  961. }
  962. if (Changed)
  963. {
  964. Updates.ShownResults = false;
  965. }
  966. return Complete;
  967. }
  968. //---------------------------------------------------------------------------
  969. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  970. {
  971. return DoQueryUpdates(Updates, false);
  972. }
  973. //---------------------------------------------------------------------------
  974. static void __fastcall DoQueryUpdates(bool CollectUsage)
  975. {
  976. try
  977. {
  978. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  979. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  980. WinConfiguration->Updates = Updates;
  981. if (!Complete)
  982. {
  983. EXCEPTION;
  984. }
  985. Configuration->Usage->Reset();
  986. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  987. }
  988. catch(Exception & E)
  989. {
  990. Configuration->Usage->Inc(L"UpdateChecksFailed");
  991. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  992. }
  993. }
  994. //---------------------------------------------------------------------------
  995. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  996. {
  997. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  998. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  999. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1000. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  1001. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1002. Message = ReplaceStr(Message, L"|", L"\n");
  1003. return Message;
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1007. TQueryType & Type, bool Force)
  1008. {
  1009. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1010. DebugAssert(Updates.HaveResults);
  1011. if (Updates.HaveResults)
  1012. {
  1013. if (Updates.Results.Disabled)
  1014. {
  1015. New = false;
  1016. if (Force)
  1017. {
  1018. Message = LoadStr(UPDATE_DISABLED);
  1019. }
  1020. }
  1021. else
  1022. {
  1023. New = (Updates.Results.Version > 0);
  1024. if (New)
  1025. {
  1026. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1027. if (!Updates.Results.Release.IsEmpty())
  1028. {
  1029. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1030. }
  1031. Message = FMTLOAD(NEW_VERSION4, (Version));
  1032. }
  1033. else
  1034. {
  1035. Message = LoadStr(NO_NEW_VERSION);
  1036. }
  1037. }
  1038. if (!Message.IsEmpty())
  1039. {
  1040. Message = MainInstructions(Message);
  1041. }
  1042. if (!Updates.Results.Message.IsEmpty())
  1043. {
  1044. Message +=
  1045. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1046. }
  1047. if (!Updates.Results.AuthenticationError.IsEmpty())
  1048. {
  1049. Message +=
  1050. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1051. }
  1052. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1053. }
  1054. else
  1055. {
  1056. New = false;
  1057. }
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1061. {
  1062. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. void __fastcall EnableAutomaticUpdates()
  1066. {
  1067. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  1071. {
  1072. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1073. OpenBrowser(LoadStr(HISTORY_URL));
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1077. {
  1078. return static_cast<int>(Size / 1024);
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. class TUpdateDownloadThread : public TCompThread
  1082. {
  1083. public:
  1084. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1085. virtual __fastcall ~TUpdateDownloadThread();
  1086. void __fastcall CancelClicked(TObject * Sender);
  1087. bool __fastcall CancelDownload();
  1088. protected:
  1089. virtual void __fastcall Execute();
  1090. void __fastcall UpdateDownloaded();
  1091. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1092. void __fastcall UpdateProgress();
  1093. void __fastcall ShowException();
  1094. void __fastcall DownloadNotVerified();
  1095. void __fastcall CancelForm();
  1096. private:
  1097. TCustomForm * FForm;
  1098. TProgressBar * FProgressBar;
  1099. __int64 FDownloaded;
  1100. std::unique_ptr<Exception> FException;
  1101. std::unique_ptr<THttp> FHttp;
  1102. TUpdatesConfiguration FUpdates;
  1103. };
  1104. //---------------------------------------------------------------------------
  1105. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1106. TCompThread(true)
  1107. {
  1108. // cache, as the progress bar miht be destroyed already when
  1109. // we need the form at the end of Execute()
  1110. FForm = GetParentForm(ProgressBar);
  1111. FProgressBar = ProgressBar;
  1112. // cache to prevent concurrency
  1113. FUpdates = WinConfiguration->Updates;
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1117. {
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void __fastcall TUpdateDownloadThread::Execute()
  1121. {
  1122. try
  1123. {
  1124. bool Retried = false;
  1125. bool Retry;
  1126. do
  1127. {
  1128. Retry = false;
  1129. try
  1130. {
  1131. FDownloaded = 0;
  1132. FHttp.reset(CreateHttp(FUpdates));
  1133. FHttp->URL = FUpdates.Results.DownloadUrl;
  1134. FHttp->OnDownload = HttpDownload;
  1135. FHttp->Get();
  1136. }
  1137. catch (EAbort &)
  1138. {
  1139. throw;
  1140. }
  1141. catch (Exception & E)
  1142. {
  1143. // The original URL failed, try to get a fresh one and retry
  1144. if (!Retried)
  1145. {
  1146. try
  1147. {
  1148. // Check if new update data (URL particlarly) is available
  1149. if (QueryUpdates(FUpdates) &&
  1150. !FUpdates.Results.DownloadUrl.IsEmpty())
  1151. {
  1152. Retry = true;
  1153. Retried = true;
  1154. }
  1155. }
  1156. catch (...)
  1157. {
  1158. }
  1159. }
  1160. if (!Retry)
  1161. {
  1162. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1163. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1164. }
  1165. }
  1166. }
  1167. while (Retry);
  1168. Synchronize(UpdateDownloaded);
  1169. }
  1170. catch (EAbort &)
  1171. {
  1172. // noop
  1173. }
  1174. catch (Exception & E)
  1175. {
  1176. Configuration->Usage->Inc(L"UpdateFailures");
  1177. FException.reset(CloneException(&E));
  1178. Synchronize(ShowException);
  1179. }
  1180. Synchronize(CancelForm);
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. void __fastcall TUpdateDownloadThread::CancelForm()
  1184. {
  1185. FForm->ModalResult = mrCancel;
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1189. {
  1190. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1191. const char * Buffer = FHttp->ResponseRaw.c_str();
  1192. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1193. {
  1194. DownloadNotVerified();
  1195. }
  1196. UnicodeString Digest = Sha256(Buffer, Size);
  1197. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1198. {
  1199. DownloadNotVerified();
  1200. }
  1201. UnicodeString FileName = FUpdates.Results.DownloadUrl;
  1202. int P = FileName.Pos(L"?");
  1203. if (P > 0)
  1204. {
  1205. FileName.SetLength(P - 1);
  1206. }
  1207. P = FileName.LastDelimiter("/");
  1208. if (DebugAlwaysTrue(P > 0))
  1209. {
  1210. FileName.Delete(1, P);
  1211. }
  1212. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1213. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1214. UnicodeString SetupPath = SetupPathBase;
  1215. int Index = 0;
  1216. while (FileExists(SetupPath))
  1217. {
  1218. Index++;
  1219. SetupPath =
  1220. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1221. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1222. }
  1223. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1224. FileStream->Write(Buffer, Size);
  1225. FileStream.reset(NULL);
  1226. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1227. if (FUpdates.Results.OpenGettingStarted)
  1228. {
  1229. Params += L" /OpenGettingStarted";
  1230. }
  1231. if (!ExecuteShell(SetupPath, Params))
  1232. {
  1233. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (SetupPath)));
  1234. }
  1235. Configuration->Usage->Inc(L"UpdateRuns");
  1236. Application->Terminate();
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1240. {
  1241. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1245. {
  1246. FDownloaded = Size;
  1247. Synchronize(UpdateProgress);
  1248. // Do not waste bandwidth, if something goes wrong
  1249. if (FDownloaded > FUpdates.Results.DownloadSize)
  1250. {
  1251. DownloadNotVerified();
  1252. }
  1253. if (Terminated)
  1254. {
  1255. Cancel = true;
  1256. }
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1260. {
  1261. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. void __fastcall TUpdateDownloadThread::ShowException()
  1265. {
  1266. DebugAssert(FException.get() != NULL);
  1267. ShowExtendedException(FException.get());
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1271. {
  1272. bool Result = !Terminated;
  1273. if (Result)
  1274. {
  1275. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1276. Terminate();
  1277. }
  1278. return Result;
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1282. {
  1283. if (CancelDownload())
  1284. {
  1285. Terminate();
  1286. WaitFor();
  1287. }
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. //---------------------------------------------------------------------------
  1291. class TUpdateDownloadData : public TComponent
  1292. {
  1293. public:
  1294. TUpdateDownloadThread * Thread;
  1295. __fastcall TUpdateDownloadData() :
  1296. TComponent(NULL)
  1297. {
  1298. }
  1299. virtual __fastcall ~TUpdateDownloadData()
  1300. {
  1301. // will stop the thread
  1302. delete Thread;
  1303. }
  1304. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1305. {
  1306. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1307. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1308. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1309. }
  1310. };
  1311. //---------------------------------------------------------------------------
  1312. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1313. {
  1314. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1315. if (UpdateDownloadData->Thread->CancelDownload())
  1316. {
  1317. Action = caNone;
  1318. }
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender)
  1322. {
  1323. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1324. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1325. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1326. TPanel * Panel = CreateBlankPanel(Form);
  1327. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1328. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1329. ProgressBar->Top = 0;
  1330. ProgressBar->Left = 0;
  1331. ProgressBar->Width = Panel->Width;
  1332. ProgressBar->Parent = Panel;
  1333. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1334. Panel->Height = ProgressBar->Height;
  1335. InsertPanelToMessageDialog(Form, Panel);
  1336. Button->Enabled = false;
  1337. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1338. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1339. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1340. // The form becomes owner of the thread (via TUpdateDownloadData),
  1341. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1342. // But it gets done only after the form controls are gone, and the thread
  1343. // might try to access them meanwhile. So we stop the thread explicitly.
  1344. CancelButton->OnClick = Thread->CancelClicked;
  1345. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1346. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1347. Data->Thread = Thread;
  1348. Form->InsertComponent(Data);
  1349. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1350. if (!DownloadingUrl.IsEmpty())
  1351. {
  1352. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1353. }
  1354. DebugAssert(Form->OnClose == NULL);
  1355. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1356. Thread->Resume();
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1360. {
  1361. EnableAutomaticUpdates();
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1365. {
  1366. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1367. TPanel * Panel = CreateBlankPanel(Dialog);
  1368. TStaticText * StaticText = new TStaticText(Panel);
  1369. StaticText->Top = 0;
  1370. StaticText->Left = 0;
  1371. StaticText->AutoSize = true;
  1372. StaticText->Caption = LoadStr(UPDATES_DONATE_LINK);
  1373. StaticText->Parent = Panel;
  1374. StaticText->OnClick = MakeMethod<TNotifyEvent>(NULL, UpdatesDonateClick);
  1375. StaticText->TabStop = true;
  1376. LinkLabel(StaticText);
  1377. Panel->Height = StaticText->Height;
  1378. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1379. // (what should not happen)
  1380. InsertPanelToMessageDialog(Dialog, Panel);
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. bool __fastcall CheckForUpdates(bool CachedResults)
  1384. {
  1385. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1386. bool Result = false;
  1387. TOperationVisualizer Visualizer;
  1388. try
  1389. {
  1390. if (ActiveForm)
  1391. {
  1392. DebugAssert(ActiveForm->Enabled);
  1393. ActiveForm->Enabled = false;
  1394. }
  1395. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1396. bool Cached =
  1397. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1398. CachedResults;
  1399. if (!Cached)
  1400. {
  1401. DoQueryUpdates(WinConfiguration->CollectUsage);
  1402. // reread new data
  1403. Updates = WinConfiguration->Updates;
  1404. }
  1405. if (!Updates.ShownResults)
  1406. {
  1407. Updates.ShownResults = true;
  1408. WinConfiguration->Updates = Updates;
  1409. }
  1410. DebugAssert(Updates.HaveResults);
  1411. UnicodeString Message;
  1412. bool New;
  1413. TQueryType Type;
  1414. GetUpdatesMessage(Message, New, Type, true);
  1415. Configuration->Usage->Inc(L"UpdateDisplays");
  1416. if (New)
  1417. {
  1418. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1419. }
  1420. if (Updates.HaveResults &&
  1421. (double(Updates.Period) > 0) &&
  1422. // do not chow next check time, if we have new version info
  1423. !New)
  1424. {
  1425. Message += L"\n\n" +
  1426. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1427. }
  1428. int Answers = qaOK |
  1429. // show "what's new" button only when change list URL was not provided in results
  1430. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1431. FLAGMASK(New, qaCancel) |
  1432. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1433. TQueryButtonAlias Aliases[4];
  1434. Aliases[0].Button = qaYes;
  1435. if (Updates.Results.UrlButton.IsEmpty())
  1436. {
  1437. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1438. }
  1439. else
  1440. {
  1441. Aliases[0].Alias = Updates.Results.UrlButton;
  1442. }
  1443. Aliases[1].Button = qaAll;
  1444. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1445. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  1446. Aliases[2].Button = qaCancel;
  1447. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1448. // Used only when New == true, see AliasesCount below
  1449. Aliases[3].Button = qaOK;
  1450. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1451. if (!Updates.Results.DownloadUrl.IsEmpty())
  1452. {
  1453. Aliases[3].OnClick = MakeMethod<TNotifyEvent>(NULL, DownloadUpdate);
  1454. Aliases[3].ElevationRequired = true;
  1455. }
  1456. TMessageParams Params;
  1457. Params.Aliases = Aliases;
  1458. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1459. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1460. // alias "ok" button to "upgrade" only if we have new version
  1461. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1462. if (New)
  1463. {
  1464. Params.ImageName = L"Installer";
  1465. }
  1466. std::unique_ptr<TForm> Dialog(
  1467. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1468. if (New)
  1469. {
  1470. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1471. {
  1472. DebugAssert(Dialog->OnShow == NULL);
  1473. // InsertDonateLink need to be called only after MessageBrowser is created
  1474. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1475. }
  1476. }
  1477. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1478. switch (Answer)
  1479. {
  1480. case qaOK:
  1481. if (New)
  1482. {
  1483. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1484. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1485. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1486. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1487. OpenBrowser(UpgradeUrl);
  1488. Result = true;
  1489. }
  1490. break;
  1491. case qaYes:
  1492. OpenBrowser(Updates.Results.Url);
  1493. break;
  1494. case qaAll:
  1495. DebugFail();
  1496. break;
  1497. }
  1498. }
  1499. __finally
  1500. {
  1501. if (ActiveForm)
  1502. {
  1503. ActiveForm->Enabled = true;
  1504. }
  1505. }
  1506. return Result;
  1507. }
  1508. //---------------------------------------------------------------------------
  1509. class TUpdateThread : public TCompThread
  1510. {
  1511. public:
  1512. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1513. protected:
  1514. virtual void __fastcall Execute();
  1515. TThreadMethod FOnUpdatesChecked;
  1516. };
  1517. //---------------------------------------------------------------------------
  1518. TUpdateThread * UpdateThread = NULL;
  1519. //---------------------------------------------------------------------------
  1520. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1521. TCompThread(false),
  1522. FOnUpdatesChecked(OnUpdatesChecked)
  1523. {
  1524. }
  1525. //---------------------------------------------------------------------------
  1526. void __fastcall TUpdateThread::Execute()
  1527. {
  1528. try
  1529. {
  1530. DoQueryUpdates(WinConfiguration->CollectUsage);
  1531. if (FOnUpdatesChecked != NULL)
  1532. {
  1533. Synchronize(FOnUpdatesChecked);
  1534. }
  1535. }
  1536. catch(...)
  1537. {
  1538. // ignore errors
  1539. }
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1543. {
  1544. DebugAssert(UpdateThread == NULL);
  1545. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1546. }
  1547. //---------------------------------------------------------------------------
  1548. void __fastcall StopUpdateThread()
  1549. {
  1550. if (UpdateThread != NULL)
  1551. {
  1552. SAFE_DESTROY(UpdateThread);
  1553. }
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void __fastcall SetupInitialize()
  1557. {
  1558. WinConfiguration->UpdateJumpList();
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1562. UnicodeString AdditionalParams, TStringList * Removed,
  1563. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1564. int IconIndex)
  1565. {
  1566. bool Result = false;
  1567. IObjectCollection * Collection = NULL;
  1568. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1569. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1570. {
  1571. try
  1572. {
  1573. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1574. int Count = 0;
  1575. for (int Index = 0; Index < Names->Count; Index++)
  1576. {
  1577. IShellLink * Link =
  1578. CreateDesktopSessionShortCut(
  1579. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1580. wchar_t Desc[2048];
  1581. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1582. {
  1583. if (Removed->IndexOf(Desc) < 0)
  1584. {
  1585. try
  1586. {
  1587. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1588. Count++;
  1589. }
  1590. __finally
  1591. {
  1592. Link->Release();
  1593. }
  1594. }
  1595. else
  1596. {
  1597. Names->Delete(Index);
  1598. Index--;
  1599. }
  1600. }
  1601. }
  1602. if (Count > 0)
  1603. {
  1604. IObjectArray * Array;
  1605. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1606. {
  1607. try
  1608. {
  1609. Result = SUCCEEDED(
  1610. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1611. }
  1612. __finally
  1613. {
  1614. Array->Release();
  1615. }
  1616. }
  1617. }
  1618. }
  1619. __finally
  1620. {
  1621. Collection->Release();
  1622. }
  1623. }
  1624. return Result;
  1625. }
  1626. //---------------------------------------------------------------------------
  1627. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1628. {
  1629. ICustomDestinationList * DestinationList = NULL;
  1630. IObjectArray * RemovedArray = NULL;
  1631. TStringList * Removed = NULL;
  1632. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1633. try
  1634. {
  1635. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1636. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1637. {
  1638. unsigned int MinSlots;
  1639. unsigned int * PMinSlots = &MinSlots;
  1640. void ** PRemovedArray = (void**)&RemovedArray;
  1641. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1642. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1643. {
  1644. Removed = new TStringList();
  1645. unsigned int RemovedCount;
  1646. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1647. {
  1648. RemovedCount = 0;
  1649. }
  1650. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1651. {
  1652. IShellLink * Link;
  1653. wchar_t Desc[2048];
  1654. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1655. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1656. {
  1657. Removed->Add(Desc);
  1658. }
  1659. }
  1660. AddJumpListCategory(
  1661. WorkspaceNames, L"", Removed, DestinationList,
  1662. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1663. AddJumpListCategory(
  1664. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1665. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1666. if (DestinationList != NULL)
  1667. {
  1668. DestinationList->CommitList();
  1669. }
  1670. }
  1671. }
  1672. }
  1673. __finally
  1674. {
  1675. SetErrorMode(OldErrMode);
  1676. if (RemovedArray != NULL)
  1677. {
  1678. RemovedArray->Release();
  1679. }
  1680. if (DestinationList != NULL)
  1681. {
  1682. DestinationList->Release();
  1683. }
  1684. delete Removed;
  1685. }
  1686. }
  1687. //---------------------------------------------------------------------------
  1688. bool __fastcall AnyOtherInstanceOfSelf()
  1689. {
  1690. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1691. bool Result = false;
  1692. try
  1693. {
  1694. unsigned int Process = GetCurrentProcessId();
  1695. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1696. PROCESSENTRY32 ProcessEntry;
  1697. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1698. if (Process32First(Snapshot, &ProcessEntry))
  1699. {
  1700. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1701. {
  1702. // we should check if the process is running in the same session,
  1703. // but for that we probably need some special privileges
  1704. if ((Process != ProcessEntry.th32ProcessID) &&
  1705. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1706. {
  1707. Result = true;
  1708. }
  1709. }
  1710. }
  1711. }
  1712. __finally
  1713. {
  1714. CloseHandle(Snapshot);
  1715. }
  1716. return Result;
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1720. {
  1721. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1722. Registry->RootKey = RootKey;
  1723. bool Result =
  1724. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1725. if (Result)
  1726. {
  1727. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1728. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1729. Result =
  1730. !InstallPath.IsEmpty() &&
  1731. CompareFileName(ExePath, InstallPath);
  1732. }
  1733. return Result;
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. bool __fastcall IsInstalled()
  1737. {
  1738. return
  1739. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1740. DoIsInstalled(HKEY_CURRENT_USER);
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1744. {
  1745. std::unique_ptr<TStringList> List(new TStringList());
  1746. List->CommaText = Text;
  1747. return List.release();
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. UnicodeString __fastcall FirstUnshownTip()
  1751. {
  1752. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1753. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1754. Tips->CaseSensitive = false;
  1755. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1756. TipsSeen->CaseSensitive = false;
  1757. int LastTipSeen = -1;
  1758. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1759. {
  1760. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1761. if (TipIndex >= 0)
  1762. {
  1763. LastTipSeen = TipIndex;
  1764. }
  1765. }
  1766. UnicodeString Result;
  1767. if (LastTipSeen < Tips->Count - 1)
  1768. {
  1769. Result = Tips->Strings[LastTipSeen + 1];
  1770. }
  1771. return Result;
  1772. }
  1773. //---------------------------------------------------------------------------
  1774. class TTipsData : public TComponent
  1775. {
  1776. public:
  1777. __fastcall TTipsData() :
  1778. TComponent(NULL)
  1779. {
  1780. }
  1781. int Index;
  1782. TStringList * Tips;
  1783. static TTipsData * __fastcall Retrieve(TObject * Object)
  1784. {
  1785. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1786. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1787. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1788. }
  1789. };
  1790. //---------------------------------------------------------------------------
  1791. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1792. {
  1793. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1794. }
  1795. //---------------------------------------------------------------------------
  1796. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1797. {
  1798. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1799. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"Yes")));
  1800. PrevButton->Enabled = (TipsData->Index > 0);
  1801. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1802. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1803. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Form->FindComponent(L"Panel")));
  1804. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(Panel->FindComponent(L"MainMessage")));
  1805. MessageLabel->Caption = TipsMessage(TipsData);
  1806. }
  1807. //---------------------------------------------------------------------------
  1808. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1809. {
  1810. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1811. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1812. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1813. }
  1814. //---------------------------------------------------------------------------
  1815. static void __fastcall TipSeen(const UnicodeString & Tip)
  1816. {
  1817. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1818. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1819. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1820. WinConfiguration->TipsShown = Now();
  1821. WinConfiguration->RunsSinceLastTip = 0;
  1822. // prevent parallel app instances showing the same tip
  1823. WinConfiguration->Save();
  1824. }
  1825. //---------------------------------------------------------------------------
  1826. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender)
  1827. {
  1828. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1829. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1830. TipsData->Index += reinterpret_cast<int>(Data);
  1831. UpdateTipsForm(Form);
  1832. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1833. UnicodeString Url = TipUrl(TipsData);
  1834. NavigateMessageDialogToUrl(Form, Url);
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. static void __fastcall ShowTip(bool AutoShow)
  1838. {
  1839. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1840. UnicodeString Tip = FirstUnshownTip();
  1841. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1842. Tips->CaseSensitive = false;
  1843. int Index;
  1844. if (Tip.IsEmpty())
  1845. {
  1846. Index = Tips->Count - 1;
  1847. Tip = Tips->Strings[Index];
  1848. }
  1849. else
  1850. {
  1851. Index = Tips->IndexOf(Tip);
  1852. }
  1853. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1854. TipsData->Name = TTipsData::QualifiedClassName();
  1855. TipsData->Index = Index;
  1856. TipsData->Tips = Tips.get();
  1857. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1858. TQueryButtonAlias Aliases[3];
  1859. Aliases[0].Button = qaYes;
  1860. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1861. Aliases[0].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1862. Aliases[1].Button = qaNo;
  1863. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1864. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1865. Aliases[2].Button = qaCancel;
  1866. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1867. TMessageParams Params;
  1868. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1869. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1870. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1871. Params.Aliases = Aliases;
  1872. Params.AliasesCount = LENOF(Aliases);
  1873. Params.ImageName = L"Bulb On n p";
  1874. if (AutoShow)
  1875. {
  1876. // Won't be used automatically as we have more than the "OK" button
  1877. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1878. Params.NeverAskAgainAnswer = qaCancel;
  1879. Params.Params |= mpNeverAskAgainCheck;
  1880. }
  1881. int Answers = qaYes | qaNo | qaCancel;
  1882. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1883. Dialog->InsertComponent(TipsData.release());
  1884. UpdateTipsForm(Dialog.get());
  1885. TipSeen(Tip);
  1886. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1887. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1888. {
  1889. WinConfiguration->ShowTips = false;
  1890. }
  1891. WinConfiguration->Updates = Updates;
  1892. }
  1893. //---------------------------------------------------------------------------
  1894. void __fastcall AutoShowNewTip()
  1895. {
  1896. Configuration->Usage->Inc(L"TipsShownAuto");
  1897. ShowTip(true);
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. void __fastcall ShowTips()
  1901. {
  1902. {
  1903. TOperationVisualizer Visualizer;
  1904. DoQueryUpdates(false);
  1905. }
  1906. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1907. {
  1908. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1909. }
  1910. Configuration->Usage->Inc(L"TipsShownCommand");
  1911. ShowTip(false);
  1912. }
  1913. //---------------------------------------------------------------------------
  1914. void __fastcall TipsUpdateStaticUsage()
  1915. {
  1916. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1917. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1918. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1919. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1920. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1921. }