1
0

WinMain.cpp 34 KB

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