WinMain.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <CoreMain.h>
  5. #include <TextsWin.h>
  6. #include <TextsCore.h>
  7. #include <HelpWin.h>
  8. #include "CustomScpExplorer.h"
  9. #include "TerminalManager.h"
  10. #include "NonVisual.h"
  11. #include "Glyphs.h"
  12. #include "ProgParams.h"
  13. #include "Setup.h"
  14. #include "WinConfiguration.h"
  15. #include "GUITools.h"
  16. #include "Tools.h"
  17. #include "WinApi.h"
  18. #include <DateUtils.hpp>
  19. #include <StrUtils.hpp>
  20. #include <Xml.Win.msxmldom.hpp>
  21. //---------------------------------------------------------------------------
  22. #pragma package(smart_init)
  23. //---------------------------------------------------------------------------
  24. UnicodeString GetFolderOrWorkspaceName(const UnicodeString & SessionName)
  25. {
  26. UnicodeString FolderOrWorkspaceName = DecodeUrlChars(SessionName);
  27. UnicodeString Result;
  28. if (StoredSessions->IsFolderOrWorkspace(FolderOrWorkspaceName))
  29. {
  30. Result = FolderOrWorkspaceName;
  31. }
  32. return Result;
  33. }
  34. //---------------------------------------------------------------------------
  35. void __fastcall GetLoginData(UnicodeString SessionName, TOptions * Options,
  36. TObjectList * DataList, UnicodeString & DownloadFile, bool NeedSession, TForm * LinkedForm, int Flags)
  37. {
  38. bool DefaultsOnly = false;
  39. UnicodeString FolderOrWorkspaceName = GetFolderOrWorkspaceName(SessionName);
  40. if (!FolderOrWorkspaceName.IsEmpty())
  41. {
  42. StoredSessions->GetFolderOrWorkspace(FolderOrWorkspaceName, DataList);
  43. }
  44. else
  45. {
  46. TSessionData * SessionData =
  47. StoredSessions->ParseUrl(SessionName, Options, DefaultsOnly, &DownloadFile, NULL, NULL, Flags);
  48. DataList->Add(SessionData);
  49. if (DataList->Count == 1)
  50. {
  51. TSessionData * SessionData = DebugNotNull(dynamic_cast<TSessionData *>(DataList->Items[0]));
  52. if (SessionData->SaveOnly)
  53. {
  54. Configuration->Usage->Inc(L"CommandLineSessionSave");
  55. TSessionData * SavedSession = DoSaveSession(SessionData, NULL, true, NULL);
  56. if (SavedSession == NULL)
  57. {
  58. Abort();
  59. }
  60. WinConfiguration->LastStoredSession = SavedSession->Name;
  61. DataList->Clear();
  62. }
  63. else if (!SessionData->PuttyProtocol.IsEmpty())
  64. {
  65. OpenSessionInPutty(SessionData);
  66. DataList->Clear();
  67. Abort();
  68. }
  69. }
  70. }
  71. if (DefaultsOnly && !NeedSession)
  72. {
  73. // No URL specified on command-line and no explicit command-line parameter
  74. // that requires session was specified => noop
  75. DataList->Clear();
  76. }
  77. else if ((DataList->Count == 0) ||
  78. !dynamic_cast<TSessionData *>(DataList->Items[0])->CanOpen ||
  79. DefaultsOnly)
  80. {
  81. // Note that GetFolderOrWorkspace never returns sites that !CanOpen,
  82. // so we should not get here with more than one site.
  83. // Though we should be good, if we ever do.
  84. // We get here when:
  85. // - we need session for explicit command-line operation
  86. // - after we handle "save" URL.
  87. // - the specified session does not contain enough information to open [= not even hostname nor local browser]
  88. DebugAssert(DataList->Count <= 1);
  89. if (!DoLoginDialog(DataList, LinkedForm))
  90. {
  91. Abort();
  92. }
  93. }
  94. }
  95. //---------------------------------------------------------------------------
  96. int GetCommandLineParseUrlFlags(TProgramParams * Params)
  97. {
  98. return
  99. pufAllowStoredSiteWithProtocol |
  100. FLAGMASK(!CheckSafe(Params), pufUnsafe);
  101. }
  102. //---------------------------------------------------------------------------
  103. void __fastcall Upload(TTerminal * Terminal, TStrings * FileList, int UseDefaults)
  104. {
  105. UnicodeString TargetDirectory;
  106. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  107. TargetDirectory = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  108. std::unique_ptr<TSessionData> Data(Terminal->SessionData->Clone());
  109. Terminal->FillSessionDataForCode(Data.get());
  110. int Options = coDisableQueue;
  111. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  112. if ((UseDefaults == 0) ||
  113. DoCopyDialog(true, false, FileList, TargetDirectory, &CopyParam, Options,
  114. CopyParamAttrs, Data.get(), NULL, UseDefaults))
  115. {
  116. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  117. CopyParam.OnceDoneOperation = odoDisconnect;
  118. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  119. Terminal->CopyToRemote(FileList, TargetDirectory, &CopyParam, 0, NULL);
  120. }
  121. }
  122. //---------------------------------------------------------------------------
  123. void __fastcall Download(TTerminal * Terminal, const UnicodeString FileName, int UseDefaults, bool & Browse, UnicodeString & BrowseFile)
  124. {
  125. TRemoteFile * File = NULL;
  126. try
  127. {
  128. Terminal->ExceptionOnFail = true;
  129. try
  130. {
  131. File = Terminal->ReadFile(FileName);
  132. }
  133. __finally
  134. {
  135. Terminal->ExceptionOnFail = false;
  136. }
  137. File->FullFileName = FileName;
  138. UnicodeString LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  139. if (LocalDirectory.IsEmpty())
  140. {
  141. LocalDirectory = GetPersonalFolder();
  142. }
  143. UnicodeString TargetDirectory = IncludeTrailingBackslash(LocalDirectory);
  144. TGUICopyParamType CopyParam = GUIConfiguration->DefaultCopyParam;
  145. UnicodeString DisplayName = File->FileName;
  146. bool CustomDisplayName =
  147. !File->DisplayName.IsEmpty() &&
  148. (File->DisplayName != DisplayName);
  149. if (CustomDisplayName)
  150. {
  151. DisplayName = File->DisplayName;
  152. }
  153. UnicodeString FriendyFileName = UnixIncludeTrailingBackslash(UnixExtractFilePath(FileName)) + DisplayName;
  154. std::unique_ptr<TStrings> FileListFriendly(new TStringList());
  155. FileListFriendly->AddObject(FriendyFileName, File);
  156. int Options = coDisableQueue | coBrowse;
  157. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Download;
  158. int OutputOptions = 0;
  159. if ((UseDefaults == 0) ||
  160. DoCopyDialog(false, false, FileListFriendly.get(), TargetDirectory, &CopyParam,
  161. Options, CopyParamAttrs, NULL, &OutputOptions, UseDefaults))
  162. {
  163. if (FLAGCLEAR(OutputOptions, cooBrowse))
  164. {
  165. // Setting parameter overrides only now, otherwise the dialog would present the parametes as non-default
  166. if (CustomDisplayName)
  167. {
  168. // Set only now, so that it is not redundantly displayed on the copy dialog.
  169. // We should escape the * and ?'s.
  170. CopyParam.FileMask = DisplayName;
  171. }
  172. CopyParam.OnceDoneOperation = odoDisconnect;
  173. std::unique_ptr<TStrings> FileList(new TStringList());
  174. FileList->AddObject(FileName, File);
  175. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList.get());
  176. Terminal->CopyToLocal(FileList.get(), TargetDirectory, &CopyParam, 0, NULL);
  177. }
  178. else
  179. {
  180. UnicodeString Directory = UnixExtractFilePath(FileName);
  181. BrowseFile = UnixExtractFileName(FileName);
  182. Browse = true;
  183. Terminal->AutoReadDirectory = true;
  184. Terminal->ChangeDirectory(Directory);
  185. }
  186. }
  187. else
  188. {
  189. Abort();
  190. }
  191. }
  192. __finally
  193. {
  194. delete File;
  195. }
  196. }
  197. //---------------------------------------------------------------------------
  198. void __fastcall Edit(TCustomScpExplorerForm * ScpExplorer, TStrings * FileList)
  199. {
  200. ScpExplorer->StandaloneEdit(FileList->Strings[0]);
  201. Abort();
  202. }
  203. //---------------------------------------------------------------------------
  204. void __fastcall SynchronizeDirectories(
  205. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams,
  206. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory)
  207. {
  208. if (CommandParams->Count >= 1)
  209. {
  210. LocalDirectory = CommandParams->Strings[0];
  211. }
  212. else if (!Terminal->SessionData->LocalDirectory.IsEmpty())
  213. {
  214. LocalDirectory = Terminal->SessionData->LocalDirectoryExpanded;
  215. }
  216. else
  217. {
  218. LocalDirectory = ScpExplorer->DefaultDownloadTargetDirectory();
  219. }
  220. if (CommandParams->Count >= 2)
  221. {
  222. RemoteDirectory = CommandParams->Strings[1];
  223. }
  224. else
  225. {
  226. RemoteDirectory = Terminal->CurrentDirectory;
  227. }
  228. }
  229. //---------------------------------------------------------------------------
  230. void __fastcall FullSynchronize(
  231. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  232. {
  233. UnicodeString LocalDirectory;
  234. UnicodeString RemoteDirectory;
  235. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  236. bool SaveMode = true;
  237. // bit ugly
  238. TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode;
  239. int Params = GUIConfiguration->SynchronizeParams;
  240. // Undocumented syntax for "Start in New Window"
  241. if (CommandParams->Count >= 4)
  242. {
  243. Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode);
  244. Params = StrToIntDef(CommandParams->Strings[3], Params);
  245. }
  246. int Result =
  247. ScpExplorer->DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, UseDefaults);
  248. if ((Result >= 0) && SaveMode)
  249. {
  250. GUIConfiguration->SynchronizeMode = Mode;
  251. }
  252. Abort();
  253. }
  254. //---------------------------------------------------------------------------
  255. void __fastcall Synchronize(
  256. TTerminal * Terminal, TCustomScpExplorerForm * ScpExplorer, TStrings * CommandParams, int UseDefaults)
  257. {
  258. UnicodeString LocalDirectory;
  259. UnicodeString RemoteDirectory;
  260. SynchronizeDirectories(Terminal, ScpExplorer, CommandParams, LocalDirectory, RemoteDirectory);
  261. // Undocumented syntax for "Start in New Window"
  262. if (CommandParams->Count >= 4)
  263. {
  264. GUIConfiguration->SynchronizeParams = StrToIntDef(CommandParams->Strings[2], -1);
  265. GUIConfiguration->SynchronizeOptions = StrToIntDef(CommandParams->Strings[3], -1);
  266. Configuration->DontSave();
  267. }
  268. ScpExplorer->DoSynchronizeDirectories(LocalDirectory, RemoteDirectory, UseDefaults);
  269. Abort();
  270. }
  271. //---------------------------------------------------------------------------
  272. void __fastcall ImportSitesIfAny()
  273. {
  274. if (!WinConfiguration->AutoImportedFromPuttyOrFilezilla)
  275. {
  276. bool AnyPuttySession = GUIConfiguration->AnyPuttySessionForImport(StoredSessions);
  277. bool AnyFilezillaSession = GUIConfiguration->AnyFilezillaSessionForImport(StoredSessions);
  278. if (AnyPuttySession || AnyFilezillaSession)
  279. {
  280. UnicodeString PuttySource = LoadStrPart(IMPORT_SESSIONS2, 2);
  281. UnicodeString FilezillaSource = LoadStrPart(IMPORT_SESSIONS2, 3);
  282. UnicodeString Source;
  283. if (AnyPuttySession && AnyFilezillaSession)
  284. {
  285. Source = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 4), (PuttySource, FilezillaSource));
  286. }
  287. else if (AnyPuttySession)
  288. {
  289. Source = PuttySource;
  290. }
  291. else if (AnyFilezillaSession)
  292. {
  293. Source = FilezillaSource;
  294. }
  295. else
  296. {
  297. DebugFail();
  298. }
  299. UnicodeString Message = FORMAT(LoadStrPart(IMPORT_SESSIONS2, 1), (Source));
  300. if (MessageDialog(Message, qtConfirmation,
  301. qaYes | qaNo, HELP_IMPORT_SESSIONS) == qaYes)
  302. {
  303. DoImportSessionsDialog(NULL);
  304. }
  305. WinConfiguration->AutoImportedFromPuttyOrFilezilla = true;
  306. }
  307. }
  308. }
  309. //---------------------------------------------------------------------------
  310. void __fastcall Usage(UnicodeString Param)
  311. {
  312. while (!Param.IsEmpty())
  313. {
  314. UnicodeString Pair = CutToChar(Param, L',', true);
  315. if (!Pair.IsEmpty())
  316. {
  317. if (Pair[Pair.Length()] == L'+')
  318. {
  319. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  320. Configuration->Usage->Inc(Key);
  321. }
  322. else if (Pair[Pair.Length()] == L'@')
  323. {
  324. UnicodeString Key = Pair.SubString(1, Pair.Length() - 1).Trim();
  325. UnicodeString Value;
  326. if (SameText(Key, L"InstallationParentProcess"))
  327. {
  328. Value = GetAncestorProcessName(3).LowerCase();
  329. }
  330. else
  331. {
  332. Value = L"err-unknown-key";
  333. }
  334. Configuration->Usage->Set(Key, Value);
  335. }
  336. else
  337. {
  338. UnicodeString Key = CutToChar(Pair, L':', true);
  339. UnicodeString Value = Pair.Trim();
  340. Configuration->Usage->Set(Key, Value);
  341. }
  342. }
  343. }
  344. }
  345. //---------------------------------------------------------------------------
  346. void __fastcall RecordWrapperVersions(UnicodeString ConsoleVersion, UnicodeString DotNetVersion)
  347. {
  348. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  349. if (!DotNetVersion.IsEmpty())
  350. {
  351. Updates.DotNetVersion = DotNetVersion;
  352. }
  353. if (!ConsoleVersion.IsEmpty())
  354. {
  355. Updates.ConsoleVersion = ConsoleVersion;
  356. }
  357. WinConfiguration->Updates = Updates;
  358. if ((WinConfiguration->Storage == stNul) &&
  359. WinConfiguration->TrySetSafeStorage())
  360. {
  361. try
  362. {
  363. THierarchicalStorage * Storage = WinConfiguration->CreateConfigStorage();
  364. try
  365. {
  366. Storage->AccessMode = smReadWrite;
  367. if (Storage->OpenSubKey(Configuration->ConfigurationSubKey, true) &&
  368. Storage->OpenSubKeyPath(L"Interface\\Updates", true))
  369. {
  370. if (!DotNetVersion.IsEmpty())
  371. {
  372. Storage->WriteString(L"DotNetVersion", DotNetVersion);
  373. }
  374. if (!ConsoleVersion.IsEmpty())
  375. {
  376. Storage->WriteString(L"ConsoleVersion", ConsoleVersion);
  377. }
  378. }
  379. }
  380. __finally
  381. {
  382. delete Storage;
  383. }
  384. }
  385. __finally
  386. {
  387. Configuration->SetNulStorage();
  388. }
  389. }
  390. }
  391. //---------------------------------------------------------------------------
  392. static UnicodeString ColorToRGBStr(TColor Color)
  393. {
  394. int RGB = ColorToRGB(Color);
  395. int R = GetRValue(RGB);
  396. int G = GetGValue(RGB);
  397. int B = GetBValue(RGB);
  398. UnicodeString Result = FORMAT(L"%.2x%.2x%.2x", (R, G, B));
  399. return Result;
  400. }
  401. //---------------------------------------------------------------------------
  402. class TStartupThread : public TSimpleThread
  403. {
  404. public:
  405. TStartupThread();
  406. virtual __fastcall ~TStartupThread();
  407. int GetStartupSeconds();
  408. virtual void __fastcall Terminate();
  409. protected:
  410. virtual void __fastcall Execute();
  411. int FMilliseconds;
  412. bool FStop;
  413. };
  414. //---------------------------------------------------------------------------
  415. TStartupThread::TStartupThread()
  416. {
  417. FMilliseconds = 0;
  418. FStop = false;
  419. Start();
  420. }
  421. //---------------------------------------------------------------------------
  422. __fastcall TStartupThread::~TStartupThread()
  423. {
  424. Close();
  425. }
  426. //---------------------------------------------------------------------------
  427. int TStartupThread::GetStartupSeconds()
  428. {
  429. DebugAssert(!FStop);
  430. return FMilliseconds / 1000;
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TStartupThread::Terminate()
  434. {
  435. FStop = true;
  436. }
  437. //---------------------------------------------------------------------------
  438. void __fastcall TStartupThread::Execute()
  439. {
  440. while (!FStop)
  441. {
  442. const int Step = 250;
  443. Sleep(Step);
  444. FMilliseconds += Step;
  445. }
  446. }
  447. //---------------------------------------------------------------------------
  448. TStartupThread * StartupThread(new TStartupThread());
  449. TDateTime Started(Now());
  450. TDateTime LastStartupStartupSequence(Now());
  451. UnicodeString StartupSequence;
  452. int LifetimeRuns = -1;
  453. //---------------------------------------------------------------------------
  454. void InterfaceStartDontMeasure()
  455. {
  456. Started = TDateTime();
  457. StartupThread->Terminate();
  458. }
  459. //---------------------------------------------------------------------------
  460. void AddStartupSequence(const UnicodeString & Tag)
  461. {
  462. int SequenceTensOfSecond = static_cast<int>(MilliSecondsBetween(Now(), LastStartupStartupSequence) / 100);
  463. LastStartupStartupSequence = Now();
  464. AddToList(StartupSequence, FORMAT(L"%s:%d", (Tag, SequenceTensOfSecond)), L",");
  465. }
  466. //---------------------------------------------------------------------------
  467. void InterfaceStarted()
  468. {
  469. if ((Started != TDateTime()) && (LifetimeRuns > 0))
  470. {
  471. // deliberate downcast
  472. int StartupSeconds = static_cast<int>(SecondsBetween(Now(), Started));
  473. int StartupSecondsReal = DebugNotNull(StartupThread)->GetStartupSeconds();
  474. if (LifetimeRuns == 1)
  475. {
  476. Configuration->Usage->Set(L"StartupSeconds1", StartupSeconds);
  477. }
  478. else if (LifetimeRuns == 2)
  479. {
  480. Configuration->Usage->Set(L"StartupSeconds2", StartupSeconds);
  481. }
  482. Configuration->Usage->Set(L"StartupSecondsLast", StartupSeconds);
  483. Configuration->Usage->Set(L"StartupSecondsLastReal", StartupSecondsReal);
  484. AddStartupSequence(L"I");
  485. Configuration->Usage->Set(L"StartupSequenceLast", StartupSequence);
  486. }
  487. StartupThread->Terminate();
  488. }
  489. //---------------------------------------------------------------------------
  490. void __fastcall UpdateStaticUsage()
  491. {
  492. Configuration->Usage->Inc(L"Runs");
  493. Configuration->Usage->UpdateCurrentVersion();
  494. Configuration->Usage->Set(L"WindowsVersion", (WindowsVersionLong()));
  495. Configuration->Usage->Set(L"WindowsProductName", (WindowsProductName()));
  496. DWORD Type;
  497. GetWindowsProductType(Type);
  498. Configuration->Usage->Set(L"WindowsProductType", (static_cast<int>(Type)));
  499. Configuration->Usage->Set(L"Windows64", IsWin64());
  500. Configuration->Usage->Set(L"UWP", IsUWP());
  501. Configuration->Usage->Set(L"PackageName", GetPackageName());
  502. Configuration->Usage->Set(L"DefaultLocale",
  503. // See TGUIConfiguration::GetAppliedLocaleHex()
  504. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  505. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  506. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  507. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  508. bool PixelsPerInchSystemDiffers = false;
  509. bool PixelsPerInchMonitorsDiffer = false;
  510. bool PixelsPerInchAxesDiffer = false;
  511. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  512. if (ShCoreLibrary != NULL)
  513. {
  514. GetDpiForMonitorProc GetDpiForMonitor =
  515. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  516. if (GetDpiForMonitor != NULL)
  517. {
  518. unsigned int PrimaryDpiX;
  519. unsigned int PrimaryDpiY;
  520. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  521. {
  522. unsigned int DpiX;
  523. unsigned int DpiY;
  524. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  525. if (DpiX != DpiY)
  526. {
  527. PixelsPerInchAxesDiffer = true;
  528. }
  529. if (Index == 0)
  530. {
  531. PrimaryDpiX = DpiX;
  532. PrimaryDpiY = DpiY;
  533. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  534. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  535. {
  536. PixelsPerInchSystemDiffers = true;
  537. }
  538. }
  539. else
  540. {
  541. if ((DpiX != PrimaryDpiX) ||
  542. (DpiY != PrimaryDpiY))
  543. {
  544. PixelsPerInchMonitorsDiffer = true;
  545. }
  546. }
  547. }
  548. }
  549. }
  550. if (PixelsPerInchSystemDiffers)
  551. {
  552. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  553. }
  554. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  555. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  556. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  557. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  558. HDC DC = GetDC(NULL);
  559. int Planes = GetDeviceCaps(DC, PLANES);
  560. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  561. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  562. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  563. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  564. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  565. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  566. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  567. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  568. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  569. UnicodeString ProgramsFolder;
  570. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  571. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  572. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  573. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  574. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  575. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  576. Configuration->Usage->Set(L"IsInstalledMsi", IsInstalledMsi());
  577. Configuration->Usage->Set(L"Wine", IsWine());
  578. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  579. Configuration->Usage->Set(L"NetCoreVersion", GetNetCoreVersionStr());
  580. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  581. Configuration->Usage->Set(L"PwshVersion", GetPowerShellCoreVersionStr());
  582. bool MsXmlInstalled;
  583. try
  584. {
  585. TMSXMLDOMDocumentFactory::CreateDOMDocument();
  586. MsXmlInstalled = true;
  587. }
  588. catch (...)
  589. {
  590. MsXmlInstalled = false;
  591. }
  592. Configuration->Usage->Set(L"MsXmlInstalled", MsXmlInstalled);
  593. UnicodeString ParentProcess = GetAncestorProcessName();
  594. // do not record the installer as a parent process
  595. if (!ParentProcess.IsEmpty() &&
  596. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  597. {
  598. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  599. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  600. ParentProcessesList->CommaText = ParentProcesses;
  601. ParentProcessesList->Add(ParentProcess.LowerCase());
  602. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  603. }
  604. WinConfiguration->UpdateStaticUsage();
  605. }
  606. //---------------------------------------------------------------------------
  607. void __fastcall UpdateFinalStaticUsage()
  608. {
  609. CoreUpdateFinalStaticUsage();
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall MaintenanceTask()
  613. {
  614. CoreMaintenanceTask();
  615. InterfaceStartDontMeasure();
  616. }
  617. //---------------------------------------------------------------------------
  618. typedef std::vector<HWND> THandles;
  619. typedef std::map<unsigned long, THandles> TProcesses;
  620. //---------------------------------------------------------------------------
  621. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  622. {
  623. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  624. // This should be optimized to query class name already here
  625. unsigned long ProcessId;
  626. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  627. {
  628. Processes[ProcessId].push_back(Handle);
  629. }
  630. return TRUE;
  631. }
  632. //---------------------------------------------------------------------------
  633. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  634. {
  635. COPYDATASTRUCT CopyData;
  636. CopyData.cbData = sizeof(Message);
  637. CopyData.lpData = &Message;
  638. LRESULT SendResult =
  639. SendMessage(Window, WM_COPYDATA,
  640. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  641. bool Result = (SendResult > 0);
  642. return Result;
  643. }
  644. //---------------------------------------------------------------------------
  645. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  646. {
  647. TProcesses Processes;
  648. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  649. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  650. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  651. {
  652. TCopyDataMessage Message;
  653. Message.Command = TCopyDataMessage::MainWindowCheck;
  654. TProcesses::const_iterator ProcessI = Processes.begin();
  655. while (ProcessI != Processes.end())
  656. {
  657. HWND HiddenWindow = NULL;
  658. THandles::const_iterator WindowI = ProcessI->second.begin();
  659. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  660. {
  661. wchar_t ClassName[1024];
  662. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  663. {
  664. NULL_TERMINATE(ClassName);
  665. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  666. {
  667. HiddenWindow = *WindowI;
  668. }
  669. }
  670. WindowI++;
  671. }
  672. if (HiddenWindow != NULL)
  673. {
  674. WindowI = ProcessI->second.begin();
  675. while (WindowI != ProcessI->second.end())
  676. {
  677. if (*WindowI != HiddenWindow) // optimization
  678. {
  679. if (SendCopyDataMessage(*WindowI, Message))
  680. {
  681. OtherInstances.push_back(*WindowI);
  682. break;
  683. }
  684. }
  685. WindowI++;
  686. }
  687. }
  688. ProcessI++;
  689. }
  690. }
  691. }
  692. //---------------------------------------------------------------------------
  693. bool __fastcall SendToAnotherInstance()
  694. {
  695. THandles OtherInstances;
  696. FindOtherInstances(OtherInstances);
  697. bool Result = false;
  698. THandles::const_iterator I = OtherInstances.begin();
  699. while (!Result && (I != OtherInstances.end()))
  700. {
  701. HWND Handle = *I;
  702. TCopyDataMessage Message;
  703. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  704. if (SendCopyDataMessage(Handle, Message))
  705. {
  706. // Restore window, if minimized
  707. ShowWindow(Handle, SW_RESTORE);
  708. // bring it to foreground
  709. SetForegroundWindow(Handle);
  710. Message.Command = TCopyDataMessage::CommandCommandLine;
  711. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  712. NULL_TERMINATE(Message.CommandLine);
  713. Result = SendCopyDataMessage(Handle, Message);
  714. }
  715. I++;
  716. }
  717. return Result;
  718. }
  719. //---------------------------------------------------------------------------
  720. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  721. {
  722. THandles OtherInstances;
  723. FindOtherInstances(OtherInstances);
  724. THandles::const_iterator I = OtherInstances.begin();
  725. while (I != OtherInstances.end())
  726. {
  727. HWND Handle = *I;
  728. TCopyDataMessage Message;
  729. Message.Command = TCopyDataMessage::RefreshPanel;
  730. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  731. NULL_TERMINATE(Message.Refresh.Session);
  732. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  733. NULL_TERMINATE(Message.Refresh.Path);
  734. SendCopyDataMessage(Handle, Message);
  735. I++;
  736. }
  737. }
  738. //---------------------------------------------------------------------------
  739. bool __fastcall ShowUpdatesIfAvailable()
  740. {
  741. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  742. int CurrentCompoundVer = Configuration->CompoundVersion;
  743. bool NoPopup = true;
  744. bool Result =
  745. !IsUWP() &&
  746. Updates.ShowOnStartup &&
  747. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  748. !Updates.Results.Disabled &&
  749. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  750. !Updates.ShownResults;
  751. if (Result)
  752. {
  753. Configuration->Usage->Inc(L"UpdateStartup");
  754. Result = CheckForUpdates(true);
  755. if (Result)
  756. {
  757. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  758. }
  759. NoPopup = false;
  760. }
  761. else if (WinConfiguration->ShowTips)
  762. {
  763. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  764. if ((Days >= Updates.Results.TipsIntervalDays) &&
  765. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  766. {
  767. UnicodeString Tip = FirstUnshownTip();
  768. if (!Tip.IsEmpty())
  769. {
  770. AutoShowNewTip();
  771. NoPopup = false;
  772. }
  773. else
  774. {
  775. Configuration->Usage->Inc(L"TipsNoUnseen");
  776. }
  777. }
  778. }
  779. if (NoPopup)
  780. {
  781. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  782. }
  783. return Result;
  784. }
  785. //---------------------------------------------------------------------------
  786. int __fastcall Execute()
  787. {
  788. std::unique_ptr<TStartupThread> StartupThreadOwner(StartupThread);
  789. AddStartupSequence(L"X");
  790. DebugAssert(StoredSessions);
  791. TProgramParams * Params = TProgramParams::Instance();
  792. DebugAssert(Params);
  793. // do not flash message boxes on startup
  794. SetOnForeground(true);
  795. // let installer know, that some instance of application is running
  796. CreateMutex(NULL, False, AppName.c_str());
  797. bool OnlyInstance = (GetLastError() == 0);
  798. UpdateStaticUsage();
  799. UnicodeString KeyFile;
  800. if (Params->FindSwitch(PRIVATEKEY_SWITCH, KeyFile))
  801. {
  802. WinConfiguration->DefaultKeyFile = KeyFile;
  803. }
  804. UnicodeString ConsoleVersion;
  805. UnicodeString DotNetVersion;
  806. Params->FindSwitch(L"Console", ConsoleVersion);
  807. Params->FindSwitch(L"DotNet", DotNetVersion);
  808. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  809. {
  810. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  811. }
  812. if (!DotNetVersion.IsEmpty())
  813. {
  814. Configuration->Usage->Inc(L"ConsoleDotNet");
  815. }
  816. UnicodeString SwitchValue;
  817. if (Params->FindSwitch(L"loglevel", SwitchValue))
  818. {
  819. int StarPos = SwitchValue.Pos(L"*");
  820. if (StarPos > 0)
  821. {
  822. bool LogSensitive = true;
  823. SwitchValue.Delete(StarPos, 1);
  824. if ((StarPos <= SwitchValue.Length()) &&
  825. (SwitchValue[StarPos] == L'-'))
  826. {
  827. LogSensitive = false;
  828. SwitchValue.Delete(StarPos, 1);
  829. }
  830. SwitchValue = SwitchValue.Trim();
  831. Configuration->TemporaryLogSensitive(LogSensitive);
  832. }
  833. int LogProtocol;
  834. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  835. {
  836. Configuration->TemporaryLogProtocol(LogProtocol);
  837. }
  838. }
  839. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  840. {
  841. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  842. int LogMaxCount = 0;
  843. if (StarPos > 1)
  844. {
  845. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  846. {
  847. LogMaxCount = -1;
  848. }
  849. SwitchValue.Delete(1, StarPos);
  850. SwitchValue = SwitchValue.Trim();
  851. }
  852. __int64 LogMaxSize;
  853. if ((LogMaxCount >= 0) &&
  854. !SwitchValue.IsEmpty() &&
  855. TryStrToSize(SwitchValue, LogMaxSize))
  856. {
  857. Configuration->TemporaryLogMaxCount(LogMaxCount);
  858. Configuration->TemporaryLogMaxSize(LogMaxSize);
  859. }
  860. }
  861. std::unique_ptr<TStrings> RawSettings(new TStringList());
  862. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  863. {
  864. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  865. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  866. }
  867. TConsoleMode Mode = cmNone;
  868. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  869. {
  870. Mode = cmHelp;
  871. }
  872. else if (Params->FindSwitch(L"batchsettings"))
  873. {
  874. Mode = cmBatchSettings;
  875. }
  876. else if (Params->FindSwitch(KEYGEN_SWITCH))
  877. {
  878. Mode = cmKeyGen;
  879. }
  880. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  881. {
  882. Mode = cmFingerprintScan;
  883. }
  884. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  885. {
  886. Mode = cmDumpCallstack;
  887. }
  888. else if (Params->FindSwitch(INFO_SWITCH))
  889. {
  890. Mode = cmInfo;
  891. }
  892. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  893. {
  894. Mode = cmComRegistration;
  895. }
  896. // We have to check for /console only after the other options,
  897. // as the /console is always used when we are run by winscp.com
  898. // (ambiguous use to pass console version)
  899. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  900. Params->FindSwitch(COMMAND_SWITCH))
  901. {
  902. Mode = cmScripting;
  903. }
  904. if (Mode != cmNone)
  905. {
  906. InterfaceStartDontMeasure();
  907. return Console(Mode);
  908. }
  909. TTerminalManager * TerminalManager = NULL;
  910. GlyphsModule = NULL;
  911. NonVisualDataModule = NULL;
  912. TStrings * CommandParams = new TStringList;
  913. AddStartupSequence(L"C");
  914. try
  915. {
  916. TerminalManager = TTerminalManager::Instance();
  917. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  918. try
  919. {
  920. GlyphsModule = new TGlyphsModule(Application);
  921. }
  922. __finally
  923. {
  924. GUIConfiguration->ChangeResourceModule(ResourceModule);
  925. }
  926. AddStartupSequence(L"G");
  927. NonVisualDataModule = new TNonVisualDataModule(Application);
  928. AddStartupSequence(L"N");
  929. // The default is 2.5s.
  930. // 20s is used by Office 2010 and Windows 10 Explorer.
  931. // Some applications use an infinite (Thunderbird, Firefox).
  932. // Overriden for some controls using THintInfo.HideTimeout
  933. Application->HintHidePause = 20000;
  934. HintWindowClass = __classid(TScreenTipHintWindow);
  935. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  936. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  937. {
  938. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  939. if (!FileExists(ApiPath(IniFileNameExpanded)))
  940. {
  941. // this should be displayed rather at the very beginning.
  942. // however for simplicity (GUI-only), we do it only here.
  943. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  944. }
  945. }
  946. if (Params->FindSwitch(L"UninstallCleanup"))
  947. {
  948. MaintenanceTask();
  949. Configuration->DontSave();
  950. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  951. // workaround is that we create mutex in uninstaller, if it runs silent, and
  952. // ignore the UninstallCleanup, when the mutex exists.
  953. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  954. {
  955. DoCleanupDialogIfAnyDataAndWanted();
  956. }
  957. }
  958. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  959. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  960. {
  961. MaintenanceTask();
  962. if (CheckSafe(Params))
  963. {
  964. RegisterForDefaultProtocols();
  965. Configuration->DontSave();
  966. }
  967. }
  968. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  969. {
  970. MaintenanceTask();
  971. if (CheckSafe(Params))
  972. {
  973. UnregisterForProtocols();
  974. Configuration->DontSave();
  975. }
  976. }
  977. else if (Params->FindSwitch(L"AddSearchPath"))
  978. {
  979. MaintenanceTask();
  980. if (CheckSafe(Params))
  981. {
  982. AddSearchPath(ExtractFilePath(Application->ExeName));
  983. Configuration->DontSave();
  984. }
  985. }
  986. else if (Params->FindSwitch(L"RemoveSearchPath"))
  987. {
  988. MaintenanceTask();
  989. if (CheckSafe(Params))
  990. {
  991. try
  992. {
  993. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  994. }
  995. catch(...)
  996. {
  997. // ignore errors
  998. // (RemoveSearchPath is called always on uninstallation,
  999. // even if AddSearchPath was not used, so we would get the error
  1000. // always for non-priviledged user)
  1001. }
  1002. Configuration->DontSave();
  1003. }
  1004. }
  1005. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  1006. {
  1007. MaintenanceTask();
  1008. ImportSitesIfAny();
  1009. }
  1010. else if (Params->FindSwitch(L"Usage", SwitchValue))
  1011. {
  1012. MaintenanceTask();
  1013. Usage(SwitchValue);
  1014. }
  1015. else if (Params->FindSwitch(L"Update"))
  1016. {
  1017. MaintenanceTask();
  1018. CheckForUpdates(false);
  1019. }
  1020. else if (ShowUpdatesIfAvailable())
  1021. {
  1022. // noop
  1023. }
  1024. else if (Params->FindSwitch(L"Exit"))
  1025. {
  1026. // noop
  1027. MaintenanceTask();
  1028. Configuration->DontSave();
  1029. }
  1030. else if (Params->FindSwitch(L"MaintenanceTask"))
  1031. {
  1032. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  1033. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  1034. MaintenanceTask();
  1035. Configuration->DontSave();
  1036. }
  1037. else
  1038. {
  1039. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  1040. ParamCommand = pcNone;
  1041. UnicodeString AutoStartSession;
  1042. UnicodeString DownloadFile;
  1043. int UseDefaults = -1;
  1044. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  1045. if (OnlyInstance &&
  1046. WinConfiguration->TemporaryDirectoryCleanup)
  1047. {
  1048. TemporaryDirectoryCleanup();
  1049. }
  1050. WinConfiguration->CheckDefaultTranslation();
  1051. // Loading shell image lists here (rather than only on demand when file controls are being created)
  1052. // reduces risk of an occasional crash.
  1053. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  1054. InitFileControls();
  1055. if (!Params->Empty)
  1056. {
  1057. UnicodeString Value;
  1058. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  1059. {
  1060. UseDefaults = StrToIntDef(Value, 0);
  1061. }
  1062. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  1063. {
  1064. ParamCommand = pcUpload;
  1065. if (CommandParams->Count == 0)
  1066. {
  1067. throw Exception(NO_UPLOAD_LIST_ERROR);
  1068. }
  1069. }
  1070. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  1071. {
  1072. if (CommandParams->Count > 0)
  1073. {
  1074. ParamCommand = pcUpload;
  1075. }
  1076. }
  1077. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  1078. {
  1079. ParamCommand = pcFullSynchronize;
  1080. }
  1081. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  1082. {
  1083. ParamCommand = pcSynchronize;
  1084. }
  1085. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  1086. (CommandParams->Count == 1))
  1087. {
  1088. ParamCommand = pcEdit;
  1089. }
  1090. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  1091. {
  1092. ParamCommand = pcRefresh;
  1093. }
  1094. }
  1095. bool NewInstance = Params->FindSwitch(NEWINSTANCE_SWICH);
  1096. if (Params->ParamCount > 0)
  1097. {
  1098. AutoStartSession = Params->ConsumeParam();
  1099. bool TrySendToAnotherInstance =
  1100. (ParamCommand == pcNone) &&
  1101. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  1102. !NewInstance;
  1103. if (TrySendToAnotherInstance &&
  1104. !AutoStartSession.IsEmpty() &&
  1105. (AutoStartSession.Pos(L"/") > 0) && // optimization
  1106. GetFolderOrWorkspaceName(AutoStartSession).IsEmpty())
  1107. {
  1108. bool DummyDefaultsOnly = false;
  1109. UnicodeString DownloadFile2;
  1110. int Flags = GetCommandLineParseUrlFlags(Params) | pufParseOnly;
  1111. // Make copy, as ParseUrl consumes /rawsettings
  1112. TOptions Options(*Params);
  1113. std::unique_ptr<TSessionData> SessionData(
  1114. StoredSessions->ParseUrl(AutoStartSession, &Options, DummyDefaultsOnly, &DownloadFile2, NULL, NULL, Flags));
  1115. if (!DownloadFile2.IsEmpty())
  1116. {
  1117. TrySendToAnotherInstance = false;
  1118. }
  1119. }
  1120. if (TrySendToAnotherInstance &&
  1121. SendToAnotherInstance())
  1122. {
  1123. Configuration->Usage->Inc(L"SendToAnotherInstance");
  1124. return 0;
  1125. }
  1126. UnicodeString CounterName;
  1127. if (Params->FindSwitch(JUMPLIST_SWITCH))
  1128. {
  1129. CounterName = L"CommandLineJumpList";
  1130. }
  1131. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1132. {
  1133. CounterName = L"CommandLineDesktop";
  1134. }
  1135. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1136. {
  1137. CounterName = L"CommandLineSendToHook";
  1138. }
  1139. else
  1140. {
  1141. CounterName = L"CommandLineSession2";
  1142. }
  1143. Configuration->Usage->Inc(CounterName);
  1144. }
  1145. else if (NewInstance)
  1146. {
  1147. // no autostart
  1148. }
  1149. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1150. {
  1151. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1152. }
  1153. else
  1154. {
  1155. AutoStartSession = WinConfiguration->AutoStartSession;
  1156. }
  1157. if (ParamCommand == pcRefresh)
  1158. {
  1159. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1160. return 0;
  1161. }
  1162. // from now flash message boxes on background
  1163. SetOnForeground(false);
  1164. bool NeedSession = NewInstance || (ParamCommand != pcNone);
  1165. bool Retry;
  1166. do
  1167. {
  1168. Retry = false;
  1169. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1170. try
  1171. {
  1172. int Flags = GetCommandLineParseUrlFlags(Params);
  1173. AddStartupSequence(L"B");
  1174. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1175. // GetLoginData now Aborts when session is needed and none is selected
  1176. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1177. {
  1178. if (CheckSafe(Params))
  1179. {
  1180. UnicodeString LogFile;
  1181. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1182. {
  1183. Configuration->TemporaryLogging(LogFile);
  1184. }
  1185. if (Params->FindSwitch(L"XmlLog", LogFile))
  1186. {
  1187. Configuration->TemporaryActionsLogging(LogFile);
  1188. }
  1189. }
  1190. try
  1191. {
  1192. DebugAssert(TerminalManager->ActiveSession == NULL);
  1193. bool CanStart;
  1194. bool Browse = false;
  1195. UnicodeString BrowseFile;
  1196. if (DataList->Count > 0)
  1197. {
  1198. TManagedTerminal * Session = TerminalManager->NewSessions(DataList.get());
  1199. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1200. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1201. {
  1202. if (BrowseFile.IsEmpty())
  1203. {
  1204. BrowseFile = DownloadFile;
  1205. }
  1206. DownloadFile = UnicodeString();
  1207. Browse = true;
  1208. }
  1209. if (!DownloadFile.IsEmpty())
  1210. {
  1211. Session->AutoReadDirectory = false;
  1212. DownloadFile = UnixIncludeTrailingBackslash(Session->SessionData->RemoteDirectory) + DownloadFile;
  1213. Session->SessionData->RemoteDirectory = L"";
  1214. Session->StateData->RemoteDirectory = Session->SessionData->RemoteDirectory;
  1215. }
  1216. TerminalManager->ActiveSession = Session;
  1217. CanStart = (TerminalManager->Count > 0);
  1218. }
  1219. else
  1220. {
  1221. DebugAssert(!NeedSession);
  1222. CanStart = true;
  1223. }
  1224. if (!CanStart)
  1225. {
  1226. // do not prompt with login dialog, if connection of
  1227. // auto-start session (typically from command line) failed
  1228. if (AutoStartSession.IsEmpty())
  1229. {
  1230. Retry = true;
  1231. }
  1232. }
  1233. else
  1234. {
  1235. // from now on, we do not support runtime interface change
  1236. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1237. AddStartupSequence(L"A");
  1238. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1239. AddStartupSequence(L"E");
  1240. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1241. try
  1242. {
  1243. // moved inside try .. __finally, because it can fail as well
  1244. TerminalManager->ScpExplorer = ScpExplorer;
  1245. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1246. {
  1247. Configuration->Usage->Inc(L"CommandLineOperation");
  1248. ScpExplorer->StandaloneOperation = true;
  1249. InterfaceStartDontMeasure();
  1250. }
  1251. if (ParamCommand == pcUpload)
  1252. {
  1253. Upload(TerminalManager->ActiveSession, CommandParams, UseDefaults);
  1254. }
  1255. else if (ParamCommand == pcFullSynchronize)
  1256. {
  1257. FullSynchronize(TerminalManager->ActiveSession, ScpExplorer,
  1258. CommandParams, UseDefaults);
  1259. }
  1260. else if (ParamCommand == pcSynchronize)
  1261. {
  1262. Synchronize(TerminalManager->ActiveSession, ScpExplorer,
  1263. CommandParams, UseDefaults);
  1264. }
  1265. else if (ParamCommand == pcEdit)
  1266. {
  1267. Edit(ScpExplorer, CommandParams);
  1268. }
  1269. else if (!DownloadFile.IsEmpty())
  1270. {
  1271. Download(
  1272. TerminalManager->ActiveSession, DownloadFile, UseDefaults, Browse, BrowseFile);
  1273. }
  1274. else
  1275. {
  1276. if (DataList->Count == 0)
  1277. {
  1278. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1279. }
  1280. }
  1281. ScpExplorer->StandaloneOperation = false;
  1282. if (Browse)
  1283. {
  1284. ScpExplorer->BrowseFile(BrowseFile);
  1285. }
  1286. AddStartupSequence(L"R");
  1287. Application->Run();
  1288. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1289. SetAppTerminated(False);
  1290. }
  1291. __finally
  1292. {
  1293. TerminalManager->ScpExplorer = NULL;
  1294. SAFE_DESTROY(ScpExplorer);
  1295. }
  1296. }
  1297. }
  1298. catch (Exception &E)
  1299. {
  1300. ShowExtendedException(&E);
  1301. }
  1302. }
  1303. }
  1304. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1305. catch (EAbort & E)
  1306. {
  1307. Retry = false; // unlikely to be true, but just in case
  1308. }
  1309. }
  1310. while (Retry);
  1311. }
  1312. // In GUI mode only
  1313. CheckConfigurationForceSave();
  1314. UpdateFinalStaticUsage();
  1315. }
  1316. __finally
  1317. {
  1318. delete NonVisualDataModule;
  1319. NonVisualDataModule = NULL;
  1320. ReleaseImagesModules();
  1321. delete GlyphsModule;
  1322. GlyphsModule = NULL;
  1323. TTerminalManager::DestroyInstance();
  1324. delete CommandParams;
  1325. }
  1326. return 0;
  1327. }