WinMain.cpp 36 KB

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