WinMain.cpp 45 KB

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