WinMain.cpp 34 KB

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