WinMain.cpp 38 KB

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