12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090 |
- //---------------------------------------------------------------------------
- // Part of this code is
- // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #pragma hdrstop
- #include <stdio.h>
- #include <tchar.h>
- #include <shlobj.h>
- #include <tlhelp32.h>
- #include <Common.h>
- #include <CoreMain.h>
- #include <Exceptions.h>
- #include <TextsWin.h>
- #include <TextsCore.h>
- #include <HelpWin.h>
- #include <Http.h>
- #include <CompThread.hpp>
- #include <FileInfo.h>
- #include "WinConfiguration.h"
- #include "WinInterface.h"
- #include "Tools.h"
- #include "Setup.h"
- #include <StrUtils.hpp>
- #include "ProgParams.h"
- #include <Consts.hpp>
- #include <GUITools.h>
- #include <PuttyTools.h>
- #include <VCLCommon.h>
- #include <WebBrowserEx.hpp>
- #include <DateUtils.hpp>
- //---------------------------------------------------------------------------
- #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
- _T("Session Manager\\Environment")
- // when the PATH registry key is over aprox 2048 characters,
- // PATH as well as WINDIR variables are actually not set, breaking the system
- #define MAX_PATH_LEN 2000
- /* Command line options. */
- UnicodeString LastPathError;
- //---------------------------------------------------------------------------
- // Display the error "err_msg".
- void err_out(LPCTSTR err_msg)
- {
- LastPathError = err_msg;
- }
- //---------------------------------------------------------------------------
- // Display "base_err_msg" followed by the description of the system error
- // identified by "sys_err".
- void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
- {
- LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
- }
- //---------------------------------------------------------------------------
- // Works as "strcmp" but the comparison is not case sensitive.
- int tcharicmp(LPCTSTR str1, LPCTSTR str2){
- for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
- if (*str1 == L'\0')
- return 0;
- return tolower(*str1) - tolower(*str2);
- }
- //---------------------------------------------------------------------------
- // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
- // not present). The returned value must be freed with "free".
- LPTSTR unquote(LPCTSTR str){
- int last_pos;
- LPTSTR ret;
- size_t new_len;
- last_pos = _tcslen(str) - 1;
- if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
- new_len= (_tcslen(str) - 1);
- ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
- lstrcpyn(ret, &str[1], new_len);
- }
- else
- ret = _tcsdup(str);
- return ret;
- }
- //---------------------------------------------------------------------------
- // Find "what" in the ";" separated string "str" and returns a pointer to
- // the first letter of "what" in the string. If "next" is not "NULL" it
- // points to the first letter after "what" (excluding the trailing ";").
- // If "what" isn't find the functions returns "NULL".
- LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
- LPTSTR tok_buff;
- LPTSTR curr_tok;
- LPTSTR curr_tok_dup;
- BOOL path_eq;
- TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
- int pos = -1;
- LPTSTR ret;
- tok_buff = _tcsdup(str);
- curr_tok = _tcstok(tok_buff, _T(";"));
- while (pos == -1 && curr_tok){
- curr_tok_dup = unquote(curr_tok);
- path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
- GetShortPathName(curr_tok_dup, sh_path2,
- LENOF(sh_path2)) &&
- (tcharicmp(sh_path1, sh_path2) == 0);
- if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
- pos = curr_tok - tok_buff;
- }
- free(curr_tok_dup);
- curr_tok = _tcstok(NULL, _T(";"));
- if (pos != -1 && next){
- if (curr_tok)
- *next = str + (curr_tok - tok_buff);
- else
- *next = str + _tcslen(str);
- }
- }
- free(tok_buff);
- if (pos != -1)
- ret = str + pos;
- else
- ret = NULL;
- return ret;
- }
- //---------------------------------------------------------------------------
- void path_reg_propagate()
- {
- DWORD send_message_result;
- LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
- (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
- 5000, &send_message_result);
- if (ret != ERROR_SUCCESS && GetLastError() != 0)
- {
- err_out_sys(_T("Cannot propagate the new enviroment to ")
- _T("other processes. The new value will be ")
- _T("avaible after a reboot."), GetLastError());
- SimpleErrorDialog(LastPathError);
- LastPathError = L"";
- }
- }
- //---------------------------------------------------------------------------
- // Add "path" to the registry. Return "TRUE" if the path has been added or
- // was already in the registry, "FALSE" otherwise.
- BOOL add_path_reg(LPCTSTR path){
- HKEY key;
- LONG ret;
- DWORD data_size;
- LPTSTR reg_str;
- BOOL func_ret = TRUE;
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
- KEY_WRITE | KEY_READ, &key);
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot open registry."), ret);
- return FALSE;
- }
- RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
- data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
- includes '\0'. */
- reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
- ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
- &data_size);
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot read \"PATH\" key."), ret);
- func_ret = FALSE;
- }
- else{
- if (!find_reg_str(reg_str, path, NULL)){
- _tcscat(reg_str, _T(";"));
- _tcscat(reg_str, path);
- size_t len = _tcslen(reg_str);
- if (len >= MAX_PATH_LEN)
- {
- err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
- func_ret = FALSE;
- }
- else
- {
- ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
- (LPBYTE)reg_str,
- (_tcslen(reg_str) + 1) * sizeof(TCHAR));
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot write \"PATH\" key."), ret);
- func_ret = FALSE;
- }
- /* Is this needed to make the new key avaible? */
- RegFlushKey(key);
- SetLastError(0);
- path_reg_propagate();
- }
- }
- }
- RegCloseKey(key);
- free(reg_str);
- return func_ret;
- }
- //---------------------------------------------------------------------------
- // Removes "path" from the registry. Return "TRUE" if the path has been
- // removed or it wasn't in the registry, "FALSE" otherwise.
- BOOL remove_path_reg(LPCTSTR path){
- HKEY key;
- LONG ret;
- DWORD data_size;
- LPTSTR reg_str;
- LPTSTR reg_str2;
- BOOL func_ret = TRUE;
- LPTSTR next;
- LPTSTR del_part;
- int last_pos;
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
- KEY_WRITE | KEY_READ, &key);
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot open registry."), ret);
- return FALSE;
- }
- RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
- data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
- includes '\0'. */
- reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
- ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
- (LPBYTE)reg_str, &data_size);
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot read \"PATH\" key."), ret);
- func_ret = FALSE;
- }
- else{
- if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
- reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
- *del_part = '\0';
- _stprintf(reg_str2, _T("%s%s"), reg_str, next);
- last_pos = _tcslen(reg_str2) - 1;
- if (last_pos != -1 && reg_str2[last_pos] == ';')
- reg_str2[last_pos] = '\0';
- ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
- (LPBYTE)reg_str2,
- (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
- if (ret != ERROR_SUCCESS){
- err_out_sys(_T("Cannot write \"PATH\" key."), ret);
- func_ret = FALSE;
- }
- free(reg_str2);
- /* Is this needed to make the new key avaible? */
- RegFlushKey(key);
- SetLastError(0);
- path_reg_propagate();
- }
- }
- RegCloseKey(key);
- free(reg_str);
- return func_ret;
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- void __fastcall AddSearchPath(const UnicodeString Path)
- {
- if (!add_path_reg(Path.c_str()))
- {
- throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall RemoveSearchPath(const UnicodeString Path)
- {
- if (!remove_path_reg(Path.c_str()))
- {
- throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
- }
- }
- //---------------------------------------------------------------------------
- static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
- //---------------------------------------------------------------------------
- static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
- {
- if (Registry->OpenKey(Key, false))
- {
- std::unique_ptr<TStrings> List(new TStringList());
- Registry->GetValueNames(List.get());
- bool CanDelete = true;
- for (int Index = 0; CanDelete && (Index < List->Count); Index++)
- {
- UnicodeString ValueName = List->Strings[Index];
- if (!AllowRootValues)
- {
- CanDelete = false;
- }
- if ((ValueName != L"") &&
- (ValueName != L"URL Protocol") &&
- (ValueName != L"EditFlags") &&
- (ValueName != L"BrowserFlags"))
- {
- CanDelete = false;
- }
- }
- List->Clear();
- Registry->GetKeyNames(List.get());
- Registry->CloseKey();
- if (CanDelete)
- {
- for (int Index = 0; Index < List->Count; Index++)
- {
- DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
- }
- // will fail, if not all subkeys got removed
- Registry->DeleteKey(Key);
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterProtocol(TRegistry * Registry,
- const UnicodeString & Protocol, UnicodeString Description, bool Force)
- {
- if (Description.IsEmpty())
- {
- Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
- }
- UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
- if (Force || !Registry->KeyExists(ProtocolKey))
- {
- if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
- {
- Registry->WriteString(L"", Description);
- Registry->WriteString(L"URL Protocol", L"");
- Registry->WriteInteger(L"EditFlags", 0x02);
- Registry->WriteInteger(L"BrowserFlags", 0x08);
- if (Registry->OpenKey(L"DefaultIcon", true))
- {
- Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
- Registry->CloseKey();
- }
- else
- {
- Abort();
- }
- }
- else
- {
- Abort();
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterProtocol(TRegistry * Registry,
- const UnicodeString & Protocol)
- {
- DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
- }
- //---------------------------------------------------------------------------
- static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
- {
- std::unique_ptr<TRegistry> Registry(new TRegistry());
- Registry->Access = KEY_WRITE | KEY_READ;
- Registry->RootKey = RootKey;
- return Registry.release();
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
- const UnicodeString & Protocol, UnicodeString Description = L"")
- {
- std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
- RegisterProtocol(Registry.get(), Protocol, Description, true);
- if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
- Registry->OpenKey(L"shell", true) &&
- Registry->OpenKey(L"open", true) &&
- Registry->OpenKey(L"command", true))
- {
- Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
- Registry->CloseKey();
- }
- else
- {
- Abort();
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
- {
- try
- {
- RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
- // get rid of any HKCU registraction that would overrite the HKLM one
- std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
- if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
- {
- Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
- }
- }
- catch (Exception & E)
- {
- try
- {
- RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
- }
- catch(Exception & E)
- {
- throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
- const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
- {
- std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
- UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
- if (Registry->OpenKey(DefaultIconKey, false))
- {
- UnicodeString Value = Registry->ReadString(L"");
- UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
- if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
- {
- Registry->DeleteValue(L"");
- }
- Registry->CloseKey();
- DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
- }
- UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
- if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
- {
- UnicodeString Value = Registry->ReadString(L"");
- UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
- if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
- {
- Registry->DeleteValue(L"");
- }
- Registry->CloseKey();
- DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
- }
- if (UnregisterProtocol)
- {
- ::UnregisterProtocol(Registry.get(), Protocol);
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
- {
- UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
- UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
- {
- RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
- RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
- {
- UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
- UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
- }
- //---------------------------------------------------------------------------
- static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
- //---------------------------------------------------------------------------
- static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
- {
- // Register protocol, if it does not exist yet.
- // Prior to Windows 8, we need to register ourselves as legacy handler to
- // become the default handler. On Windows 8, it's automatic as long as no other
- // application is registered for the protocol (i.e. RegisterProtocol would be enough)
- RegisterAsUrlHandler(RootKey, Protocol);
- // see http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
- std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
- // create capabilities record
- // this has to be a separate branch from WinSCP one, as by its presence we
- // enforce registry storage usage, and the capabilities branch may exist
- // even if we are using INI file
- UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
- if (!Registry->OpenKey(CapabilitiesKey, true))
- {
- Abort();
- }
- UnicodeString Description = LoadStr(REGISTERED_APP_DESC2);
- Registry->WriteString(L"ApplicationDescription", Description);
- if (!Registry->OpenKey(L"UrlAssociations", true))
- {
- Abort();
- }
- Registry->WriteString(Protocol, GenericUrlHandler);
- Registry->CloseKey();
- // register application
- if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
- {
- Abort();
- }
- Registry->WriteString(AppNameString(), CapabilitiesKey);
- Registry->CloseKey();
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
- const UnicodeString & Protocol, bool ForceHandlerUnregistration)
- {
- std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
- // unregister the protocol
- UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
- // remove capabilities record
- UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
- UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
- if (Registry->OpenKey(UrlAssociationsKey, false))
- {
- Registry->DeleteValue(Protocol);
- Registry->CloseKey();
- DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
- }
- if (Registry->OpenKey(CapabilitiesKey, false))
- {
- if (!Registry->HasSubKeys())
- {
- Registry->DeleteValue(L"ApplicationDescription");
- }
- Registry->CloseKey();
- DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
- }
- if (!Registry->KeyExists(CapabilitiesKey))
- {
- // unregister application
- if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
- {
- Registry->DeleteValue(AppNameString());
- Registry->CloseKey();
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
- {
- // register URL handler, if it does not exist yet
- RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
- RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
- RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
- RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
- RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
- RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
- RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
- // deliberately not including WebDAV/http,
- // it's unlikely that anyone would like to change http handler
- // to non-browser application
- }
- //---------------------------------------------------------------------------
- static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
- {
- UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
- UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
- UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
- UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
- UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
- UnregisterProtocolForDefaultPrograms(RootKey, SshProtocol, ForceHandlerUnregistration);
- // we should not really need the "force" flag here, but why not
- UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
- }
- //---------------------------------------------------------------------------
- static void __fastcall RegisterForDefaultPrograms()
- {
- try
- {
- RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
- // make sure we unregister any legacy protocol handler for CU,
- // this is needed for Windows Vista+7
- UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
- }
- catch (Exception & E)
- {
- try
- {
- RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
- }
- catch (Exception & E)
- {
- throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall NotifyChangedAssociations()
- {
- SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
- }
- //---------------------------------------------------------------------------
- void __fastcall RegisterForDefaultProtocols()
- {
- if (IsWinVista())
- {
- RegisterForDefaultPrograms();
- }
- else
- {
- RegisterAsNonBrowserUrlHandler(UnicodeString());
- }
- RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
- RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
- RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
- RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
- RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase());
- RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase());
- RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
- NotifyChangedAssociations();
- }
- //---------------------------------------------------------------------------
- void __fastcall UnregisterForProtocols()
- {
- UnregisterAsUrlHandlers(UnicodeString(), false);
- UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase(), true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase(), true);
- UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
- UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
- UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
- NotifyChangedAssociations();
- }
- //---------------------------------------------------------------------------
- void __fastcall LaunchAdvancedAssociationUI()
- {
- DebugAssert(IsWinVista());
- RegisterForDefaultPrograms();
- NotifyChangedAssociations();
- // sleep recommended by http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
- Sleep(1000);
- if (IsWin10())
- {
- ExecuteShell(L"control.exe", L"/name Microsoft.DefaultPrograms");
- }
- else
- {
- IApplicationAssociationRegistrationUI * AppAssocRegUI;
- HRESULT Result =
- CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
- NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
- if (SUCCEEDED(Result))
- {
- AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
- AppAssocRegUI->Release();
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TemporaryDirectoryCleanup()
- {
- bool Continue = true;
- TStrings * Folders = NULL;
- try
- {
- if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
- {
- Folders = WinConfiguration->FindTemporaryFolders();
- Continue = (Folders != NULL);
- if (Continue)
- {
- Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
- TQueryButtonAlias Aliases[1];
- Aliases[0].Button = qaRetry;
- Aliases[0].Alias = LoadStr(OPEN_BUTTON);
- TMessageParams Params(mpNeverAskAgainCheck);
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- unsigned int Answer = MoreMessageDialog(
- FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
- qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
- if (Answer == qaNeverAskAgain)
- {
- WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
- Answer = qaYes;
- }
- else if (Answer == qaRetry)
- {
- for (int Index = 0; Index < Folders->Count; Index++)
- {
- ShellExecute(Application->Handle, NULL,
- Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
- }
- }
- Continue = (Answer == qaYes);
- }
- }
- if (Continue)
- {
- try
- {
- WinConfiguration->CleanupTemporaryFolders(Folders);
- }
- catch (Exception &E)
- {
- ShowExtendedException(&E);
- }
- }
- }
- __finally
- {
- delete Folders;
- }
- }
- //-------------------------------------------- -------------------------------
- UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
- {
- int MajorVer = Version / (10000*100*100);
- int MinorVer = (Version % (10000*100*100)) / (10000*100);
- int Release = (Version % (10000*100)) / (10000);
- UnicodeString Result;
- if (Release > 0)
- {
- Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
- }
- else
- {
- Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall CampaignUrl(UnicodeString URL)
- {
- int CurrentCompoundVer = Configuration->CompoundVersion;
- UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
- // Beware that these parameters may get truncated if URL is too long,
- // such as with ERROR_REPORT_URL2
- UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
- return AppendUrlParams(URL, Params);
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall GetUsageData()
- {
- return Configuration->Usage->Serialize();
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall ProgramUrl(UnicodeString URL)
- {
- TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
- UnicodeString CurrentVersionStr =
- FORMAT(L"%d.%d.%d.%d",
- (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
- HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
- UnicodeString Params =
- FORMAT(L"v=%s&lang=%s&isinstalled=%d",
- (CurrentVersionStr,
- GUIConfiguration->LocaleHex,
- int(IsInstalled())));
- if (Configuration->IsUnofficial)
- {
- Params += L"&unofficial=1";
- }
- return AppendUrlParams(URL, Params);
- }
- //---------------------------------------------------------------------------
- static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
- {
- bool Beta;
- if (WinConfiguration->IsBeta)
- {
- Beta = true;
- }
- else
- {
- switch (WinConfiguration->Updates.BetaVersions)
- {
- case asAuto:
- Beta = WinConfiguration->AnyBetaInVersionHistory;
- break;
- case asOn:
- Beta = true;
- break;
- default:
- Beta = false;
- break;
- }
- }
- if (Beta || Force)
- {
- URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
- }
- return URL;
- }
- //---------------------------------------------------------------------------
- static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
- {
- std::unique_ptr<THttp> Http(new THttp());
- UnicodeString ProxyHost;
- int ProxyPort = 0;
- switch (Updates.ConnectionType)
- {
- case ctAuto:
- if (AutodetectProxy(ProxyHost, ProxyPort))
- {
- Configuration->Usage->Inc(L"UpdateProxyAutodetected");
- }
- break;
- case ctProxy:
- ProxyHost = Updates.ProxyHost;
- ProxyPort = Updates.ProxyPort;
- Configuration->Usage->Inc(L"UpdateProxyManual");
- break;
- }
- Http->ProxyHost = ProxyHost;
- Http->ProxyPort = ProxyPort;
- return Http.release();
- }
- //---------------------------------------------------------------------------
- THttp * __fastcall CreateHttp()
- {
- return CreateHttp(WinConfiguration->Updates);
- }
- //---------------------------------------------------------------------------
- static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
- {
- bool Complete = false;
- UnicodeString Response;
- THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
- try
- {
- UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
- URL = WantBetaUrl(URL, false);
- URL += L"&dotnet=" + Updates.DotNetVersion;
- URL += L"&console=" + Updates.ConsoleVersion;
- UnicodeString LocaleVersion = WinConfiguration->LocaleVersion();
- if (!LocaleVersion.IsEmpty())
- {
- URL += L"&localever=" + LocaleVersion;
- URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
- }
- if (!Updates.AuthenticationEmail.IsEmpty())
- {
- RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
- URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
- }
- CheckForUpdatesHTTP->URL = URL;
- // sanity check
- CheckForUpdatesHTTP->ResponseLimit = 102400;
- if (CollectUsage)
- {
- UnicodeString Usage = GetUsageData();
- CheckForUpdatesHTTP->Post(Usage);
- }
- else
- {
- CheckForUpdatesHTTP->Get();
- }
- Response = CheckForUpdatesHTTP->Response;
- }
- __finally
- {
- delete CheckForUpdatesHTTP;
- }
- int CurrentCompoundVer = Configuration->CompoundVersion;
- bool Changed = !Updates.HaveResults;
- Updates.LastCheck = Now();
- Updates.HaveResults = true;
- TUpdatesData PrevResults = Updates.Results;
- Updates.Results.Reset();
- Updates.Results.ForVersion = CurrentCompoundVer;
- while (!Response.IsEmpty())
- {
- UnicodeString Line = CutToChar(Response, L'\n', false);
- UnicodeString Name = CutToChar(Line, L'=', false);
- if (AnsiSameText(Name, "Version"))
- {
- int NewVersion = StrToCompoundVersion(Line);
- Changed |= (NewVersion != PrevResults.Version);
- if (NewVersion <= CurrentCompoundVer)
- {
- NewVersion = 0;
- }
- Updates.Results.Version = NewVersion;
- Complete = true;
- }
- else if (AnsiSameText(Name, L"Message"))
- {
- Changed |= (PrevResults.Message != Line);
- Updates.Results.Message = Line;
- }
- else if (AnsiSameText(Name, L"Critical"))
- {
- bool NewCritical = (StrToIntDef(Line, 0) != 0);
- Changed |= (PrevResults.Critical != NewCritical);
- Updates.Results.Critical = NewCritical;
- }
- else if (AnsiSameText(Name, L"Release"))
- {
- Changed |= (PrevResults.Release != Line);
- Updates.Results.Release = Line;
- }
- else if (AnsiSameText(Name, L"Disabled"))
- {
- bool NewDisabled = (StrToIntDef(Line, 0) != 0);
- Changed |= (PrevResults.Disabled != NewDisabled);
- Updates.Results.Disabled = NewDisabled;
- Complete = true;
- }
- else if (AnsiSameText(Name, L"Url"))
- {
- Changed |= (PrevResults.Url != Line);
- Updates.Results.Url = Line;
- }
- else if (AnsiSameText(Name, L"UrlButton"))
- {
- Changed |= (PrevResults.UrlButton != Line);
- Updates.Results.UrlButton = Line;
- }
- else if (AnsiSameText(Name, L"NewsUrl"))
- {
- Changed |= (PrevResults.NewsUrl != Line);
- Updates.Results.NewsUrl = Line;
- }
- else if (AnsiSameText(Name, L"NewsSize"))
- {
- TSize NewsSize;
- NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
- NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
- Changed |= (PrevResults.NewsSize != NewsSize);
- Updates.Results.NewsSize = NewsSize;
- }
- else if (AnsiSameText(Name, L"DownloadUrl"))
- {
- Changed |= (PrevResults.DownloadUrl != Line);
- Updates.Results.DownloadUrl = Line;
- }
- else if (AnsiSameText(Name, L"DownloadSize"))
- {
- Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
- }
- else if (AnsiSameText(Name, L"DownloadSha256"))
- {
- Updates.Results.DownloadSha256 = Line;
- }
- else if (AnsiSameText(Name, L"AuthenticationError"))
- {
- Changed |= (PrevResults.AuthenticationError != Line);
- Updates.Results.AuthenticationError = Line;
- }
- else if (AnsiSameText(Name, L"OpenGettingStarted"))
- {
- Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
- }
- else if (AnsiSameText(Name, L"DownloadingUrl"))
- {
- Updates.Results.DownloadingUrl = Line;
- }
- else if (AnsiSameText(Name, L"TipsSize"))
- {
- TSize TipsSize;
- TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
- TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
- Updates.Results.TipsSize = TipsSize;
- }
- else if (AnsiSameText(Name, L"TipsUrl"))
- {
- Updates.Results.TipsUrl = Line;
- }
- else if (AnsiSameText(Name, L"Tips"))
- {
- Updates.Results.Tips = Line;
- }
- else if (AnsiSameText(Name, L"TipsIntervalDays"))
- {
- int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
- if (TipsIntervalDays < 0)
- {
- TipsIntervalDays = Updates.Results.TipsIntervalDays;
- }
- Updates.Results.TipsIntervalDays = TipsIntervalDays;
- }
- else if (AnsiSameText(Name, L"TipsIntervalRuns"))
- {
- int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
- if (TipsIntervalRuns < 0)
- {
- TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
- }
- Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
- }
- }
- if (Changed)
- {
- Updates.ShownResults = false;
- }
- return Complete;
- }
- //---------------------------------------------------------------------------
- bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
- {
- return DoQueryUpdates(Updates, false);
- }
- //---------------------------------------------------------------------------
- static void __fastcall DoQueryUpdates(bool CollectUsage)
- {
- try
- {
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- bool Complete = DoQueryUpdates(Updates, CollectUsage);
- WinConfiguration->Updates = Updates;
- if (!Complete)
- {
- EXCEPTION;
- }
- Configuration->Usage->Reset();
- Configuration->Usage->Inc(L"UpdateChecksSucceeded");
- }
- catch(Exception & E)
- {
- Configuration->Usage->Inc(L"UpdateChecksFailed");
- throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
- {
- Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
- Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
- Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
- Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
- Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
- Message = ReplaceStr(Message, L"|", L"\n");
- return Message;
- }
- //---------------------------------------------------------------------------
- void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
- TQueryType & Type, bool Force)
- {
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- DebugAssert(Updates.HaveResults);
- if (Updates.HaveResults)
- {
- if (Updates.Results.Disabled)
- {
- New = false;
- if (Force)
- {
- Message = LoadStr(UPDATE_DISABLED);
- }
- }
- else
- {
- New = (Updates.Results.Version > 0);
- if (New)
- {
- UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
- if (!Updates.Results.Release.IsEmpty())
- {
- Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
- }
- Message = FMTLOAD(NEW_VERSION4, (Version));
- }
- else
- {
- Message = LoadStr(NO_NEW_VERSION);
- }
- }
- if (!Message.IsEmpty())
- {
- Message = MainInstructions(Message);
- }
- if (!Updates.Results.Message.IsEmpty())
- {
- Message +=
- FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
- }
- if (!Updates.Results.AuthenticationError.IsEmpty())
- {
- Message +=
- FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
- }
- Type = (Updates.Results.Critical ? qtWarning : qtInformation);
- }
- else
- {
- New = false;
- }
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
- {
- return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
- }
- //---------------------------------------------------------------------------
- void __fastcall EnableAutomaticUpdates()
- {
- OpenBrowser(GetEnableAutomaticUpdatesUrl());
- }
- //---------------------------------------------------------------------------
- static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
- {
- Configuration->Usage->Inc(L"UpdateHistoryOpens");
- OpenBrowser(LoadStr(HISTORY_URL));
- }
- //---------------------------------------------------------------------------
- static int __fastcall DownloadSizeToProgress(__int64 Size)
- {
- return static_cast<int>(Size / 1024);
- }
- //---------------------------------------------------------------------------
- class TUpdateDownloadThread : public TCompThread
- {
- public:
- __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
- virtual __fastcall ~TUpdateDownloadThread();
- void __fastcall CancelClicked(TObject * Sender);
- bool __fastcall CancelDownload();
- __property bool Done = { read = FDone };
- protected:
- virtual void __fastcall Execute();
- void __fastcall UpdateDownloaded();
- void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
- void __fastcall UpdateProgress();
- void __fastcall ShowException();
- void __fastcall DownloadNotVerified();
- void __fastcall CancelForm();
- private:
- TCustomForm * FForm;
- TProgressBar * FProgressBar;
- __int64 FDownloaded;
- std::unique_ptr<Exception> FException;
- std::unique_ptr<THttp> FHttp;
- TUpdatesConfiguration FUpdates;
- bool FDone;
- };
- //---------------------------------------------------------------------------
- __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
- TCompThread(true)
- {
- // cache, as the progress bar miht be destroyed already when
- // we need the form at the end of Execute()
- FForm = GetParentForm(ProgressBar);
- FProgressBar = ProgressBar;
- // cache to prevent concurrency
- FUpdates = WinConfiguration->Updates;
- FDone = false;
- }
- //---------------------------------------------------------------------------
- __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
- {
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::Execute()
- {
- try
- {
- bool Retried = false;
- bool Retry;
- do
- {
- Retry = false;
- try
- {
- FDownloaded = 0;
- FHttp.reset(CreateHttp(FUpdates));
- FHttp->URL = FUpdates.Results.DownloadUrl;
- FHttp->OnDownload = HttpDownload;
- FHttp->Get();
- }
- catch (EAbort &)
- {
- throw;
- }
- catch (Exception & E)
- {
- // The original URL failed, try to get a fresh one and retry
- if (!Retried)
- {
- try
- {
- // Check if new update data (URL particlarly) is available
- if (QueryUpdates(FUpdates) &&
- !FUpdates.Results.DownloadUrl.IsEmpty())
- {
- Retry = true;
- Retried = true;
- }
- }
- catch (...)
- {
- }
- }
- if (!Retry)
- {
- Configuration->Usage->Inc(L"UpdateFailuresDownload");
- throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
- }
- }
- }
- while (Retry);
- Synchronize(UpdateDownloaded);
- }
- catch (EAbort &)
- {
- // noop
- }
- catch (Exception & E)
- {
- Configuration->Usage->Inc(L"UpdateFailures");
- FException.reset(CloneException(&E));
- Synchronize(ShowException);
- }
- FDone = true;
- Synchronize(CancelForm);
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::CancelForm()
- {
- FForm->ModalResult = mrCancel;
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::UpdateDownloaded()
- {
- size_t Size = static_cast<size_t>(FHttp->ResponseLength);
- const char * Buffer = FHttp->ResponseRaw.c_str();
- if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
- {
- DownloadNotVerified();
- }
- UnicodeString Digest = Sha256(Buffer, Size);
- if (!SameText(FUpdates.Results.DownloadSha256, Digest))
- {
- DownloadNotVerified();
- }
- UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
- UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
- UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
- UnicodeString SetupPath = SetupPathBase;
- int Index = 0;
- while (FileExists(SetupPath))
- {
- Index++;
- SetupPath =
- ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
- FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
- }
- std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
- FileStream->Write(Buffer, Size);
- FileStream.reset(NULL);
- UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
- if (FUpdates.Results.OpenGettingStarted)
- {
- Params += L" /OpenGettingStarted";
- }
- if (!ExecuteShell(SetupPath, Params))
- {
- throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (SetupPath)));
- }
- Configuration->Usage->Inc(L"UpdateRuns");
- Application->Terminate();
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::DownloadNotVerified()
- {
- throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
- {
- FDownloaded = Size;
- Synchronize(UpdateProgress);
- // Do not waste bandwidth, if something goes wrong
- if (FDownloaded > FUpdates.Results.DownloadSize)
- {
- DownloadNotVerified();
- }
- if (Terminated)
- {
- Cancel = true;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::UpdateProgress()
- {
- FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::ShowException()
- {
- DebugAssert(FException.get() != NULL);
- ShowExtendedException(FException.get());
- }
- //---------------------------------------------------------------------------
- bool __fastcall TUpdateDownloadThread::CancelDownload()
- {
- bool Result = !Terminated;
- if (Result)
- {
- Configuration->Usage->Inc(L"UpdateDownloadCancels");
- Terminate();
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
- {
- if (CancelDownload())
- {
- WaitFor();
- }
- }
- //---------------------------------------------------------------------------
- //---------------------------------------------------------------------------
- class TUpdateDownloadData : public TComponent
- {
- public:
- TUpdateDownloadThread * Thread;
- __fastcall TUpdateDownloadData() :
- TComponent(NULL)
- {
- }
- virtual __fastcall ~TUpdateDownloadData()
- {
- // will stop the thread
- delete Thread;
- }
- static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
- {
- TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
- TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
- return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
- }
- };
- //---------------------------------------------------------------------------
- static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
- {
- TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
- // If the form was closed by CancelForm at the end of the thread, do nothing
- if (!UpdateDownloadData->Thread->Done)
- {
- // Otherwise the form is closing because X was clicked (or maybe Cancel).
- // May this should actually call CancelClicked?
- if (UpdateDownloadData->Thread->CancelDownload())
- {
- Action = caNone;
- }
- }
- }
- //---------------------------------------------------------------------------
- static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender)
- {
- Configuration->Usage->Inc(L"UpdateDownloadStarts");
- TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
- TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
- TPanel * Panel = CreateBlankPanel(Form);
- TProgressBar * ProgressBar = new TProgressBar(Panel);
- ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
- ProgressBar->Top = 0;
- ProgressBar->Left = 0;
- ProgressBar->Width = Panel->Width;
- ProgressBar->Parent = Panel;
- ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
- Panel->Height = ProgressBar->Height;
- InsertPanelToMessageDialog(Form, Panel);
- Button->Enabled = false;
- TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
- CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
- TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
- // The form becomes owner of the thread (via TUpdateDownloadData),
- // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
- // But it gets done only after the form controls are gone, and the thread
- // might try to access them meanwhile. So we stop the thread explicitly.
- CancelButton->OnClick = Thread->CancelClicked;
- TUpdateDownloadData * Data = new TUpdateDownloadData();
- Data->Name = TUpdateDownloadData::QualifiedClassName();
- Data->Thread = Thread;
- Form->InsertComponent(Data);
- UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
- if (!DownloadingUrl.IsEmpty())
- {
- NavigateMessageDialogToUrl(Form, DownloadingUrl);
- }
- DebugAssert(Form->OnClose == NULL);
- Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
- Thread->Resume();
- }
- //---------------------------------------------------------------------------
- static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
- {
- EnableAutomaticUpdates();
- }
- //---------------------------------------------------------------------------
- static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
- {
- TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
- TPanel * Panel = CreateBlankPanel(Dialog);
- TStaticText * StaticText = new TStaticText(Panel);
- StaticText->Top = 0;
- StaticText->Left = 0;
- StaticText->AutoSize = true;
- StaticText->Caption = LoadStr(UPDATES_DONATE_LINK);
- StaticText->Parent = Panel;
- StaticText->OnClick = MakeMethod<TNotifyEvent>(NULL, UpdatesDonateClick);
- StaticText->TabStop = true;
- LinkLabel(StaticText);
- Panel->Height = StaticText->Height;
- // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
- // (what should not happen)
- InsertPanelToMessageDialog(Dialog, Panel);
- }
- //---------------------------------------------------------------------------
- bool __fastcall CheckForUpdates(bool CachedResults)
- {
- TCustomForm * ActiveForm = Screen->ActiveCustomForm;
- bool Result = false;
- TOperationVisualizer Visualizer;
- try
- {
- if (ActiveForm)
- {
- DebugAssert(ActiveForm->Enabled);
- ActiveForm->Enabled = false;
- }
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- bool Cached =
- Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
- CachedResults;
- if (!Cached)
- {
- DoQueryUpdates(WinConfiguration->CollectUsage);
- // reread new data
- Updates = WinConfiguration->Updates;
- }
- if (!Updates.ShownResults)
- {
- Updates.ShownResults = true;
- WinConfiguration->Updates = Updates;
- }
- DebugAssert(Updates.HaveResults);
- UnicodeString Message;
- bool New;
- TQueryType Type;
- GetUpdatesMessage(Message, New, Type, true);
- Configuration->Usage->Inc(L"UpdateDisplays");
- if (New)
- {
- Configuration->Usage->Inc(L"UpdateDisplaysNew");
- }
- if (Updates.HaveResults &&
- (double(Updates.Period) > 0) &&
- // do not chow next check time, if we have new version info
- !New)
- {
- Message += L"\n\n" +
- FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
- }
- int Answers = qaOK |
- // show "what's new" button only when change list URL was not provided in results
- FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
- FLAGMASK(New, qaCancel) |
- FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
- TQueryButtonAlias Aliases[4];
- Aliases[0].Button = qaYes;
- if (Updates.Results.UrlButton.IsEmpty())
- {
- Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
- }
- else
- {
- Aliases[0].Alias = Updates.Results.UrlButton;
- }
- Aliases[1].Button = qaAll;
- Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
- Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
- Aliases[2].Button = qaCancel;
- Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
- // Used only when New == true, see AliasesCount below
- Aliases[3].Button = qaOK;
- Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
- if (!Updates.Results.DownloadUrl.IsEmpty())
- {
- Aliases[3].OnClick = MakeMethod<TNotifyEvent>(NULL, DownloadUpdate);
- Aliases[3].ElevationRequired = true;
- }
- TMessageParams Params;
- Params.Aliases = Aliases;
- Params.MoreMessagesUrl = Updates.Results.NewsUrl;
- Params.MoreMessagesSize = Updates.Results.NewsSize;
- // alias "ok" button to "upgrade" only if we have new version
- Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
- Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
- if (New)
- {
- Params.ImageName = L"Installer";
- }
- std::unique_ptr<TForm> Dialog(
- CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
- if (New)
- {
- if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
- {
- DebugAssert(Dialog->OnShow == NULL);
- // InsertDonateLink need to be called only after MessageBrowser is created
- Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
- }
- }
- unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
- switch (Answer)
- {
- case qaOK:
- if (New)
- {
- Configuration->Usage->Inc(L"UpdateDownloadOpens");
- UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
- UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
- UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
- OpenBrowser(UpgradeUrl);
- Result = true;
- }
- break;
- case qaYes:
- OpenBrowser(Updates.Results.Url);
- break;
- case qaAll:
- DebugFail();
- break;
- }
- }
- __finally
- {
- if (ActiveForm)
- {
- ActiveForm->Enabled = true;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- class TUpdateThread : public TCompThread
- {
- public:
- __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
- protected:
- virtual void __fastcall Execute();
- TThreadMethod FOnUpdatesChecked;
- };
- //---------------------------------------------------------------------------
- TUpdateThread * UpdateThread = NULL;
- //---------------------------------------------------------------------------
- __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
- TCompThread(false),
- FOnUpdatesChecked(OnUpdatesChecked)
- {
- }
- //---------------------------------------------------------------------------
- void __fastcall TUpdateThread::Execute()
- {
- try
- {
- DoQueryUpdates(WinConfiguration->CollectUsage);
- if (FOnUpdatesChecked != NULL)
- {
- Synchronize(FOnUpdatesChecked);
- }
- }
- catch(...)
- {
- // ignore errors
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
- {
- DebugAssert(UpdateThread == NULL);
- UpdateThread = new TUpdateThread(OnUpdatesChecked);
- }
- //---------------------------------------------------------------------------
- void __fastcall StopUpdateThread()
- {
- if (UpdateThread != NULL)
- {
- SAFE_DESTROY(UpdateThread);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall SetupInitialize()
- {
- WinConfiguration->UpdateJumpList();
- }
- //---------------------------------------------------------------------------
- static bool __fastcall AddJumpListCategory(TStrings * Names,
- UnicodeString AdditionalParams, TStringList * Removed,
- ICustomDestinationList * DestinationList, UnicodeString CategoryName,
- int IconIndex)
- {
- bool Result = false;
- IObjectCollection * Collection = NULL;
- if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
- CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
- {
- try
- {
- AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
- int Count = 0;
- for (int Index = 0; Index < Names->Count; Index++)
- {
- IShellLink * Link =
- CreateDesktopSessionShortCut(
- Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
- wchar_t Desc[2048];
- if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
- {
- if (Removed->IndexOf(Desc) < 0)
- {
- try
- {
- DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
- Count++;
- }
- __finally
- {
- Link->Release();
- }
- }
- else
- {
- Names->Delete(Index);
- Index--;
- }
- }
- }
- if (Count > 0)
- {
- IObjectArray * Array;
- if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
- {
- try
- {
- Result = SUCCEEDED(
- DestinationList->AppendCategory(CategoryName.c_str(), Array));
- }
- __finally
- {
- Array->Release();
- }
- }
- }
- }
- __finally
- {
- Collection->Release();
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
- {
- ICustomDestinationList * DestinationList = NULL;
- IObjectArray * RemovedArray = NULL;
- TStringList * Removed = NULL;
- int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
- try
- {
- if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
- CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
- {
- unsigned int MinSlots;
- unsigned int * PMinSlots = &MinSlots;
- void ** PRemovedArray = (void**)&RemovedArray;
- HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
- if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
- {
- Removed = new TStringList();
- unsigned int RemovedCount;
- if (FAILED(RemovedArray->GetCount(&RemovedCount)))
- {
- RemovedCount = 0;
- }
- for (unsigned int Index = 0; Index < RemovedCount; Index++)
- {
- IShellLink * Link;
- wchar_t Desc[2048];
- if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
- SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
- {
- Removed->Add(Desc);
- }
- }
- AddJumpListCategory(
- WorkspaceNames, L"", Removed, DestinationList,
- LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
- AddJumpListCategory(
- SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
- LoadStr(JUMPLIST_RECENT), SITE_ICON);
- if (DestinationList != NULL)
- {
- DestinationList->CommitList();
- }
- }
- }
- }
- __finally
- {
- SetErrorMode(OldErrMode);
- if (RemovedArray != NULL)
- {
- RemovedArray->Release();
- }
- if (DestinationList != NULL)
- {
- DestinationList->Release();
- }
- delete Removed;
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall AnyOtherInstanceOfSelf()
- {
- HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
- bool Result = false;
- try
- {
- unsigned int Process = GetCurrentProcessId();
- UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
- PROCESSENTRY32 ProcessEntry;
- ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
- if (Process32First(Snapshot, &ProcessEntry))
- {
- while (!Result && Process32Next(Snapshot, &ProcessEntry))
- {
- // we should check if the process is running in the same session,
- // but for that we probably need some special privileges
- if ((Process != ProcessEntry.th32ProcessID) &&
- SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
- {
- Result = true;
- }
- }
- }
- }
- __finally
- {
- CloseHandle(Snapshot);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- static bool __fastcall DoIsInstalled(HKEY RootKey)
- {
- std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
- Registry->RootKey = RootKey;
- bool Result =
- Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
- if (Result)
- {
- UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
- UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
- Result =
- !InstallPath.IsEmpty() &&
- CompareFileName(ExePath, InstallPath);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- bool __fastcall IsInstalled()
- {
- return
- DoIsInstalled(HKEY_LOCAL_MACHINE) ||
- DoIsInstalled(HKEY_CURRENT_USER);
- }
- //---------------------------------------------------------------------------
- static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
- {
- std::unique_ptr<TStringList> List(new TStringList());
- List->CommaText = Text;
- return List.release();
- }
- //---------------------------------------------------------------------------
- UnicodeString __fastcall FirstUnshownTip()
- {
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
- Tips->CaseSensitive = false;
- std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
- TipsSeen->CaseSensitive = false;
- int LastTipSeen = -1;
- for (int Index = 0; Index < TipsSeen->Count; Index++)
- {
- int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
- if (TipIndex >= 0)
- {
- LastTipSeen = TipIndex;
- }
- }
- UnicodeString Result;
- if (LastTipSeen < Tips->Count - 1)
- {
- Result = Tips->Strings[LastTipSeen + 1];
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- class TTipsData : public TComponent
- {
- public:
- __fastcall TTipsData() :
- TComponent(NULL)
- {
- }
- int Index;
- TStringList * Tips;
- static TTipsData * __fastcall Retrieve(TObject * Object)
- {
- TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
- TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
- return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
- }
- };
- //---------------------------------------------------------------------------
- static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
- {
- return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
- }
- //---------------------------------------------------------------------------
- static void __fastcall UpdateTipsForm(TCustomForm * Form)
- {
- TTipsData * TipsData = TTipsData::Retrieve(Form);
- TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"Yes")));
- PrevButton->Enabled = (TipsData->Index > 0);
- TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
- NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
- TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Form->FindComponent(L"Panel")));
- TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(Panel->FindComponent(L"MainMessage")));
- MessageLabel->Caption = TipsMessage(TipsData);
- }
- //---------------------------------------------------------------------------
- static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
- {
- UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
- UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
- return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
- }
- //---------------------------------------------------------------------------
- static void __fastcall TipSeen(const UnicodeString & Tip)
- {
- std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
- TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
- WinConfiguration->TipsSeen = TipsSeen->CommaText;
- WinConfiguration->TipsShown = Now();
- WinConfiguration->RunsSinceLastTip = 0;
- // prevent parallel app instances showing the same tip
- WinConfiguration->Save();
- }
- //---------------------------------------------------------------------------
- static void __fastcall PrevNextTipClick(void * Data, TObject * Sender)
- {
- TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
- TTipsData * TipsData = TTipsData::Retrieve(Form);
- TipsData->Index += reinterpret_cast<int>(Data);
- UpdateTipsForm(Form);
- TipSeen(TipsData->Tips->Strings[TipsData->Index]);
- UnicodeString Url = TipUrl(TipsData);
- NavigateMessageDialogToUrl(Form, Url);
- }
- //---------------------------------------------------------------------------
- static void __fastcall ShowTip(bool AutoShow)
- {
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- UnicodeString Tip = FirstUnshownTip();
- std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
- Tips->CaseSensitive = false;
- int Index;
- if (Tip.IsEmpty())
- {
- Index = Tips->Count - 1;
- Tip = Tips->Strings[Index];
- }
- else
- {
- Index = Tips->IndexOf(Tip);
- }
- std::unique_ptr<TTipsData> TipsData(new TTipsData());
- TipsData->Name = TTipsData::QualifiedClassName();
- TipsData->Index = Index;
- TipsData->Tips = Tips.get();
- UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
- TQueryButtonAlias Aliases[3];
- Aliases[0].Button = qaYes;
- Aliases[0].Alias = LoadStr(PREV_BUTTON);
- Aliases[0].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
- Aliases[1].Button = qaNo;
- Aliases[1].Alias = LoadStr(NEXT_BUTTON);
- Aliases[1].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
- Aliases[2].Button = qaCancel;
- Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
- TMessageParams Params;
- Params.CustomCaption = LoadStr(TIPS_TITLE);
- Params.MoreMessagesSize = Updates.Results.TipsSize;
- Params.MoreMessagesUrl = TipUrl(TipsData.get());
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- Params.ImageName = L"Bulb On n p";
- if (AutoShow)
- {
- // Won't be used automatically as we have more than the "OK" button
- Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
- Params.NeverAskAgainAnswer = qaCancel;
- Params.Params |= mpNeverAskAgainCheck;
- }
- int Answers = qaYes | qaNo | qaCancel;
- std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
- Dialog->InsertComponent(TipsData.release());
- UpdateTipsForm(Dialog.get());
- TipSeen(Tip);
- unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
- if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
- {
- WinConfiguration->ShowTips = false;
- }
- WinConfiguration->Updates = Updates;
- }
- //---------------------------------------------------------------------------
- void __fastcall AutoShowNewTip()
- {
- Configuration->Usage->Inc(L"TipsShownAuto");
- ShowTip(true);
- }
- //---------------------------------------------------------------------------
- void __fastcall ShowTips()
- {
- {
- TOperationVisualizer Visualizer;
- DoQueryUpdates(false);
- }
- if (WinConfiguration->Updates.Results.Tips.IsEmpty())
- {
- throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
- }
- Configuration->Usage->Inc(L"TipsShownCommand");
- ShowTip(false);
- }
- //---------------------------------------------------------------------------
- void __fastcall TipsUpdateStaticUsage()
- {
- TUpdatesConfiguration Updates = WinConfiguration->Updates;
- std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
- Configuration->Usage->Set(L"TipsCount", Tips->Count);
- std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
- Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
- }
|