WinMain.cpp 46 KB

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