Setup.cpp 68 KB

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