Setup.cpp 67 KB

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