1
0

WinMain.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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(TTerminal * Terminal,
  182. 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 = WinConfiguration->ScpExplorer.LastLocalTargetDirectory;
  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, 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, 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"DefaultLocale",
  417. // See TGUIConfiguration::GetAppliedLocaleHex()
  418. IntToHex(static_cast<int>(GetDefaultLCID()), 4));
  419. Configuration->Usage->Set(L"Locale", WinConfiguration->AppliedLocaleHex);
  420. Configuration->Usage->Set(L"EncodingMultiByteAnsi", !TEncoding::Default->IsSingleByte);
  421. Configuration->Usage->Set(L"PixelsPerInch", Screen->PixelsPerInch);
  422. bool PixelsPerInchSystemDiffers = false;
  423. bool PixelsPerInchMonitorsDiffer = false;
  424. bool PixelsPerInchAxesDiffer = false;
  425. HINSTANCE ShCoreLibrary = LoadLibrary(L"shcore.dll");
  426. if (ShCoreLibrary != NULL)
  427. {
  428. GetDpiForMonitorProc GetDpiForMonitor =
  429. (GetDpiForMonitorProc)GetProcAddress(ShCoreLibrary, "GetDpiForMonitor");
  430. if (GetDpiForMonitor != NULL)
  431. {
  432. unsigned int PrimaryDpiX;
  433. unsigned int PrimaryDpiY;
  434. for (int Index = 0; Index < Screen->MonitorCount; Index++)
  435. {
  436. unsigned int DpiX;
  437. unsigned int DpiY;
  438. GetDpiForMonitor(Screen->Monitors[Index]->Handle, MDT_Default, &DpiX, &DpiY);
  439. if (DpiX != DpiY)
  440. {
  441. PixelsPerInchAxesDiffer = true;
  442. }
  443. if (Index == 0)
  444. {
  445. PrimaryDpiX = DpiX;
  446. PrimaryDpiY = DpiY;
  447. // PixelsPerInch is GetDeviceCaps(DC, LOGPIXELSY)
  448. if (DpiY != (unsigned int)Screen->PixelsPerInch)
  449. {
  450. PixelsPerInchSystemDiffers = true;
  451. }
  452. }
  453. else
  454. {
  455. if ((DpiX != PrimaryDpiX) ||
  456. (DpiY != PrimaryDpiY))
  457. {
  458. PixelsPerInchMonitorsDiffer = true;
  459. }
  460. }
  461. }
  462. }
  463. }
  464. if (PixelsPerInchSystemDiffers)
  465. {
  466. Configuration->Usage->Inc(L"PixelsPerInchSystemDiffered");
  467. }
  468. Configuration->Usage->Set(L"PixelsPerInchMonitorsDiffer", PixelsPerInchMonitorsDiffer);
  469. Configuration->Usage->Set(L"PixelsPerInchAxesDiffer", PixelsPerInchAxesDiffer);
  470. Configuration->Usage->Set(L"WorkAreaWidth", Screen->WorkAreaWidth);
  471. Configuration->Usage->Set(L"WorkAreaHeight", Screen->WorkAreaHeight);
  472. HDC DC = GetDC(NULL);
  473. int Planes = GetDeviceCaps(DC, PLANES);
  474. int BitsPixel = GetDeviceCaps(DC, BITSPIXEL);
  475. Configuration->Usage->Set(L"ColorDepth", Planes * BitsPixel);
  476. Configuration->Usage->Set(L"MonitorCount", Screen->MonitorCount);
  477. Configuration->Usage->Set(L"NotUseThemes", !UseThemes());
  478. Configuration->Usage->Set(L"ThemeDefaultFontSize", Application->DefaultFont->Size);
  479. Configuration->Usage->Set(L"ThemeIconFontSize", Screen->IconFont->Size);
  480. Configuration->Usage->Set(L"SysColorWindow", ColorToRGBStr(clWindow));
  481. Configuration->Usage->Set(L"SysColorBtnFace", ColorToRGBStr(clBtnFace));
  482. Configuration->Usage->Set(L"SysColorWindowText", ColorToRGBStr(clWindowText));
  483. UnicodeString ProgramsFolder;
  484. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  485. ProgramsFolder = IncludeTrailingBackslash(ExpandFileName(ProgramsFolder));
  486. UnicodeString ExeName = ExpandFileName(Application->ExeName);
  487. bool InProgramFiles = AnsiSameText(ExeName.SubString(1, ProgramsFolder.Length()), ProgramsFolder);
  488. Configuration->Usage->Set(L"InProgramFiles", InProgramFiles);
  489. Configuration->Usage->Set(L"IsInstalled", IsInstalled());
  490. Configuration->Usage->Set(L"Wine", IsWine());
  491. Configuration->Usage->Set(L"NetFrameworkVersion", GetNetVersionStr());
  492. Configuration->Usage->Set(L"PowerShellVersion", GetPowerShellVersionStr());
  493. UnicodeString ParentProcess = GetAncestorProcessName();
  494. // do not record the installer as a parent process
  495. if (!ParentProcess.IsEmpty() &&
  496. (!StartsText(L"winscp-", ParentProcess) || !ContainsText(ParentProcess, L"-setup")))
  497. {
  498. UnicodeString ParentProcesses = Configuration->Usage->Get(L"ParentProcesses");
  499. std::unique_ptr<TStringList> ParentProcessesList(CreateSortedStringList());
  500. ParentProcessesList->CommaText = ParentProcesses;
  501. ParentProcessesList->Add(ParentProcess.LowerCase());
  502. Configuration->Usage->Set(L"ParentProcesses", ParentProcessesList->CommaText);
  503. }
  504. WinConfiguration->UpdateStaticUsage();
  505. }
  506. //---------------------------------------------------------------------------
  507. void __fastcall MaintenanceTask()
  508. {
  509. CoreMaintenanceTask();
  510. }
  511. //---------------------------------------------------------------------------
  512. typedef std::vector<HWND> THandles;
  513. typedef std::map<unsigned long, THandles> TProcesses;
  514. //---------------------------------------------------------------------------
  515. BOOL __stdcall EnumOtherInstances(HWND Handle, LPARAM AParam)
  516. {
  517. TProcesses & Processes = *reinterpret_cast<TProcesses *>(AParam);
  518. unsigned long ProcessId;
  519. if (GetWindowThreadProcessId(Handle, &ProcessId) != 0)
  520. {
  521. Processes[ProcessId].push_back(Handle);
  522. }
  523. return TRUE;
  524. }
  525. //---------------------------------------------------------------------------
  526. static bool __fastcall SendCopyDataMessage(HWND Window, TCopyDataMessage & Message)
  527. {
  528. COPYDATASTRUCT CopyData;
  529. CopyData.cbData = sizeof(Message);
  530. CopyData.lpData = &Message;
  531. LRESULT SendResult =
  532. SendMessage(Window, WM_COPYDATA,
  533. reinterpret_cast<WPARAM>(HInstance), reinterpret_cast<LPARAM>(&CopyData));
  534. bool Result = (SendResult > 0);
  535. return Result;
  536. }
  537. //---------------------------------------------------------------------------
  538. static void __fastcall FindOtherInstances(THandles & OtherInstances)
  539. {
  540. TProcesses Processes;
  541. // FindWindow is optimization (if there's no hidden window, no point enumerating all windows to find some)
  542. if ((FindWindow(HIDDEN_WINDOW_NAME, NULL) != NULL) &&
  543. EnumWindows(EnumOtherInstances, reinterpret_cast<LPARAM>(&Processes)))
  544. {
  545. TCopyDataMessage Message;
  546. Message.Command = TCopyDataMessage::MainWindowCheck;
  547. TProcesses::const_iterator ProcessI = Processes.begin();
  548. while (ProcessI != Processes.end())
  549. {
  550. HWND HiddenWindow = NULL;
  551. THandles::const_iterator WindowI = ProcessI->second.begin();
  552. while ((HiddenWindow == NULL) && (WindowI != ProcessI->second.end()))
  553. {
  554. wchar_t ClassName[1024];
  555. if (GetClassName(*WindowI, ClassName, LENOF(ClassName)) != 0)
  556. {
  557. NULL_TERMINATE(ClassName);
  558. if (wcscmp(ClassName, HIDDEN_WINDOW_NAME) == 0)
  559. {
  560. HiddenWindow = *WindowI;
  561. }
  562. }
  563. WindowI++;
  564. }
  565. if (HiddenWindow != NULL)
  566. {
  567. WindowI = ProcessI->second.begin();
  568. while (WindowI != ProcessI->second.end())
  569. {
  570. if (*WindowI != HiddenWindow) // optimization
  571. {
  572. if (SendCopyDataMessage(*WindowI, Message))
  573. {
  574. OtherInstances.push_back(*WindowI);
  575. break;
  576. }
  577. }
  578. WindowI++;
  579. }
  580. }
  581. ProcessI++;
  582. }
  583. }
  584. }
  585. //---------------------------------------------------------------------------
  586. bool __fastcall SendToAnotherInstance()
  587. {
  588. THandles OtherInstances;
  589. FindOtherInstances(OtherInstances);
  590. bool Result = false;
  591. THandles::const_iterator I = OtherInstances.begin();
  592. while (!Result && (I != OtherInstances.end()))
  593. {
  594. HWND Handle = *I;
  595. TCopyDataMessage Message;
  596. Message.Command = TCopyDataMessage::CommandCanCommandLine;
  597. if (SendCopyDataMessage(Handle, Message))
  598. {
  599. // Restore window, if minimized
  600. ShowWindow(Handle, SW_RESTORE);
  601. // bring it to foreground
  602. SetForegroundWindow(Handle);
  603. Message.Command = TCopyDataMessage::CommandCommandLine;
  604. wcsncpy(Message.CommandLine, CmdLine, LENOF(Message.CommandLine));
  605. NULL_TERMINATE(Message.CommandLine);
  606. Result = SendCopyDataMessage(Handle, Message);
  607. }
  608. I++;
  609. }
  610. return Result;
  611. }
  612. //---------------------------------------------------------------------------
  613. void __fastcall Refresh(const UnicodeString & Session, const UnicodeString & Path)
  614. {
  615. THandles OtherInstances;
  616. FindOtherInstances(OtherInstances);
  617. THandles::const_iterator I = OtherInstances.begin();
  618. while (I != OtherInstances.end())
  619. {
  620. HWND Handle = *I;
  621. TCopyDataMessage Message;
  622. Message.Command = TCopyDataMessage::RefreshPanel;
  623. wcsncpy(Message.Refresh.Session, Session.c_str(), LENOF(Message.Refresh.Session));
  624. NULL_TERMINATE(Message.Refresh.Session);
  625. wcsncpy(Message.Refresh.Path, Path.c_str(), LENOF(Message.Refresh.Path));
  626. NULL_TERMINATE(Message.Refresh.Path);
  627. SendCopyDataMessage(Handle, Message);
  628. I++;
  629. }
  630. }
  631. //---------------------------------------------------------------------------
  632. bool __fastcall ShowUpdatesIfAvailable()
  633. {
  634. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  635. int CurrentCompoundVer = Configuration->CompoundVersion;
  636. bool NoPopup = true;
  637. bool Result =
  638. !IsUWP() &&
  639. Updates.ShowOnStartup &&
  640. Updates.HaveValidResultsForVersion(CurrentCompoundVer) &&
  641. !Updates.Results.Disabled &&
  642. ((Updates.Results.Version > CurrentCompoundVer) || !Updates.Results.Message.IsEmpty()) &&
  643. !Updates.ShownResults;
  644. if (Result)
  645. {
  646. Configuration->Usage->Inc(L"UpdateStartup");
  647. Result = CheckForUpdates(true);
  648. if (Result)
  649. {
  650. Configuration->Usage->Inc(L"UpdateDownloadOpensStartup");
  651. }
  652. NoPopup = false;
  653. }
  654. else if (WinConfiguration->ShowTips)
  655. {
  656. int Days = DaysBetween(WinConfiguration->TipsShown, Now());
  657. if ((Days >= Updates.Results.TipsIntervalDays) &&
  658. (WinConfiguration->RunsSinceLastTip >= Updates.Results.TipsIntervalDays))
  659. {
  660. UnicodeString Tip = FirstUnshownTip();
  661. if (!Tip.IsEmpty())
  662. {
  663. AutoShowNewTip();
  664. NoPopup = false;
  665. }
  666. else
  667. {
  668. Configuration->Usage->Inc(L"TipsNoUnseen");
  669. }
  670. }
  671. }
  672. if (NoPopup)
  673. {
  674. WinConfiguration->RunsSinceLastTip = WinConfiguration->RunsSinceLastTip + 1;
  675. }
  676. return Result;
  677. }
  678. //---------------------------------------------------------------------------
  679. int __fastcall Execute()
  680. {
  681. DebugAssert(StoredSessions);
  682. TProgramParams * Params = TProgramParams::Instance();
  683. DebugAssert(Params);
  684. // do not flash message boxes on startup
  685. SetOnForeground(true);
  686. // let installer know, that some instance of application is running
  687. CreateMutex(NULL, False, AppName.c_str());
  688. bool OnlyInstance = (GetLastError() == 0);
  689. UpdateStaticUsage();
  690. UnicodeString KeyFile;
  691. if (Params->FindSwitch(L"PrivateKey", KeyFile))
  692. {
  693. WinConfiguration->DefaultKeyFile = KeyFile;
  694. }
  695. UnicodeString ConsoleVersion;
  696. UnicodeString DotNetVersion;
  697. Params->FindSwitch(L"Console", ConsoleVersion);
  698. Params->FindSwitch(L"DotNet", DotNetVersion);
  699. if (!ConsoleVersion.IsEmpty() || !DotNetVersion.IsEmpty())
  700. {
  701. RecordWrapperVersions(ConsoleVersion, DotNetVersion);
  702. }
  703. if (!DotNetVersion.IsEmpty())
  704. {
  705. Configuration->Usage->Inc(L"ConsoleDotNet");
  706. }
  707. UnicodeString SwitchValue;
  708. if (Params->FindSwitch(L"loglevel", SwitchValue))
  709. {
  710. int StarPos = SwitchValue.Pos(L"*");
  711. if (StarPos > 0)
  712. {
  713. bool LogSensitive = true;
  714. SwitchValue.Delete(StarPos, 1);
  715. if ((StarPos <= SwitchValue.Length()) &&
  716. (SwitchValue[StarPos] == L'-'))
  717. {
  718. LogSensitive = false;
  719. SwitchValue.Delete(StarPos, 1);
  720. }
  721. SwitchValue = SwitchValue.Trim();
  722. Configuration->TemporaryLogSensitive(LogSensitive);
  723. }
  724. int LogProtocol;
  725. if (!SwitchValue.IsEmpty() && TryStrToInt(SwitchValue, LogProtocol) && (LogProtocol >= -1))
  726. {
  727. Configuration->TemporaryLogProtocol(LogProtocol);
  728. }
  729. }
  730. if (Params->FindSwitch(LOGSIZE_SWITCH, SwitchValue))
  731. {
  732. int StarPos = SwitchValue.Pos(LOGSIZE_SEPARATOR);
  733. int LogMaxCount = 0;
  734. if (StarPos > 1)
  735. {
  736. if (!TryStrToInt(SwitchValue.SubString(1, StarPos - 1), LogMaxCount))
  737. {
  738. LogMaxCount = -1;
  739. }
  740. SwitchValue.Delete(1, StarPos);
  741. SwitchValue = SwitchValue.Trim();
  742. }
  743. __int64 LogMaxSize;
  744. if ((LogMaxCount >= 0) &&
  745. !SwitchValue.IsEmpty() &&
  746. TryStrToSize(SwitchValue, LogMaxSize))
  747. {
  748. Configuration->TemporaryLogMaxCount(LogMaxCount);
  749. Configuration->TemporaryLogMaxSize(LogMaxSize);
  750. }
  751. }
  752. std::unique_ptr<TStrings> RawSettings(new TStringList());
  753. if (Params->FindSwitch(RAWTRANSFERSETTINGS_SWITCH, RawSettings.get()))
  754. {
  755. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings.get(), false));
  756. GUIConfiguration->LoadDefaultCopyParam(OptionsStorage.get());
  757. }
  758. TConsoleMode Mode = cmNone;
  759. if (Params->FindSwitch(L"help") || Params->FindSwitch(L"h") || Params->FindSwitch(L"?"))
  760. {
  761. Mode = cmHelp;
  762. }
  763. else if (Params->FindSwitch(L"batchsettings"))
  764. {
  765. Mode = cmBatchSettings;
  766. }
  767. else if (Params->FindSwitch(KEYGEN_SWITCH))
  768. {
  769. Mode = cmKeyGen;
  770. }
  771. else if (Params->FindSwitch(FINGERPRINTSCAN_SWITCH))
  772. {
  773. Mode = cmFingerprintScan;
  774. }
  775. else if (Params->FindSwitch(DUMPCALLSTACK_SWITCH))
  776. {
  777. Mode = cmDumpCallstack;
  778. }
  779. else if (Params->FindSwitch(INFO_SWITCH))
  780. {
  781. Mode = cmInfo;
  782. }
  783. else if (Params->FindSwitch(COMREGISTRATION_SWITCH))
  784. {
  785. Mode = cmComRegistration;
  786. }
  787. // We have to check for /console only after the other options,
  788. // as the /console is always used when we are run by winscp.com
  789. // (ambiguous use to pass console version)
  790. else if (Params->FindSwitch(L"Console") || Params->FindSwitch(SCRIPT_SWITCH) ||
  791. Params->FindSwitch(COMMAND_SWITCH))
  792. {
  793. Mode = cmScripting;
  794. }
  795. if (Mode != cmNone)
  796. {
  797. return Console(Mode);
  798. }
  799. TTerminalManager * TerminalManager = NULL;
  800. GlyphsModule = NULL;
  801. NonVisualDataModule = NULL;
  802. TStrings * CommandParams = new TStringList;
  803. try
  804. {
  805. TerminalManager = TTerminalManager::Instance();
  806. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  807. try
  808. {
  809. GlyphsModule = new TGlyphsModule(Application);
  810. }
  811. __finally
  812. {
  813. GUIConfiguration->ChangeResourceModule(ResourceModule);
  814. }
  815. NonVisualDataModule = new TNonVisualDataModule(Application);
  816. // The default is 2.5s.
  817. // 20s is used by Office 2010 and Windows 10 Explorer.
  818. // Some applications use an infinite (Thunderbird, Firefox).
  819. // Overriden for some controls using THintInfo.HideTimeout
  820. Application->HintHidePause = 20000;
  821. HintWindowClass = __classid(TScreenTipHintWindow);
  822. UnicodeString IniFileName = Params->SwitchValue(INI_SWITCH);
  823. if (!IniFileName.IsEmpty() && (IniFileName != INI_NUL))
  824. {
  825. UnicodeString IniFileNameExpanded = ExpandEnvironmentVariables(IniFileName);
  826. if (!FileExists(ApiPath(IniFileNameExpanded)))
  827. {
  828. // this should be displayed rather at the very beginning.
  829. // however for simplicity (GUI-only), we do it only here.
  830. MessageDialog(FMTLOAD(FILE_NOT_EXISTS, (IniFileNameExpanded)), qtError, qaOK);
  831. }
  832. }
  833. if (Params->FindSwitch(L"UninstallCleanup"))
  834. {
  835. MaintenanceTask();
  836. Configuration->DontSave();
  837. // The innosetup cannot skip UninstallCleanup run task for silent uninstalls,
  838. // workaround is that we create mutex in uninstaller, if it runs silent, and
  839. // ignore the UninstallCleanup, when the mutex exists.
  840. if (OpenMutex(SYNCHRONIZE, false, L"WinSCPSilentUninstall") == NULL)
  841. {
  842. DoCleanupDialogIfAnyDataAndWanted();
  843. }
  844. }
  845. else if (Params->FindSwitch(L"RegisterForDefaultProtocols") ||
  846. Params->FindSwitch(L"RegisterAsUrlHandler")) // BACKWARD COMPATIBILITY
  847. {
  848. MaintenanceTask();
  849. if (CheckSafe(Params))
  850. {
  851. RegisterForDefaultProtocols();
  852. Configuration->DontSave();
  853. }
  854. }
  855. else if (Params->FindSwitch(L"UnregisterForProtocols"))
  856. {
  857. MaintenanceTask();
  858. if (CheckSafe(Params))
  859. {
  860. UnregisterForProtocols();
  861. Configuration->DontSave();
  862. }
  863. }
  864. else if (Params->FindSwitch(L"AddSearchPath"))
  865. {
  866. MaintenanceTask();
  867. if (CheckSafe(Params))
  868. {
  869. AddSearchPath(ExtractFilePath(Application->ExeName));
  870. Configuration->DontSave();
  871. }
  872. }
  873. else if (Params->FindSwitch(L"RemoveSearchPath"))
  874. {
  875. MaintenanceTask();
  876. if (CheckSafe(Params))
  877. {
  878. try
  879. {
  880. RemoveSearchPath(ExtractFilePath(Application->ExeName));
  881. }
  882. catch(...)
  883. {
  884. // ignore errors
  885. // (RemoveSearchPath is called always on uninstallation,
  886. // even if AddSearchPath was not used, so we would get the error
  887. // always for non-priviledged user)
  888. }
  889. Configuration->DontSave();
  890. }
  891. }
  892. else if (Params->FindSwitch(L"ImportSitesIfAny"))
  893. {
  894. MaintenanceTask();
  895. ImportSitesIfAny();
  896. }
  897. else if (Params->FindSwitch(L"Usage", SwitchValue))
  898. {
  899. MaintenanceTask();
  900. Usage(SwitchValue);
  901. }
  902. else if (Params->FindSwitch(L"Update"))
  903. {
  904. MaintenanceTask();
  905. CheckForUpdates(false);
  906. }
  907. else if (ShowUpdatesIfAvailable())
  908. {
  909. // noop
  910. }
  911. else if (Params->FindSwitch(L"Exit"))
  912. {
  913. // noop
  914. MaintenanceTask();
  915. Configuration->DontSave();
  916. }
  917. else if (Params->FindSwitch(L"MaintenanceTask"))
  918. {
  919. // Parameter /MaintenanceTask can be added to command-line when executing maintenance tasks
  920. // (e.g. from installer) just in case old version of WinSCP is called by mistake
  921. MaintenanceTask();
  922. Configuration->DontSave();
  923. }
  924. else
  925. {
  926. enum { pcNone, pcUpload, pcFullSynchronize, pcSynchronize, pcEdit, pcRefresh } ParamCommand;
  927. ParamCommand = pcNone;
  928. UnicodeString AutoStartSession;
  929. UnicodeString DownloadFile;
  930. int UseDefaults = -1;
  931. // do not check for temp dirs for service tasks (like RegisterAsUrlHandler)
  932. if (OnlyInstance &&
  933. WinConfiguration->TemporaryDirectoryCleanup)
  934. {
  935. TemporaryDirectoryCleanup();
  936. }
  937. WinConfiguration->CheckDefaultTranslation();
  938. // Loading shell image lists here (rather than only on demand when file controls are being created)
  939. // reduces risk of an occasional crash.
  940. // It seems that the point is to load the lists before any call to SHGetFileInfoWithTimeout.
  941. InitFileControls();
  942. if (!Params->Empty)
  943. {
  944. UnicodeString Value;
  945. if (Params->FindSwitch(DEFAULTS_SWITCH, Value) && CheckSafe(Params))
  946. {
  947. UseDefaults = StrToIntDef(Value, 0);
  948. }
  949. if (Params->FindSwitch(UPLOAD_SWITCH, CommandParams))
  950. {
  951. ParamCommand = pcUpload;
  952. if (CommandParams->Count == 0)
  953. {
  954. throw Exception(NO_UPLOAD_LIST_ERROR);
  955. }
  956. }
  957. if (Params->FindSwitch(UPLOAD_IF_ANY_SWITCH, CommandParams))
  958. {
  959. if (CommandParams->Count > 0)
  960. {
  961. ParamCommand = pcUpload;
  962. }
  963. }
  964. else if (Params->FindSwitch(SYNCHRONIZE_SWITCH, CommandParams, 4))
  965. {
  966. ParamCommand = pcFullSynchronize;
  967. }
  968. else if (Params->FindSwitch(KEEP_UP_TO_DATE_SWITCH, CommandParams, 4))
  969. {
  970. ParamCommand = pcSynchronize;
  971. }
  972. else if (Params->FindSwitch(L"Edit", CommandParams, 1) &&
  973. (CommandParams->Count == 1))
  974. {
  975. ParamCommand = pcEdit;
  976. }
  977. else if (Params->FindSwitch(REFRESH_SWITCH, CommandParams, 1))
  978. {
  979. ParamCommand = pcRefresh;
  980. }
  981. }
  982. bool NewInstance = Params->FindSwitch(NEWINSTANCE_SWICH);
  983. if (Params->ParamCount > 0)
  984. {
  985. AutoStartSession = Params->Param[1];
  986. Params->ParamsProcessed(1, 1);
  987. if ((ParamCommand == pcNone) &&
  988. (WinConfiguration->ExternalSessionInExistingInstance != OpenInNewWindow()) &&
  989. !NewInstance &&
  990. SendToAnotherInstance())
  991. {
  992. Configuration->Usage->Inc(L"SendToAnotherInstance");
  993. return 0;
  994. }
  995. UnicodeString CounterName;
  996. if (Params->FindSwitch(JUMPLIST_SWITCH))
  997. {
  998. CounterName = L"CommandLineJumpList";
  999. }
  1000. else if (Params->FindSwitch(DESKTOP_SWITCH))
  1001. {
  1002. CounterName = L"CommandLineDesktop";
  1003. }
  1004. else if (Params->FindSwitch(SEND_TO_HOOK_SWITCH))
  1005. {
  1006. CounterName = L"CommandLineSendToHook";
  1007. }
  1008. else
  1009. {
  1010. CounterName = L"CommandLineSession2";
  1011. }
  1012. Configuration->Usage->Inc(CounterName);
  1013. }
  1014. else if (NewInstance)
  1015. {
  1016. // no autostart
  1017. }
  1018. else if (WinConfiguration->EmbeddedSessions && StoredSessions->Count)
  1019. {
  1020. AutoStartSession = StoredSessions->Sessions[0]->Name;
  1021. }
  1022. else
  1023. {
  1024. AutoStartSession = WinConfiguration->AutoStartSession;
  1025. }
  1026. if (ParamCommand == pcRefresh)
  1027. {
  1028. Refresh(AutoStartSession, (CommandParams->Count > 0 ? CommandParams->Strings[0] : UnicodeString()));
  1029. return 0;
  1030. }
  1031. // from now flash message boxes on background
  1032. SetOnForeground(false);
  1033. bool NeedSession = NewInstance || (ParamCommand != pcNone);
  1034. bool Retry;
  1035. do
  1036. {
  1037. Retry = false;
  1038. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1039. try
  1040. {
  1041. int Flags = GetCommandLineParseUrlFlags(Params);
  1042. GetLoginData(AutoStartSession, Params, DataList.get(), DownloadFile, NeedSession, NULL, Flags);
  1043. // GetLoginData now Aborts when session is needed and none is selected
  1044. if (DebugAlwaysTrue(!NeedSession || (DataList->Count > 0)))
  1045. {
  1046. if (CheckSafe(Params))
  1047. {
  1048. UnicodeString LogFile;
  1049. if (Params->FindSwitch(LOG_SWITCH, LogFile))
  1050. {
  1051. Configuration->TemporaryLogging(LogFile);
  1052. }
  1053. if (Params->FindSwitch(L"XmlLog", LogFile))
  1054. {
  1055. Configuration->TemporaryActionsLogging(LogFile);
  1056. }
  1057. }
  1058. try
  1059. {
  1060. DebugAssert(TerminalManager->ActiveSession == NULL);
  1061. bool CanStart;
  1062. bool Browse = false;
  1063. if (DataList->Count > 0)
  1064. {
  1065. TManagedTerminal * Session = TerminalManager->NewSessions(DataList.get());
  1066. UnicodeString BrowseFile;
  1067. if (Params->FindSwitch(BROWSE_SWITCH, BrowseFile) &&
  1068. (!BrowseFile.IsEmpty() || !DownloadFile.IsEmpty()))
  1069. {
  1070. if (BrowseFile.IsEmpty())
  1071. {
  1072. BrowseFile = DownloadFile;
  1073. }
  1074. DebugAssert(Session->RemoteExplorerState == NULL);
  1075. Session->RemoteExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1076. DebugAssert(Session->LocalExplorerState == NULL);
  1077. Session->LocalExplorerState = CreateDirViewStateForFocusedItem(BrowseFile);
  1078. DownloadFile = UnicodeString();
  1079. Browse = true;
  1080. }
  1081. if (!DownloadFile.IsEmpty())
  1082. {
  1083. Session->AutoReadDirectory = false;
  1084. DownloadFile = UnixIncludeTrailingBackslash(Session->SessionData->RemoteDirectory) + DownloadFile;
  1085. Session->SessionData->RemoteDirectory = L"";
  1086. Session->StateData->RemoteDirectory = Session->SessionData->RemoteDirectory;
  1087. }
  1088. TerminalManager->ActiveSession = Session;
  1089. CanStart = (TerminalManager->Count > 0);
  1090. }
  1091. else
  1092. {
  1093. DebugAssert(!NeedSession);
  1094. CanStart = true;
  1095. }
  1096. if (!CanStart)
  1097. {
  1098. // do not prompt with login dialog, if connection of
  1099. // auto-start session (typically from command line) failed
  1100. if (AutoStartSession.IsEmpty())
  1101. {
  1102. Retry = true;
  1103. }
  1104. }
  1105. else
  1106. {
  1107. // from now on, we do not support runtime interface change
  1108. CustomWinConfiguration->CanApplyInterfaceImmediately = false;
  1109. TCustomScpExplorerForm * ScpExplorer = CreateScpExplorer();
  1110. CustomWinConfiguration->AppliedInterface = CustomWinConfiguration->Interface;
  1111. try
  1112. {
  1113. // moved inside try .. __finally, because it can fail as well
  1114. TerminalManager->ScpExplorer = ScpExplorer;
  1115. if ((ParamCommand != pcNone) || !DownloadFile.IsEmpty())
  1116. {
  1117. Configuration->Usage->Inc(L"CommandLineOperation");
  1118. ScpExplorer->StandaloneOperation = true;
  1119. }
  1120. if (ParamCommand == pcUpload)
  1121. {
  1122. Upload(TerminalManager->ActiveSession, CommandParams, UseDefaults);
  1123. }
  1124. else if (ParamCommand == pcFullSynchronize)
  1125. {
  1126. FullSynchronize(TerminalManager->ActiveSession, ScpExplorer,
  1127. CommandParams, UseDefaults);
  1128. }
  1129. else if (ParamCommand == pcSynchronize)
  1130. {
  1131. Synchronize(TerminalManager->ActiveSession, ScpExplorer,
  1132. CommandParams, UseDefaults);
  1133. }
  1134. else if (ParamCommand == pcEdit)
  1135. {
  1136. Edit(ScpExplorer, CommandParams);
  1137. }
  1138. else if (!DownloadFile.IsEmpty())
  1139. {
  1140. Download(TerminalManager->ActiveSession, DownloadFile,
  1141. UseDefaults);
  1142. }
  1143. else
  1144. {
  1145. if (DataList->Count == 0)
  1146. {
  1147. LifetimeRuns = Configuration->Usage->Inc(L"RunsNormal");
  1148. }
  1149. }
  1150. ScpExplorer->StandaloneOperation = false;
  1151. if (Browse)
  1152. {
  1153. ScpExplorer->BrowseFile();
  1154. }
  1155. Application->Run();
  1156. // to allow dialog boxes show later (like from CheckConfigurationForceSave)
  1157. SetAppTerminated(False);
  1158. }
  1159. __finally
  1160. {
  1161. TerminalManager->ScpExplorer = NULL;
  1162. SAFE_DESTROY(ScpExplorer);
  1163. }
  1164. }
  1165. }
  1166. catch (Exception &E)
  1167. {
  1168. ShowExtendedException(&E);
  1169. }
  1170. }
  1171. }
  1172. // Catch EAbort from Synchronize() and similar functions, so that CheckConfigurationForceSave is processed
  1173. catch (EAbort & E)
  1174. {
  1175. Retry = false; // unlikely to be true, but just in case
  1176. }
  1177. }
  1178. while (Retry);
  1179. }
  1180. // In GUI mode only
  1181. CheckConfigurationForceSave();
  1182. }
  1183. __finally
  1184. {
  1185. delete NonVisualDataModule;
  1186. NonVisualDataModule = NULL;
  1187. ReleaseImagesModules();
  1188. delete GlyphsModule;
  1189. GlyphsModule = NULL;
  1190. TTerminalManager::DestroyInstance();
  1191. delete CommandParams;
  1192. }
  1193. return 0;
  1194. }