Setup.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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. THttp * __fastcall CreateHttp()
  791. {
  792. return CreateHttp(WinConfiguration->Updates);
  793. }
  794. //---------------------------------------------------------------------------
  795. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  796. {
  797. bool Complete = false;
  798. UnicodeString Response;
  799. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  800. try
  801. {
  802. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  803. URL = WantBetaUrl(URL, false);
  804. URL += L"&dotnet=" + Updates.DotNetVersion;
  805. URL += L"&console=" + Updates.ConsoleVersion;
  806. UnicodeString LocaleVersion = WinConfiguration->LocaleVersion();
  807. if (!LocaleVersion.IsEmpty())
  808. {
  809. URL += L"&localever=" + LocaleVersion;
  810. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  811. }
  812. if (!Updates.AuthenticationEmail.IsEmpty())
  813. {
  814. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  815. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  816. }
  817. CheckForUpdatesHTTP->URL = URL;
  818. // sanity check
  819. CheckForUpdatesHTTP->ResponseLimit = 102400;
  820. if (CollectUsage)
  821. {
  822. UnicodeString Usage = GetUsageData();
  823. CheckForUpdatesHTTP->Post(Usage);
  824. }
  825. else
  826. {
  827. CheckForUpdatesHTTP->Get();
  828. }
  829. Response = CheckForUpdatesHTTP->Response;
  830. }
  831. __finally
  832. {
  833. delete CheckForUpdatesHTTP;
  834. }
  835. int CurrentCompoundVer = Configuration->CompoundVersion;
  836. bool Changed = !Updates.HaveResults;
  837. Updates.LastCheck = Now();
  838. Updates.HaveResults = true;
  839. TUpdatesData PrevResults = Updates.Results;
  840. Updates.Results.Reset();
  841. Updates.Results.ForVersion = CurrentCompoundVer;
  842. while (!Response.IsEmpty())
  843. {
  844. UnicodeString Line = CutToChar(Response, L'\n', false);
  845. UnicodeString Name = CutToChar(Line, L'=', false);
  846. if (AnsiSameText(Name, "Version"))
  847. {
  848. int NewVersion = StrToCompoundVersion(Line);
  849. Changed |= (NewVersion != PrevResults.Version);
  850. if (NewVersion <= CurrentCompoundVer)
  851. {
  852. NewVersion = 0;
  853. }
  854. Updates.Results.Version = NewVersion;
  855. Complete = true;
  856. }
  857. else if (AnsiSameText(Name, L"Message"))
  858. {
  859. Changed |= (PrevResults.Message != Line);
  860. Updates.Results.Message = Line;
  861. }
  862. else if (AnsiSameText(Name, L"Critical"))
  863. {
  864. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  865. Changed |= (PrevResults.Critical != NewCritical);
  866. Updates.Results.Critical = NewCritical;
  867. }
  868. else if (AnsiSameText(Name, L"Release"))
  869. {
  870. Changed |= (PrevResults.Release != Line);
  871. Updates.Results.Release = Line;
  872. }
  873. else if (AnsiSameText(Name, L"Disabled"))
  874. {
  875. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  876. Changed |= (PrevResults.Disabled != NewDisabled);
  877. Updates.Results.Disabled = NewDisabled;
  878. Complete = true;
  879. }
  880. else if (AnsiSameText(Name, L"Url"))
  881. {
  882. Changed |= (PrevResults.Url != Line);
  883. Updates.Results.Url = Line;
  884. }
  885. else if (AnsiSameText(Name, L"UrlButton"))
  886. {
  887. Changed |= (PrevResults.UrlButton != Line);
  888. Updates.Results.UrlButton = Line;
  889. }
  890. else if (AnsiSameText(Name, L"NewsUrl"))
  891. {
  892. Changed |= (PrevResults.NewsUrl != Line);
  893. Updates.Results.NewsUrl = Line;
  894. }
  895. else if (AnsiSameText(Name, L"NewsSize"))
  896. {
  897. TSize NewsSize;
  898. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  899. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  900. Changed |= (PrevResults.NewsSize != NewsSize);
  901. Updates.Results.NewsSize = NewsSize;
  902. }
  903. else if (AnsiSameText(Name, L"DownloadUrl"))
  904. {
  905. Changed |= (PrevResults.DownloadUrl != Line);
  906. Updates.Results.DownloadUrl = Line;
  907. }
  908. else if (AnsiSameText(Name, L"DownloadSize"))
  909. {
  910. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  911. }
  912. else if (AnsiSameText(Name, L"DownloadSha256"))
  913. {
  914. Updates.Results.DownloadSha256 = Line;
  915. }
  916. else if (AnsiSameText(Name, L"AuthenticationError"))
  917. {
  918. Changed |= (PrevResults.AuthenticationError != Line);
  919. Updates.Results.AuthenticationError = Line;
  920. }
  921. else if (AnsiSameText(Name, L"OpenGettingStarted"))
  922. {
  923. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  924. }
  925. else if (AnsiSameText(Name, L"DownloadingUrl"))
  926. {
  927. Updates.Results.DownloadingUrl = Line;
  928. }
  929. else if (AnsiSameText(Name, L"TipsSize"))
  930. {
  931. TSize TipsSize;
  932. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  933. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  934. Updates.Results.TipsSize = TipsSize;
  935. }
  936. else if (AnsiSameText(Name, L"TipsUrl"))
  937. {
  938. Updates.Results.TipsUrl = Line;
  939. }
  940. else if (AnsiSameText(Name, L"Tips"))
  941. {
  942. Updates.Results.Tips = Line;
  943. }
  944. else if (AnsiSameText(Name, L"TipsIntervalDays"))
  945. {
  946. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  947. if (TipsIntervalDays < 0)
  948. {
  949. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  950. }
  951. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  952. }
  953. else if (AnsiSameText(Name, L"TipsIntervalRuns"))
  954. {
  955. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  956. if (TipsIntervalRuns < 0)
  957. {
  958. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  959. }
  960. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  961. }
  962. }
  963. if (Changed)
  964. {
  965. Updates.ShownResults = false;
  966. }
  967. return Complete;
  968. }
  969. //---------------------------------------------------------------------------
  970. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  971. {
  972. return DoQueryUpdates(Updates, false);
  973. }
  974. //---------------------------------------------------------------------------
  975. static void __fastcall DoQueryUpdates(bool CollectUsage)
  976. {
  977. try
  978. {
  979. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  980. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  981. WinConfiguration->Updates = Updates;
  982. if (!Complete)
  983. {
  984. EXCEPTION;
  985. }
  986. Configuration->Usage->Reset();
  987. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  988. }
  989. catch(Exception & E)
  990. {
  991. Configuration->Usage->Inc(L"UpdateChecksFailed");
  992. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  993. }
  994. }
  995. //---------------------------------------------------------------------------
  996. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  997. {
  998. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  999. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1000. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1001. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  1002. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1003. Message = ReplaceStr(Message, L"|", L"\n");
  1004. return Message;
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1008. TQueryType & Type, bool Force)
  1009. {
  1010. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1011. DebugAssert(Updates.HaveResults);
  1012. if (Updates.HaveResults)
  1013. {
  1014. if (Updates.Results.Disabled)
  1015. {
  1016. New = false;
  1017. if (Force)
  1018. {
  1019. Message = LoadStr(UPDATE_DISABLED);
  1020. }
  1021. }
  1022. else
  1023. {
  1024. New = (Updates.Results.Version > 0);
  1025. if (New)
  1026. {
  1027. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1028. if (!Updates.Results.Release.IsEmpty())
  1029. {
  1030. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1031. }
  1032. Message = FMTLOAD(NEW_VERSION4, (Version));
  1033. }
  1034. else
  1035. {
  1036. Message = LoadStr(NO_NEW_VERSION);
  1037. }
  1038. }
  1039. if (!Message.IsEmpty())
  1040. {
  1041. Message = MainInstructions(Message);
  1042. }
  1043. if (!Updates.Results.Message.IsEmpty())
  1044. {
  1045. Message +=
  1046. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1047. }
  1048. if (!Updates.Results.AuthenticationError.IsEmpty())
  1049. {
  1050. Message +=
  1051. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1052. }
  1053. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1054. }
  1055. else
  1056. {
  1057. New = false;
  1058. }
  1059. }
  1060. //---------------------------------------------------------------------------
  1061. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1062. {
  1063. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall EnableAutomaticUpdates()
  1067. {
  1068. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  1072. {
  1073. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1074. OpenBrowser(LoadStr(HISTORY_URL));
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1078. {
  1079. return static_cast<int>(Size / 1024);
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. class TUpdateDownloadThread : public TCompThread
  1083. {
  1084. public:
  1085. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1086. virtual __fastcall ~TUpdateDownloadThread();
  1087. void __fastcall CancelClicked(TObject * Sender);
  1088. bool __fastcall CancelDownload();
  1089. __property bool Done = { read = FDone };
  1090. protected:
  1091. virtual void __fastcall Execute();
  1092. void __fastcall UpdateDownloaded();
  1093. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1094. void __fastcall UpdateProgress();
  1095. void __fastcall ShowException();
  1096. void __fastcall DownloadNotVerified();
  1097. void __fastcall CancelForm();
  1098. private:
  1099. TCustomForm * FForm;
  1100. TProgressBar * FProgressBar;
  1101. __int64 FDownloaded;
  1102. std::unique_ptr<Exception> FException;
  1103. std::unique_ptr<THttp> FHttp;
  1104. TUpdatesConfiguration FUpdates;
  1105. bool FDone;
  1106. };
  1107. //---------------------------------------------------------------------------
  1108. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1109. TCompThread(true)
  1110. {
  1111. // cache, as the progress bar miht be destroyed already when
  1112. // we need the form at the end of Execute()
  1113. FForm = GetParentForm(ProgressBar);
  1114. FProgressBar = ProgressBar;
  1115. // cache to prevent concurrency
  1116. FUpdates = WinConfiguration->Updates;
  1117. FDone = false;
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1121. {
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TUpdateDownloadThread::Execute()
  1125. {
  1126. try
  1127. {
  1128. bool Retried = false;
  1129. bool Retry;
  1130. do
  1131. {
  1132. Retry = false;
  1133. try
  1134. {
  1135. FDownloaded = 0;
  1136. FHttp.reset(CreateHttp(FUpdates));
  1137. FHttp->URL = FUpdates.Results.DownloadUrl;
  1138. FHttp->OnDownload = HttpDownload;
  1139. FHttp->Get();
  1140. }
  1141. catch (EAbort &)
  1142. {
  1143. throw;
  1144. }
  1145. catch (Exception & E)
  1146. {
  1147. // The original URL failed, try to get a fresh one and retry
  1148. if (!Retried)
  1149. {
  1150. try
  1151. {
  1152. // Check if new update data (URL particlarly) is available
  1153. if (QueryUpdates(FUpdates) &&
  1154. !FUpdates.Results.DownloadUrl.IsEmpty())
  1155. {
  1156. Retry = true;
  1157. Retried = true;
  1158. }
  1159. }
  1160. catch (...)
  1161. {
  1162. }
  1163. }
  1164. if (!Retry)
  1165. {
  1166. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1167. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1168. }
  1169. }
  1170. }
  1171. while (Retry);
  1172. Synchronize(UpdateDownloaded);
  1173. }
  1174. catch (EAbort &)
  1175. {
  1176. // noop
  1177. }
  1178. catch (Exception & E)
  1179. {
  1180. Configuration->Usage->Inc(L"UpdateFailures");
  1181. FException.reset(CloneException(&E));
  1182. Synchronize(ShowException);
  1183. }
  1184. FDone = true;
  1185. Synchronize(CancelForm);
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. void __fastcall TUpdateDownloadThread::CancelForm()
  1189. {
  1190. FForm->ModalResult = mrCancel;
  1191. }
  1192. //---------------------------------------------------------------------------
  1193. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1194. {
  1195. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1196. const char * Buffer = FHttp->ResponseRaw.c_str();
  1197. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1198. {
  1199. DownloadNotVerified();
  1200. }
  1201. UnicodeString Digest = Sha256(Buffer, Size);
  1202. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1203. {
  1204. DownloadNotVerified();
  1205. }
  1206. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1207. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1208. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1209. UnicodeString SetupPath = SetupPathBase;
  1210. int Index = 0;
  1211. while (FileExists(SetupPath))
  1212. {
  1213. Index++;
  1214. SetupPath =
  1215. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1216. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1217. }
  1218. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1219. FileStream->Write(Buffer, Size);
  1220. FileStream.reset(NULL);
  1221. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1222. if (FUpdates.Results.OpenGettingStarted)
  1223. {
  1224. Params += L" /OpenGettingStarted";
  1225. }
  1226. if (!ExecuteShell(SetupPath, Params))
  1227. {
  1228. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (SetupPath)));
  1229. }
  1230. Configuration->Usage->Inc(L"UpdateRuns");
  1231. Application->Terminate();
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1235. {
  1236. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1240. {
  1241. FDownloaded = Size;
  1242. Synchronize(UpdateProgress);
  1243. // Do not waste bandwidth, if something goes wrong
  1244. if (FDownloaded > FUpdates.Results.DownloadSize)
  1245. {
  1246. DownloadNotVerified();
  1247. }
  1248. if (Terminated)
  1249. {
  1250. Cancel = true;
  1251. }
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1255. {
  1256. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. void __fastcall TUpdateDownloadThread::ShowException()
  1260. {
  1261. DebugAssert(FException.get() != NULL);
  1262. ShowExtendedException(FException.get());
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1266. {
  1267. bool Result = !Terminated;
  1268. if (Result)
  1269. {
  1270. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1271. Terminate();
  1272. }
  1273. return Result;
  1274. }
  1275. //---------------------------------------------------------------------------
  1276. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1277. {
  1278. if (CancelDownload())
  1279. {
  1280. WaitFor();
  1281. }
  1282. }
  1283. //---------------------------------------------------------------------------
  1284. //---------------------------------------------------------------------------
  1285. class TUpdateDownloadData : public TComponent
  1286. {
  1287. public:
  1288. TUpdateDownloadThread * Thread;
  1289. __fastcall TUpdateDownloadData() :
  1290. TComponent(NULL)
  1291. {
  1292. }
  1293. virtual __fastcall ~TUpdateDownloadData()
  1294. {
  1295. // will stop the thread
  1296. delete Thread;
  1297. }
  1298. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1299. {
  1300. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1301. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1302. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1303. }
  1304. };
  1305. //---------------------------------------------------------------------------
  1306. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1307. {
  1308. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1309. // If the form was closed by CancelForm at the end of the thread, do nothing
  1310. if (!UpdateDownloadData->Thread->Done)
  1311. {
  1312. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1313. // May this should actually call CancelClicked?
  1314. if (UpdateDownloadData->Thread->CancelDownload())
  1315. {
  1316. Action = caNone;
  1317. }
  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. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1463. if (New)
  1464. {
  1465. Params.ImageName = L"Installer";
  1466. }
  1467. std::unique_ptr<TForm> Dialog(
  1468. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1469. if (New)
  1470. {
  1471. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1472. {
  1473. DebugAssert(Dialog->OnShow == NULL);
  1474. // InsertDonateLink need to be called only after MessageBrowser is created
  1475. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1476. }
  1477. }
  1478. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1479. switch (Answer)
  1480. {
  1481. case qaOK:
  1482. if (New)
  1483. {
  1484. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1485. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1486. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1487. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1488. OpenBrowser(UpgradeUrl);
  1489. Result = true;
  1490. }
  1491. break;
  1492. case qaYes:
  1493. OpenBrowser(Updates.Results.Url);
  1494. break;
  1495. case qaAll:
  1496. DebugFail();
  1497. break;
  1498. }
  1499. }
  1500. __finally
  1501. {
  1502. if (ActiveForm)
  1503. {
  1504. ActiveForm->Enabled = true;
  1505. }
  1506. }
  1507. return Result;
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. class TUpdateThread : public TCompThread
  1511. {
  1512. public:
  1513. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1514. protected:
  1515. virtual void __fastcall Execute();
  1516. TThreadMethod FOnUpdatesChecked;
  1517. };
  1518. //---------------------------------------------------------------------------
  1519. TUpdateThread * UpdateThread = NULL;
  1520. //---------------------------------------------------------------------------
  1521. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1522. TCompThread(false),
  1523. FOnUpdatesChecked(OnUpdatesChecked)
  1524. {
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. void __fastcall TUpdateThread::Execute()
  1528. {
  1529. try
  1530. {
  1531. DoQueryUpdates(WinConfiguration->CollectUsage);
  1532. if (FOnUpdatesChecked != NULL)
  1533. {
  1534. Synchronize(FOnUpdatesChecked);
  1535. }
  1536. }
  1537. catch(...)
  1538. {
  1539. // ignore errors
  1540. }
  1541. }
  1542. //---------------------------------------------------------------------------
  1543. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1544. {
  1545. DebugAssert(UpdateThread == NULL);
  1546. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. void __fastcall StopUpdateThread()
  1550. {
  1551. if (UpdateThread != NULL)
  1552. {
  1553. SAFE_DESTROY(UpdateThread);
  1554. }
  1555. }
  1556. //---------------------------------------------------------------------------
  1557. void __fastcall SetupInitialize()
  1558. {
  1559. WinConfiguration->UpdateJumpList();
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1563. UnicodeString AdditionalParams, TStringList * Removed,
  1564. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1565. int IconIndex)
  1566. {
  1567. bool Result = false;
  1568. IObjectCollection * Collection = NULL;
  1569. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1570. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1571. {
  1572. try
  1573. {
  1574. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1575. int Count = 0;
  1576. for (int Index = 0; Index < Names->Count; Index++)
  1577. {
  1578. IShellLink * Link =
  1579. CreateDesktopSessionShortCut(
  1580. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1581. wchar_t Desc[2048];
  1582. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1583. {
  1584. if (Removed->IndexOf(Desc) < 0)
  1585. {
  1586. try
  1587. {
  1588. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1589. Count++;
  1590. }
  1591. __finally
  1592. {
  1593. Link->Release();
  1594. }
  1595. }
  1596. else
  1597. {
  1598. Names->Delete(Index);
  1599. Index--;
  1600. }
  1601. }
  1602. }
  1603. if (Count > 0)
  1604. {
  1605. IObjectArray * Array;
  1606. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1607. {
  1608. try
  1609. {
  1610. Result = SUCCEEDED(
  1611. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1612. }
  1613. __finally
  1614. {
  1615. Array->Release();
  1616. }
  1617. }
  1618. }
  1619. }
  1620. __finally
  1621. {
  1622. Collection->Release();
  1623. }
  1624. }
  1625. return Result;
  1626. }
  1627. //---------------------------------------------------------------------------
  1628. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1629. {
  1630. ICustomDestinationList * DestinationList = NULL;
  1631. IObjectArray * RemovedArray = NULL;
  1632. TStringList * Removed = NULL;
  1633. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1634. try
  1635. {
  1636. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1637. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1638. {
  1639. unsigned int MinSlots;
  1640. unsigned int * PMinSlots = &MinSlots;
  1641. void ** PRemovedArray = (void**)&RemovedArray;
  1642. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1643. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1644. {
  1645. Removed = new TStringList();
  1646. unsigned int RemovedCount;
  1647. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1648. {
  1649. RemovedCount = 0;
  1650. }
  1651. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1652. {
  1653. IShellLink * Link;
  1654. wchar_t Desc[2048];
  1655. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1656. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1657. {
  1658. Removed->Add(Desc);
  1659. }
  1660. }
  1661. AddJumpListCategory(
  1662. WorkspaceNames, L"", Removed, DestinationList,
  1663. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1664. AddJumpListCategory(
  1665. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1666. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1667. if (DestinationList != NULL)
  1668. {
  1669. DestinationList->CommitList();
  1670. }
  1671. }
  1672. }
  1673. }
  1674. __finally
  1675. {
  1676. SetErrorMode(OldErrMode);
  1677. if (RemovedArray != NULL)
  1678. {
  1679. RemovedArray->Release();
  1680. }
  1681. if (DestinationList != NULL)
  1682. {
  1683. DestinationList->Release();
  1684. }
  1685. delete Removed;
  1686. }
  1687. }
  1688. //---------------------------------------------------------------------------
  1689. bool __fastcall AnyOtherInstanceOfSelf()
  1690. {
  1691. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1692. bool Result = false;
  1693. try
  1694. {
  1695. unsigned int Process = GetCurrentProcessId();
  1696. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1697. PROCESSENTRY32 ProcessEntry;
  1698. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1699. if (Process32First(Snapshot, &ProcessEntry))
  1700. {
  1701. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1702. {
  1703. // we should check if the process is running in the same session,
  1704. // but for that we probably need some special privileges
  1705. if ((Process != ProcessEntry.th32ProcessID) &&
  1706. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1707. {
  1708. Result = true;
  1709. }
  1710. }
  1711. }
  1712. }
  1713. __finally
  1714. {
  1715. CloseHandle(Snapshot);
  1716. }
  1717. return Result;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1721. {
  1722. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1723. Registry->RootKey = RootKey;
  1724. bool Result =
  1725. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1726. if (Result)
  1727. {
  1728. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1729. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1730. Result =
  1731. !InstallPath.IsEmpty() &&
  1732. CompareFileName(ExePath, InstallPath);
  1733. }
  1734. return Result;
  1735. }
  1736. //---------------------------------------------------------------------------
  1737. bool __fastcall IsInstalled()
  1738. {
  1739. return
  1740. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1741. DoIsInstalled(HKEY_CURRENT_USER);
  1742. }
  1743. //---------------------------------------------------------------------------
  1744. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1745. {
  1746. std::unique_ptr<TStringList> List(new TStringList());
  1747. List->CommaText = Text;
  1748. return List.release();
  1749. }
  1750. //---------------------------------------------------------------------------
  1751. UnicodeString __fastcall FirstUnshownTip()
  1752. {
  1753. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1754. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1755. Tips->CaseSensitive = false;
  1756. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1757. TipsSeen->CaseSensitive = false;
  1758. int LastTipSeen = -1;
  1759. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1760. {
  1761. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1762. if (TipIndex >= 0)
  1763. {
  1764. LastTipSeen = TipIndex;
  1765. }
  1766. }
  1767. UnicodeString Result;
  1768. if (LastTipSeen < Tips->Count - 1)
  1769. {
  1770. Result = Tips->Strings[LastTipSeen + 1];
  1771. }
  1772. return Result;
  1773. }
  1774. //---------------------------------------------------------------------------
  1775. class TTipsData : public TComponent
  1776. {
  1777. public:
  1778. __fastcall TTipsData() :
  1779. TComponent(NULL)
  1780. {
  1781. }
  1782. int Index;
  1783. TStringList * Tips;
  1784. static TTipsData * __fastcall Retrieve(TObject * Object)
  1785. {
  1786. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1787. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1788. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1789. }
  1790. };
  1791. //---------------------------------------------------------------------------
  1792. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1793. {
  1794. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1798. {
  1799. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1800. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"Yes")));
  1801. PrevButton->Enabled = (TipsData->Index > 0);
  1802. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1803. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1804. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Form->FindComponent(L"Panel")));
  1805. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(Panel->FindComponent(L"MainMessage")));
  1806. MessageLabel->Caption = TipsMessage(TipsData);
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1810. {
  1811. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1812. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1813. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1814. }
  1815. //---------------------------------------------------------------------------
  1816. static void __fastcall TipSeen(const UnicodeString & Tip)
  1817. {
  1818. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1819. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1820. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1821. WinConfiguration->TipsShown = Now();
  1822. WinConfiguration->RunsSinceLastTip = 0;
  1823. // prevent parallel app instances showing the same tip
  1824. WinConfiguration->Save();
  1825. }
  1826. //---------------------------------------------------------------------------
  1827. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender)
  1828. {
  1829. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1830. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1831. TipsData->Index += reinterpret_cast<int>(Data);
  1832. UpdateTipsForm(Form);
  1833. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1834. UnicodeString Url = TipUrl(TipsData);
  1835. NavigateMessageDialogToUrl(Form, Url);
  1836. }
  1837. //---------------------------------------------------------------------------
  1838. static void __fastcall ShowTip(bool AutoShow)
  1839. {
  1840. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1841. UnicodeString Tip = FirstUnshownTip();
  1842. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1843. Tips->CaseSensitive = false;
  1844. int Index;
  1845. if (Tip.IsEmpty())
  1846. {
  1847. Index = Tips->Count - 1;
  1848. Tip = Tips->Strings[Index];
  1849. }
  1850. else
  1851. {
  1852. Index = Tips->IndexOf(Tip);
  1853. }
  1854. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1855. TipsData->Name = TTipsData::QualifiedClassName();
  1856. TipsData->Index = Index;
  1857. TipsData->Tips = Tips.get();
  1858. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1859. TQueryButtonAlias Aliases[3];
  1860. Aliases[0].Button = qaYes;
  1861. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1862. Aliases[0].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1863. Aliases[1].Button = qaNo;
  1864. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1865. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1866. Aliases[2].Button = qaCancel;
  1867. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1868. TMessageParams Params;
  1869. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1870. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1871. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1872. Params.Aliases = Aliases;
  1873. Params.AliasesCount = LENOF(Aliases);
  1874. Params.ImageName = L"Bulb On n p";
  1875. if (AutoShow)
  1876. {
  1877. // Won't be used automatically as we have more than the "OK" button
  1878. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1879. Params.NeverAskAgainAnswer = qaCancel;
  1880. Params.Params |= mpNeverAskAgainCheck;
  1881. }
  1882. int Answers = qaYes | qaNo | qaCancel;
  1883. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1884. Dialog->InsertComponent(TipsData.release());
  1885. UpdateTipsForm(Dialog.get());
  1886. TipSeen(Tip);
  1887. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1888. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1889. {
  1890. WinConfiguration->ShowTips = false;
  1891. }
  1892. WinConfiguration->Updates = Updates;
  1893. }
  1894. //---------------------------------------------------------------------------
  1895. void __fastcall AutoShowNewTip()
  1896. {
  1897. Configuration->Usage->Inc(L"TipsShownAuto");
  1898. ShowTip(true);
  1899. }
  1900. //---------------------------------------------------------------------------
  1901. void __fastcall ShowTips()
  1902. {
  1903. {
  1904. TOperationVisualizer Visualizer;
  1905. DoQueryUpdates(false);
  1906. }
  1907. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1908. {
  1909. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1910. }
  1911. Configuration->Usage->Inc(L"TipsShownCommand");
  1912. ShowTip(false);
  1913. }
  1914. //---------------------------------------------------------------------------
  1915. void __fastcall TipsUpdateStaticUsage()
  1916. {
  1917. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1918. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1919. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1920. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1921. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1922. }