WinMain.cpp 43 KB

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