WinMain.cpp 42 KB

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