WinMain.cpp 37 KB

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