Setup.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  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, SftpProtocol);
  522. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  523. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  524. // deliberately not including WebDAV/http,
  525. // it's unlikely that anyone would like to change http handler
  526. // to non-browser application
  527. }
  528. //---------------------------------------------------------------------------
  529. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  530. {
  531. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  532. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  533. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  534. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  535. UnregisterProtocolForDefaultPrograms(RootKey, SshProtocol, ForceHandlerUnregistration);
  536. // we should not really need the "force" flag here, but why not
  537. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  538. }
  539. //---------------------------------------------------------------------------
  540. static void __fastcall RegisterForDefaultPrograms()
  541. {
  542. try
  543. {
  544. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  545. // make sure we unregister any legacy protocol handler for CU,
  546. // this is needed for Windows Vista+7
  547. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  548. }
  549. catch (Exception & E)
  550. {
  551. try
  552. {
  553. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  554. }
  555. catch (Exception & E)
  556. {
  557. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  558. }
  559. }
  560. }
  561. //---------------------------------------------------------------------------
  562. static void __fastcall NotifyChangedAssociations()
  563. {
  564. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  565. }
  566. //---------------------------------------------------------------------------
  567. void __fastcall RegisterForDefaultProtocols()
  568. {
  569. if (IsWinVista())
  570. {
  571. RegisterForDefaultPrograms();
  572. }
  573. else
  574. {
  575. RegisterAsNonBrowserUrlHandler(UnicodeString());
  576. }
  577. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  578. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  579. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  580. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase());
  581. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase());
  582. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  583. NotifyChangedAssociations();
  584. }
  585. //---------------------------------------------------------------------------
  586. void __fastcall UnregisterForProtocols()
  587. {
  588. UnregisterAsUrlHandlers(UnicodeString(), false);
  589. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  590. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  591. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  592. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase(), true);
  593. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase(), true);
  594. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  595. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  596. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  597. NotifyChangedAssociations();
  598. }
  599. //---------------------------------------------------------------------------
  600. void __fastcall LaunchAdvancedAssociationUI()
  601. {
  602. DebugAssert(IsWinVista());
  603. RegisterForDefaultPrograms();
  604. NotifyChangedAssociations();
  605. // sleep recommended by http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  606. Sleep(1000);
  607. if (IsWin10())
  608. {
  609. ExecuteShell(L"control.exe", L"/name Microsoft.DefaultPrograms");
  610. }
  611. else
  612. {
  613. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  614. HRESULT Result =
  615. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  616. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  617. if (SUCCEEDED(Result))
  618. {
  619. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  620. AppAssocRegUI->Release();
  621. }
  622. }
  623. }
  624. //---------------------------------------------------------------------------
  625. void __fastcall TemporaryDirectoryCleanup()
  626. {
  627. bool Continue = true;
  628. TStrings * Folders = NULL;
  629. try
  630. {
  631. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  632. {
  633. Folders = WinConfiguration->FindTemporaryFolders();
  634. Continue = (Folders != NULL);
  635. if (Continue)
  636. {
  637. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  638. TQueryButtonAlias Aliases[1];
  639. Aliases[0].Button = qaRetry;
  640. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  641. TMessageParams Params(mpNeverAskAgainCheck);
  642. Params.Aliases = Aliases;
  643. Params.AliasesCount = LENOF(Aliases);
  644. unsigned int Answer = MoreMessageDialog(
  645. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  646. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  647. if (Answer == qaNeverAskAgain)
  648. {
  649. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  650. Answer = qaYes;
  651. }
  652. else if (Answer == qaRetry)
  653. {
  654. for (int Index = 0; Index < Folders->Count; Index++)
  655. {
  656. ShellExecute(Application->Handle, NULL,
  657. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  658. }
  659. }
  660. Continue = (Answer == qaYes);
  661. }
  662. }
  663. if (Continue)
  664. {
  665. try
  666. {
  667. WinConfiguration->CleanupTemporaryFolders(Folders);
  668. }
  669. catch (Exception &E)
  670. {
  671. ShowExtendedException(&E);
  672. }
  673. }
  674. }
  675. __finally
  676. {
  677. delete Folders;
  678. }
  679. }
  680. //-------------------------------------------- -------------------------------
  681. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  682. {
  683. int MajorVer = Version / (10000*100*100);
  684. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  685. int Release = (Version % (10000*100)) / (10000);
  686. UnicodeString Result;
  687. if (Release > 0)
  688. {
  689. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  690. }
  691. else
  692. {
  693. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  694. }
  695. return Result;
  696. }
  697. //---------------------------------------------------------------------------
  698. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  699. {
  700. int CurrentCompoundVer = Configuration->CompoundVersion;
  701. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  702. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  703. return AppendUrlParams(URL, Params);
  704. }
  705. //---------------------------------------------------------------------------
  706. UnicodeString __fastcall GetUsageData()
  707. {
  708. return Configuration->Usage->Serialize();
  709. }
  710. //---------------------------------------------------------------------------
  711. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  712. {
  713. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  714. UnicodeString CurrentVersionStr =
  715. FORMAT(L"%d.%d.%d.%d",
  716. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  717. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  718. UnicodeString Params =
  719. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  720. (CurrentVersionStr,
  721. IntToHex(__int64(GUIConfiguration->Locale), 4),
  722. int(IsInstalled())));
  723. if (Configuration->IsUnofficial)
  724. {
  725. Params += L"&unofficial=1";
  726. }
  727. return AppendUrlParams(URL, Params);
  728. }
  729. //---------------------------------------------------------------------------
  730. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  731. {
  732. bool Beta;
  733. if (WinConfiguration->IsBeta)
  734. {
  735. Beta = true;
  736. }
  737. else
  738. {
  739. switch (WinConfiguration->Updates.BetaVersions)
  740. {
  741. case asAuto:
  742. Beta = WinConfiguration->AnyBetaInVersionHistory;
  743. break;
  744. case asOn:
  745. Beta = true;
  746. break;
  747. default:
  748. Beta = false;
  749. break;
  750. }
  751. }
  752. if (Beta || Force)
  753. {
  754. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  755. }
  756. return URL;
  757. }
  758. //---------------------------------------------------------------------------
  759. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  760. {
  761. std::unique_ptr<THttp> Http(new THttp());
  762. UnicodeString ProxyHost;
  763. int ProxyPort = 0;
  764. switch (Updates.ConnectionType)
  765. {
  766. case ctAuto:
  767. if (AutodetectProxy(ProxyHost, ProxyPort))
  768. {
  769. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  770. }
  771. break;
  772. case ctProxy:
  773. ProxyHost = Updates.ProxyHost;
  774. ProxyPort = Updates.ProxyPort;
  775. Configuration->Usage->Inc(L"UpdateProxyManual");
  776. break;
  777. }
  778. Http->ProxyHost = ProxyHost;
  779. Http->ProxyPort = ProxyPort;
  780. return Http.release();
  781. }
  782. //---------------------------------------------------------------------------
  783. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  784. {
  785. bool Complete = false;
  786. UnicodeString Response;
  787. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  788. try
  789. {
  790. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  791. URL = WantBetaUrl(URL, false);
  792. URL += L"&dotnet=" + Updates.DotNetVersion;
  793. URL += L"&console=" + Updates.ConsoleVersion;
  794. UnicodeString LocaleVersion = WinConfiguration->LocaleVersion();
  795. if (!LocaleVersion.IsEmpty())
  796. {
  797. URL += L"&localever=" + LocaleVersion;
  798. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  799. }
  800. if (!Updates.AuthenticationEmail.IsEmpty())
  801. {
  802. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  803. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  804. }
  805. CheckForUpdatesHTTP->URL = URL;
  806. // sanity check
  807. CheckForUpdatesHTTP->ResponseLimit = 102400;
  808. if (CollectUsage)
  809. {
  810. UnicodeString Usage = GetUsageData();
  811. CheckForUpdatesHTTP->Post(Usage);
  812. }
  813. else
  814. {
  815. CheckForUpdatesHTTP->Get();
  816. }
  817. Response = CheckForUpdatesHTTP->Response;
  818. }
  819. __finally
  820. {
  821. delete CheckForUpdatesHTTP;
  822. }
  823. int CurrentCompoundVer = Configuration->CompoundVersion;
  824. bool Changed = !Updates.HaveResults;
  825. Updates.LastCheck = Now();
  826. Updates.HaveResults = true;
  827. TUpdatesData PrevResults = Updates.Results;
  828. Updates.Results.Reset();
  829. Updates.Results.ForVersion = CurrentCompoundVer;
  830. while (!Response.IsEmpty())
  831. {
  832. UnicodeString Line = CutToChar(Response, L'\n', false);
  833. UnicodeString Name = CutToChar(Line, L'=', false);
  834. if (AnsiSameText(Name, "Version"))
  835. {
  836. int MajorVer = StrToInt(CutToChar(Line, L'.', false));
  837. int MinorVer = StrToInt(CutToChar(Line, L'.', false));
  838. int Release = StrToInt(CutToChar(Line, L'.', false));
  839. int Build = StrToInt(CutToChar(Line, L'.', false));
  840. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  841. Changed |= (NewVersion != PrevResults.Version);
  842. if (NewVersion <= CurrentCompoundVer)
  843. {
  844. NewVersion = 0;
  845. }
  846. Updates.Results.Version = NewVersion;
  847. Complete = true;
  848. }
  849. else if (AnsiSameText(Name, L"Message"))
  850. {
  851. Changed |= (PrevResults.Message != Line);
  852. Updates.Results.Message = Line;
  853. }
  854. else if (AnsiSameText(Name, L"Critical"))
  855. {
  856. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  857. Changed |= (PrevResults.Critical != NewCritical);
  858. Updates.Results.Critical = NewCritical;
  859. }
  860. else if (AnsiSameText(Name, L"Release"))
  861. {
  862. Changed |= (PrevResults.Release != Line);
  863. Updates.Results.Release = Line;
  864. }
  865. else if (AnsiSameText(Name, L"Disabled"))
  866. {
  867. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  868. Changed |= (PrevResults.Disabled != NewDisabled);
  869. Updates.Results.Disabled = NewDisabled;
  870. Complete = true;
  871. }
  872. else if (AnsiSameText(Name, L"Url"))
  873. {
  874. Changed |= (PrevResults.Url != Line);
  875. Updates.Results.Url = Line;
  876. }
  877. else if (AnsiSameText(Name, L"UrlButton"))
  878. {
  879. Changed |= (PrevResults.UrlButton != Line);
  880. Updates.Results.UrlButton = Line;
  881. }
  882. else if (AnsiSameText(Name, L"NewsUrl"))
  883. {
  884. Changed |= (PrevResults.NewsUrl != Line);
  885. Updates.Results.NewsUrl = Line;
  886. }
  887. else if (AnsiSameText(Name, L"NewsSize"))
  888. {
  889. TSize NewsSize;
  890. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  891. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  892. Changed |= (PrevResults.NewsSize != NewsSize);
  893. Updates.Results.NewsSize = NewsSize;
  894. }
  895. else if (AnsiSameText(Name, L"DownloadUrl"))
  896. {
  897. Changed |= (PrevResults.DownloadUrl != Line);
  898. Updates.Results.DownloadUrl = Line;
  899. }
  900. else if (AnsiSameText(Name, L"DownloadSize"))
  901. {
  902. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  903. }
  904. else if (AnsiSameText(Name, L"DownloadSha256"))
  905. {
  906. Updates.Results.DownloadSha256 = Line;
  907. }
  908. else if (AnsiSameText(Name, L"AuthenticationError"))
  909. {
  910. Changed |= (PrevResults.AuthenticationError != Line);
  911. Updates.Results.AuthenticationError = Line;
  912. }
  913. else if (AnsiSameText(Name, L"OpenGettingStarted"))
  914. {
  915. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  916. }
  917. else if (AnsiSameText(Name, L"DownloadingUrl"))
  918. {
  919. Updates.Results.DownloadingUrl = Line;
  920. }
  921. else if (AnsiSameText(Name, L"TipsSize"))
  922. {
  923. TSize TipsSize;
  924. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  925. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  926. Updates.Results.TipsSize = TipsSize;
  927. }
  928. else if (AnsiSameText(Name, L"TipsUrl"))
  929. {
  930. Updates.Results.TipsUrl = Line;
  931. }
  932. else if (AnsiSameText(Name, L"Tips"))
  933. {
  934. Updates.Results.Tips = Line;
  935. }
  936. else if (AnsiSameText(Name, L"TipsIntervalDays"))
  937. {
  938. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  939. if (TipsIntervalDays < 0)
  940. {
  941. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  942. }
  943. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  944. }
  945. else if (AnsiSameText(Name, L"TipsIntervalRuns"))
  946. {
  947. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  948. if (TipsIntervalRuns < 0)
  949. {
  950. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  951. }
  952. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  953. }
  954. }
  955. if (Changed)
  956. {
  957. Updates.ShownResults = false;
  958. }
  959. return Complete;
  960. }
  961. //---------------------------------------------------------------------------
  962. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  963. {
  964. return DoQueryUpdates(Updates, false);
  965. }
  966. //---------------------------------------------------------------------------
  967. static void __fastcall DoQueryUpdates(bool CollectUsage)
  968. {
  969. try
  970. {
  971. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  972. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  973. WinConfiguration->Updates = Updates;
  974. if (!Complete)
  975. {
  976. EXCEPTION;
  977. }
  978. Configuration->Usage->Reset();
  979. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  980. }
  981. catch(Exception & E)
  982. {
  983. Configuration->Usage->Inc(L"UpdateChecksFailed");
  984. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  985. }
  986. }
  987. //---------------------------------------------------------------------------
  988. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  989. {
  990. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  991. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  992. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  993. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  994. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  995. Message = ReplaceStr(Message, L"|", L"\n");
  996. return Message;
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1000. TQueryType & Type, bool Force)
  1001. {
  1002. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1003. DebugAssert(Updates.HaveResults);
  1004. if (Updates.HaveResults)
  1005. {
  1006. if (Updates.Results.Disabled)
  1007. {
  1008. New = false;
  1009. if (Force)
  1010. {
  1011. Message = LoadStr(UPDATE_DISABLED);
  1012. }
  1013. }
  1014. else
  1015. {
  1016. New = (Updates.Results.Version > 0);
  1017. if (New)
  1018. {
  1019. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1020. if (!Updates.Results.Release.IsEmpty())
  1021. {
  1022. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1023. }
  1024. Message = FMTLOAD(NEW_VERSION4, (Version));
  1025. }
  1026. else
  1027. {
  1028. Message = LoadStr(NO_NEW_VERSION);
  1029. }
  1030. }
  1031. if (!Message.IsEmpty())
  1032. {
  1033. Message = MainInstructions(Message);
  1034. }
  1035. if (!Updates.Results.Message.IsEmpty())
  1036. {
  1037. Message +=
  1038. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1039. }
  1040. if (!Updates.Results.AuthenticationError.IsEmpty())
  1041. {
  1042. Message +=
  1043. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1044. }
  1045. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1046. }
  1047. else
  1048. {
  1049. New = false;
  1050. }
  1051. }
  1052. //---------------------------------------------------------------------------
  1053. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1054. {
  1055. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. void __fastcall EnableAutomaticUpdates()
  1059. {
  1060. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  1064. {
  1065. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1066. OpenBrowser(LoadStr(HISTORY_URL));
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1070. {
  1071. return static_cast<int>(Size / 1024);
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. class TUpdateDownloadThread : public TCompThread
  1075. {
  1076. public:
  1077. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1078. virtual __fastcall ~TUpdateDownloadThread();
  1079. void __fastcall CancelClicked(TObject * Sender);
  1080. bool __fastcall CancelDownload();
  1081. protected:
  1082. virtual void __fastcall Execute();
  1083. void __fastcall UpdateDownloaded();
  1084. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1085. void __fastcall UpdateProgress();
  1086. void __fastcall ShowException();
  1087. void __fastcall DownloadNotVerified();
  1088. void __fastcall CancelForm();
  1089. private:
  1090. TCustomForm * FForm;
  1091. TProgressBar * FProgressBar;
  1092. __int64 FDownloaded;
  1093. std::unique_ptr<Exception> FException;
  1094. std::unique_ptr<THttp> FHttp;
  1095. TUpdatesConfiguration FUpdates;
  1096. };
  1097. //---------------------------------------------------------------------------
  1098. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1099. TCompThread(true)
  1100. {
  1101. // cache, as the progress bar miht be destroyed already when
  1102. // we need the form at the end of Execute()
  1103. FForm = GetParentForm(ProgressBar);
  1104. FProgressBar = ProgressBar;
  1105. // cache to prevent concurrency
  1106. FUpdates = WinConfiguration->Updates;
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1110. {
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. void __fastcall TUpdateDownloadThread::Execute()
  1114. {
  1115. try
  1116. {
  1117. try
  1118. {
  1119. FHttp.reset(CreateHttp(FUpdates));
  1120. FHttp->URL = FUpdates.Results.DownloadUrl;
  1121. FHttp->OnDownload = HttpDownload;
  1122. FHttp->Get();
  1123. }
  1124. catch (EAbort &)
  1125. {
  1126. throw;
  1127. }
  1128. catch (Exception & E)
  1129. {
  1130. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1131. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1132. }
  1133. Synchronize(UpdateDownloaded);
  1134. }
  1135. catch (EAbort &)
  1136. {
  1137. // noop
  1138. }
  1139. catch (Exception & E)
  1140. {
  1141. Configuration->Usage->Inc(L"UpdateFailures");
  1142. FException.reset(CloneException(&E));
  1143. Synchronize(ShowException);
  1144. }
  1145. Synchronize(CancelForm);
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TUpdateDownloadThread::CancelForm()
  1149. {
  1150. FForm->ModalResult = mrCancel;
  1151. }
  1152. //---------------------------------------------------------------------------
  1153. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1154. {
  1155. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1156. const char * Buffer = FHttp->ResponseRaw.c_str();
  1157. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1158. {
  1159. DownloadNotVerified();
  1160. }
  1161. UnicodeString Digest = Sha256(Buffer, Size);
  1162. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1163. {
  1164. DownloadNotVerified();
  1165. }
  1166. UnicodeString FileName = FUpdates.Results.DownloadUrl;
  1167. int P = FileName.Pos(L"?");
  1168. if (P > 0)
  1169. {
  1170. FileName.SetLength(P - 1);
  1171. }
  1172. P = FileName.LastDelimiter("/");
  1173. if (ALWAYS_TRUE(P > 0))
  1174. {
  1175. FileName.Delete(1, P);
  1176. }
  1177. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1178. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1179. UnicodeString SetupPath = SetupPathBase;
  1180. int Index = 0;
  1181. while (FileExists(SetupPath))
  1182. {
  1183. Index++;
  1184. SetupPath =
  1185. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1186. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1187. }
  1188. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1189. FileStream->Write(Buffer, Size);
  1190. FileStream.reset(NULL);
  1191. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1192. if (FUpdates.Results.OpenGettingStarted)
  1193. {
  1194. Params += L" /OpenGettingStarted";
  1195. }
  1196. if (!ExecuteShell(SetupPath, Params))
  1197. {
  1198. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (SetupPath)));
  1199. }
  1200. Configuration->Usage->Inc(L"UpdateRuns");
  1201. Application->Terminate();
  1202. }
  1203. //---------------------------------------------------------------------------
  1204. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1205. {
  1206. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1210. {
  1211. FDownloaded = Size;
  1212. Synchronize(UpdateProgress);
  1213. // Do not waste bandwidth, if something goes wrong
  1214. if (FDownloaded > FUpdates.Results.DownloadSize)
  1215. {
  1216. DownloadNotVerified();
  1217. }
  1218. if (Terminated)
  1219. {
  1220. Cancel = true;
  1221. }
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1225. {
  1226. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. void __fastcall TUpdateDownloadThread::ShowException()
  1230. {
  1231. assert(FException.get() != NULL);
  1232. ShowExtendedException(FException.get());
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1236. {
  1237. bool Result = !Terminated;
  1238. if (Result)
  1239. {
  1240. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1241. Terminate();
  1242. }
  1243. return Result;
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1247. {
  1248. if (CancelDownload())
  1249. {
  1250. Terminate();
  1251. WaitFor();
  1252. }
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. //---------------------------------------------------------------------------
  1256. class TUpdateDownloadData : public TComponent
  1257. {
  1258. public:
  1259. TUpdateDownloadThread * Thread;
  1260. __fastcall TUpdateDownloadData() :
  1261. TComponent(NULL)
  1262. {
  1263. }
  1264. virtual __fastcall ~TUpdateDownloadData()
  1265. {
  1266. // will stop the thread
  1267. delete Thread;
  1268. }
  1269. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1270. {
  1271. TComponent * Component = NOT_NULL(dynamic_cast<TComponent *>(Object));
  1272. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1273. return NOT_NULL(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1274. }
  1275. };
  1276. //---------------------------------------------------------------------------
  1277. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1278. {
  1279. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1280. if (UpdateDownloadData->Thread->CancelDownload())
  1281. {
  1282. Action = caNone;
  1283. }
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender)
  1287. {
  1288. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1289. TButton * Button = NOT_NULL(dynamic_cast<TButton *>(Sender));
  1290. TForm * Form = NOT_NULL(dynamic_cast<TForm *>(GetParentForm(Button)));
  1291. TPanel * Panel = CreateBlankPanel(Form);
  1292. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1293. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1294. ProgressBar->Top = 0;
  1295. ProgressBar->Left = 0;
  1296. ProgressBar->Width = Panel->Width;
  1297. ProgressBar->Parent = Panel;
  1298. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1299. Panel->Height = ProgressBar->Height;
  1300. InsertPanelToMessageDialog(Form, Panel);
  1301. Button->Enabled = false;
  1302. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1303. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1304. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1305. // The form becomes owner of the thread (via TUpdateDownloadData),
  1306. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1307. // But it gets done only after the form controls are gone, and the thread
  1308. // might try to access them meanwhile. So we stop the thread explicitly.
  1309. CancelButton->OnClick = Thread->CancelClicked;
  1310. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1311. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1312. Data->Thread = Thread;
  1313. Form->InsertComponent(Data);
  1314. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1315. if (!DownloadingUrl.IsEmpty())
  1316. {
  1317. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1318. }
  1319. DebugAssert(Form->OnClose == NULL);
  1320. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1321. Thread->Resume();
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1325. {
  1326. EnableAutomaticUpdates();
  1327. }
  1328. //---------------------------------------------------------------------------
  1329. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1330. {
  1331. TForm * Dialog = NOT_NULL(dynamic_cast<TForm *>(Sender));
  1332. TPanel * Panel = CreateBlankPanel(Dialog);
  1333. TStaticText * StaticText = new TStaticText(Panel);
  1334. StaticText->Top = 0;
  1335. StaticText->Left = 0;
  1336. StaticText->AutoSize = true;
  1337. StaticText->Caption = LoadStr(UPDATES_DONATE_LINK);
  1338. StaticText->Parent = Panel;
  1339. StaticText->OnClick = MakeMethod<TNotifyEvent>(NULL, UpdatesDonateClick);
  1340. StaticText->TabStop = true;
  1341. LinkLabel(StaticText);
  1342. Panel->Height = StaticText->Height;
  1343. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1344. // (what should not happen)
  1345. InsertPanelToMessageDialog(Dialog, Panel);
  1346. }
  1347. //---------------------------------------------------------------------------
  1348. bool __fastcall CheckForUpdates(bool CachedResults)
  1349. {
  1350. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1351. bool Result = false;
  1352. TOperationVisualizer Visualizer;
  1353. try
  1354. {
  1355. if (ActiveForm)
  1356. {
  1357. DebugAssert(ActiveForm->Enabled);
  1358. ActiveForm->Enabled = false;
  1359. }
  1360. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1361. bool Cached =
  1362. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1363. CachedResults;
  1364. if (!Cached)
  1365. {
  1366. DoQueryUpdates(WinConfiguration->CollectUsage);
  1367. // reread new data
  1368. Updates = WinConfiguration->Updates;
  1369. }
  1370. if (!Updates.ShownResults)
  1371. {
  1372. Updates.ShownResults = true;
  1373. WinConfiguration->Updates = Updates;
  1374. }
  1375. DebugAssert(Updates.HaveResults);
  1376. UnicodeString Message;
  1377. bool New;
  1378. TQueryType Type;
  1379. GetUpdatesMessage(Message, New, Type, true);
  1380. Configuration->Usage->Inc(L"UpdateDisplays");
  1381. if (New)
  1382. {
  1383. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1384. }
  1385. if (Updates.HaveResults &&
  1386. (double(Updates.Period) > 0) &&
  1387. // do not chow next check time, if we have new version info
  1388. !New)
  1389. {
  1390. Message += L"\n\n" +
  1391. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1392. }
  1393. int Answers = qaOK |
  1394. // show "what's new" button only when change list URL was not provided in results
  1395. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1396. FLAGMASK(New, qaCancel) |
  1397. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1398. TQueryButtonAlias Aliases[4];
  1399. Aliases[0].Button = qaYes;
  1400. if (Updates.Results.UrlButton.IsEmpty())
  1401. {
  1402. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1403. }
  1404. else
  1405. {
  1406. Aliases[0].Alias = Updates.Results.UrlButton;
  1407. }
  1408. Aliases[1].Button = qaAll;
  1409. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1410. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  1411. Aliases[2].Button = qaCancel;
  1412. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1413. // Used only when New == true, see AliasesCount below
  1414. Aliases[3].Button = qaOK;
  1415. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1416. if (!Updates.Results.DownloadUrl.IsEmpty())
  1417. {
  1418. Aliases[3].OnClick = MakeMethod<TNotifyEvent>(NULL, DownloadUpdate);
  1419. Aliases[3].ElevationRequired = true;
  1420. }
  1421. TMessageParams Params;
  1422. Params.Aliases = Aliases;
  1423. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1424. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1425. // alias "ok" button to "upgrade" only if we have new version
  1426. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1427. if (New)
  1428. {
  1429. Params.ImageName = L"Installer";
  1430. }
  1431. std::unique_ptr<TForm> Dialog(
  1432. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1433. if (New)
  1434. {
  1435. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1436. {
  1437. DebugAssert(Dialog->OnShow == NULL);
  1438. // InsertDonateLink need to be called only after MessageBrowser is created
  1439. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1440. }
  1441. }
  1442. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1443. switch (Answer)
  1444. {
  1445. case qaOK:
  1446. if (New)
  1447. {
  1448. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1449. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1450. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1451. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1452. OpenBrowser(UpgradeUrl);
  1453. Result = true;
  1454. }
  1455. break;
  1456. case qaYes:
  1457. OpenBrowser(Updates.Results.Url);
  1458. break;
  1459. case qaAll:
  1460. FAIL;
  1461. break;
  1462. }
  1463. }
  1464. __finally
  1465. {
  1466. if (ActiveForm)
  1467. {
  1468. ActiveForm->Enabled = true;
  1469. }
  1470. }
  1471. return Result;
  1472. }
  1473. //---------------------------------------------------------------------------
  1474. class TUpdateThread : public TCompThread
  1475. {
  1476. public:
  1477. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1478. protected:
  1479. virtual void __fastcall Execute();
  1480. TThreadMethod FOnUpdatesChecked;
  1481. };
  1482. //---------------------------------------------------------------------------
  1483. TUpdateThread * UpdateThread = NULL;
  1484. //---------------------------------------------------------------------------
  1485. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1486. TCompThread(false),
  1487. FOnUpdatesChecked(OnUpdatesChecked)
  1488. {
  1489. }
  1490. //---------------------------------------------------------------------------
  1491. void __fastcall TUpdateThread::Execute()
  1492. {
  1493. try
  1494. {
  1495. DoQueryUpdates(WinConfiguration->CollectUsage);
  1496. if (FOnUpdatesChecked != NULL)
  1497. {
  1498. Synchronize(FOnUpdatesChecked);
  1499. }
  1500. }
  1501. catch(...)
  1502. {
  1503. // ignore errors
  1504. }
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1508. {
  1509. DebugAssert(UpdateThread == NULL);
  1510. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. void __fastcall StopUpdateThread()
  1514. {
  1515. if (UpdateThread != NULL)
  1516. {
  1517. SAFE_DESTROY(UpdateThread);
  1518. }
  1519. }
  1520. //---------------------------------------------------------------------------
  1521. void __fastcall SetupInitialize()
  1522. {
  1523. WinConfiguration->UpdateJumpList();
  1524. }
  1525. //---------------------------------------------------------------------------
  1526. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1527. UnicodeString AdditionalParams, TStringList * Removed,
  1528. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1529. int IconIndex)
  1530. {
  1531. bool Result = false;
  1532. IObjectCollection * Collection = NULL;
  1533. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1534. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1535. {
  1536. try
  1537. {
  1538. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1539. int Count = 0;
  1540. for (int Index = 0; Index < Names->Count; Index++)
  1541. {
  1542. IShellLink * Link =
  1543. CreateDesktopSessionShortCut(
  1544. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1545. wchar_t Desc[2048];
  1546. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1547. {
  1548. if (Removed->IndexOf(Desc) < 0)
  1549. {
  1550. try
  1551. {
  1552. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1553. Count++;
  1554. }
  1555. __finally
  1556. {
  1557. Link->Release();
  1558. }
  1559. }
  1560. else
  1561. {
  1562. Names->Delete(Index);
  1563. Index--;
  1564. }
  1565. }
  1566. }
  1567. if (Count > 0)
  1568. {
  1569. IObjectArray * Array;
  1570. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1571. {
  1572. try
  1573. {
  1574. Result = SUCCEEDED(
  1575. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1576. }
  1577. __finally
  1578. {
  1579. Array->Release();
  1580. }
  1581. }
  1582. }
  1583. }
  1584. __finally
  1585. {
  1586. Collection->Release();
  1587. }
  1588. }
  1589. return Result;
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1593. {
  1594. ICustomDestinationList * DestinationList = NULL;
  1595. IObjectArray * RemovedArray = NULL;
  1596. TStringList * Removed = NULL;
  1597. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1598. try
  1599. {
  1600. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1601. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1602. {
  1603. unsigned int MinSlots;
  1604. unsigned int * PMinSlots = &MinSlots;
  1605. void ** PRemovedArray = (void**)&RemovedArray;
  1606. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1607. if (SUCCEEDED(Result) && ALWAYS_TRUE(RemovedArray != NULL))
  1608. {
  1609. Removed = new TStringList();
  1610. unsigned int RemovedCount;
  1611. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1612. {
  1613. RemovedCount = 0;
  1614. }
  1615. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1616. {
  1617. IShellLink * Link;
  1618. wchar_t Desc[2048];
  1619. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1620. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1621. {
  1622. Removed->Add(Desc);
  1623. }
  1624. }
  1625. AddJumpListCategory(
  1626. WorkspaceNames, L"", Removed, DestinationList,
  1627. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1628. AddJumpListCategory(
  1629. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1630. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1631. if (DestinationList != NULL)
  1632. {
  1633. DestinationList->CommitList();
  1634. }
  1635. }
  1636. }
  1637. }
  1638. __finally
  1639. {
  1640. SetErrorMode(OldErrMode);
  1641. if (RemovedArray != NULL)
  1642. {
  1643. RemovedArray->Release();
  1644. }
  1645. if (DestinationList != NULL)
  1646. {
  1647. DestinationList->Release();
  1648. }
  1649. delete Removed;
  1650. }
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. bool __fastcall AnyOtherInstanceOfSelf()
  1654. {
  1655. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1656. bool Result = false;
  1657. try
  1658. {
  1659. unsigned int Process = GetCurrentProcessId();
  1660. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1661. PROCESSENTRY32 ProcessEntry;
  1662. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1663. if (Process32First(Snapshot, &ProcessEntry))
  1664. {
  1665. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1666. {
  1667. // we should check if the process is running in the same session,
  1668. // but for that we probably need some special privileges
  1669. if ((Process != ProcessEntry.th32ProcessID) &&
  1670. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1671. {
  1672. Result = true;
  1673. }
  1674. }
  1675. }
  1676. }
  1677. __finally
  1678. {
  1679. CloseHandle(Snapshot);
  1680. }
  1681. return Result;
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1685. {
  1686. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1687. Registry->RootKey = RootKey;
  1688. bool Result =
  1689. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1690. if (Result)
  1691. {
  1692. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1693. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1694. Result =
  1695. !InstallPath.IsEmpty() &&
  1696. CompareFileName(ExePath, InstallPath);
  1697. }
  1698. return Result;
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. bool __fastcall IsInstalled()
  1702. {
  1703. return
  1704. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1705. DoIsInstalled(HKEY_CURRENT_USER);
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1709. {
  1710. std::unique_ptr<TStringList> List(new TStringList());
  1711. List->CommaText = Text;
  1712. return List.release();
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. UnicodeString __fastcall FirstUnshownTip()
  1716. {
  1717. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1718. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1719. Tips->CaseSensitive = false;
  1720. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1721. TipsSeen->CaseSensitive = false;
  1722. int LastTipSeen = -1;
  1723. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1724. {
  1725. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1726. if (TipIndex >= 0)
  1727. {
  1728. LastTipSeen = TipIndex;
  1729. }
  1730. }
  1731. UnicodeString Result;
  1732. if (LastTipSeen < Tips->Count - 1)
  1733. {
  1734. Result = Tips->Strings[LastTipSeen + 1];
  1735. }
  1736. return Result;
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. class TTipsData : public TComponent
  1740. {
  1741. public:
  1742. __fastcall TTipsData() :
  1743. TComponent(NULL)
  1744. {
  1745. }
  1746. int Index;
  1747. TStringList * Tips;
  1748. static TTipsData * __fastcall Retrieve(TObject * Object)
  1749. {
  1750. TComponent * Component = NOT_NULL(dynamic_cast<TComponent *>(Object));
  1751. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1752. return NOT_NULL(dynamic_cast<TTipsData *>(TipsDataComponent));
  1753. }
  1754. };
  1755. //---------------------------------------------------------------------------
  1756. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1757. {
  1758. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1759. }
  1760. //---------------------------------------------------------------------------
  1761. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1762. {
  1763. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1764. TButton * PrevButton = NOT_NULL(dynamic_cast<TButton *>(Form->FindComponent(L"Yes")));
  1765. PrevButton->Enabled = (TipsData->Index > 0);
  1766. TButton * NextButton = NOT_NULL(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1767. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1768. TPanel * Panel = NOT_NULL(dynamic_cast<TPanel *>(Form->FindComponent(L"Panel")));
  1769. TLabel * MessageLabel = NOT_NULL(dynamic_cast<TLabel *>(Panel->FindComponent(L"MainMessage")));
  1770. MessageLabel->Caption = TipsMessage(TipsData);
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1774. {
  1775. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1776. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1777. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. static void __fastcall TipSeen(const UnicodeString & Tip)
  1781. {
  1782. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1783. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1784. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1785. WinConfiguration->TipsShown = Now();
  1786. WinConfiguration->RunsSinceLastTip = 0;
  1787. // prevent parallel app instances showing the same tip
  1788. WinConfiguration->Save();
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender)
  1792. {
  1793. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1794. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1795. TipsData->Index += reinterpret_cast<int>(Data);
  1796. UpdateTipsForm(Form);
  1797. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1798. UnicodeString Url = TipUrl(TipsData);
  1799. NavigateMessageDialogToUrl(Form, Url);
  1800. }
  1801. //---------------------------------------------------------------------------
  1802. static void __fastcall ShowTip(bool AutoShow)
  1803. {
  1804. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1805. UnicodeString Tip = FirstUnshownTip();
  1806. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1807. Tips->CaseSensitive = false;
  1808. int Index;
  1809. if (Tip.IsEmpty())
  1810. {
  1811. Index = Tips->Count - 1;
  1812. Tip = Tips->Strings[Index];
  1813. }
  1814. else
  1815. {
  1816. Index = Tips->IndexOf(Tip);
  1817. }
  1818. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1819. TipsData->Name = TTipsData::QualifiedClassName();
  1820. TipsData->Index = Index;
  1821. TipsData->Tips = Tips.get();
  1822. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1823. TQueryButtonAlias Aliases[3];
  1824. Aliases[0].Button = qaYes;
  1825. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1826. Aliases[0].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1827. Aliases[1].Button = qaNo;
  1828. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1829. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1830. Aliases[2].Button = qaCancel;
  1831. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1832. TMessageParams Params;
  1833. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1834. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1835. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1836. Params.Aliases = Aliases;
  1837. Params.AliasesCount = LENOF(Aliases);
  1838. Params.ImageName = L"Bulb On n p";
  1839. if (AutoShow)
  1840. {
  1841. // Won't be used automatically as we have more than "OK button
  1842. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1843. Params.NeverAskAgainAnswer = qaCancel;
  1844. Params.Params |= mpNeverAskAgainCheck;
  1845. }
  1846. int Answers = qaYes | qaNo | qaCancel;
  1847. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1848. Dialog->InsertComponent(TipsData.release());
  1849. UpdateTipsForm(Dialog.get());
  1850. TipSeen(Tip);
  1851. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1852. if ((Result == qaNeverAskAgain) && ALWAYS_TRUE(AutoShow))
  1853. {
  1854. WinConfiguration->ShowTips = false;
  1855. }
  1856. WinConfiguration->Updates = Updates;
  1857. }
  1858. //---------------------------------------------------------------------------
  1859. void __fastcall AutoShowNewTip()
  1860. {
  1861. Configuration->Usage->Inc(L"TipsShownAuto");
  1862. ShowTip(true);
  1863. }
  1864. //---------------------------------------------------------------------------
  1865. void __fastcall ShowTips()
  1866. {
  1867. {
  1868. TOperationVisualizer Visualizer;
  1869. DoQueryUpdates(false);
  1870. }
  1871. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1872. {
  1873. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1874. }
  1875. Configuration->Usage->Inc(L"TipsShownCommand");
  1876. ShowTip(false);
  1877. }
  1878. //---------------------------------------------------------------------------
  1879. void __fastcall TipsUpdateStaticUsage()
  1880. {
  1881. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1882. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1883. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1884. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1885. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1886. }