GenerateUrl.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "VCLCommon.h"
  5. #include "GenerateUrl.h"
  6. #include "CoreMain.h"
  7. #include "WinConfiguration.h"
  8. #include <StrUtils.hpp>
  9. #include <Tools.h>
  10. #include <PuttyTools.h>
  11. #include <TextsWin.h>
  12. #include <ProgParams.h>
  13. #include <GUITools.h>
  14. //---------------------------------------------------------------------------
  15. #pragma package(smart_init)
  16. #pragma resource "*.dfm"
  17. //---------------------------------------------------------------------------
  18. const UnicodeString AllFilesMask(L"*");
  19. const UnicodeString NoOpOperationMask(L"*");
  20. //---------------------------------------------------------------------------
  21. static UnicodeString ExcludeTrailingBackslashUnlessRoot(const UnicodeString & Path)
  22. {
  23. UnicodeString Result = ExcludeTrailingBackslash(Path);
  24. if (SameText(Result, ExtractFileDrive(Result)))
  25. {
  26. Result = IncludeTrailingBackslash(Path);
  27. }
  28. return Result;
  29. }
  30. //---------------------------------------------------------------------------
  31. void __fastcall DoGenerateUrlDialog(TSessionData * Data, TStrings * Paths)
  32. {
  33. std::unique_ptr<TGenerateUrlDialog> Dialog(
  34. new TGenerateUrlDialog(GetFormOwner(), Data, fsList, Paths, false, false, false, 0, UnicodeString(), TCopyParamType()));
  35. Dialog->Execute();
  36. }
  37. //---------------------------------------------------------------------------
  38. void __fastcall DoGenerateTransferCodeDialog(
  39. bool ToRemote, bool Move, int CopyParamAttrs, TSessionData * Data, TFilesSelected FilesSelected, TStrings * FileList, const UnicodeString & Path,
  40. const TCopyParamType & CopyParam)
  41. {
  42. std::unique_ptr<TGenerateUrlDialog> Dialog(
  43. new TGenerateUrlDialog(GetFormOwner(), Data, FilesSelected, FileList, true, ToRemote, Move, CopyParamAttrs, Path, CopyParam));
  44. Dialog->Execute();
  45. }
  46. //---------------------------------------------------------------------------
  47. class TRichEditWithLinks : public TNewRichEdit
  48. {
  49. public:
  50. virtual __fastcall TRichEditWithLinks(TComponent * AOwner);
  51. protected:
  52. virtual void __fastcall CreateWnd();
  53. void __fastcall Dispatch(void * Message);
  54. };
  55. //---------------------------------------------------------------------------
  56. __fastcall TRichEditWithLinks::TRichEditWithLinks(TComponent * AOwner) :
  57. TNewRichEdit(AOwner)
  58. {
  59. }
  60. //---------------------------------------------------------------------------
  61. void __fastcall TRichEditWithLinks::CreateWnd()
  62. {
  63. TNewRichEdit::CreateWnd();
  64. int Mask = SendMessage(Handle, EM_GETEVENTMASK, 0, 0);
  65. SendMessage(Handle, EM_SETEVENTMASK, 0, Mask | ENM_LINK);
  66. }
  67. //---------------------------------------------------------------------------
  68. void __fastcall TRichEditWithLinks::Dispatch(void * AMessage)
  69. {
  70. TMessage & Message = *reinterpret_cast<TMessage *>(AMessage);
  71. if (Message.Msg == CN_NOTIFY)
  72. {
  73. TWMNotify & WMNotify = *reinterpret_cast<TWMNotify *>(AMessage);
  74. if (WMNotify.NMHdr->code == EN_LINK)
  75. {
  76. TENLink & ENLink = *reinterpret_cast<TENLink *>(Message.LParam);
  77. if (ENLink.msg == WM_LBUTTONDOWN)
  78. {
  79. UnicodeString AText = Text;
  80. // The cpMin and cpMax refer to indexes in a script with a single-byte EOL,
  81. // while the Text (GetWindowText) uses two-byte EOL
  82. AText = ReplaceStr(AText, L"\r\n", L"\n");
  83. if (DebugAlwaysTrue(ENLink.chrg.cpMax < AText.Length()))
  84. {
  85. UnicodeString Url = AText.SubString(ENLink.chrg.cpMin + 1, ENLink.chrg.cpMax - ENLink.chrg.cpMin);
  86. if (IsHttpOrHttpsUrl(Url))
  87. {
  88. OpenBrowser(Url);
  89. }
  90. else
  91. {
  92. ShowHelp(Url);
  93. }
  94. }
  95. }
  96. }
  97. TNewRichEdit::Dispatch(AMessage);
  98. }
  99. else
  100. {
  101. TNewRichEdit::Dispatch(AMessage);
  102. }
  103. }
  104. //---------------------------------------------------------------------------
  105. //---------------------------------------------------------------------------
  106. __fastcall TGenerateUrlDialog::TGenerateUrlDialog(
  107. TComponent * Owner, TSessionData * Data, TFilesSelected FilesSelected, TStrings * Paths,
  108. bool Transfer, bool ToRemote, bool Move, int CopyParamAttrs, const UnicodeString & Path, const TCopyParamType & CopyParam)
  109. : TForm(Owner)
  110. {
  111. UseSystemSettings(this);
  112. FData = Data;
  113. if (Paths != NULL)
  114. {
  115. FPaths.reset(new TStringList());
  116. FPaths->AddStrings(Paths);
  117. }
  118. FTransfer = Transfer;
  119. FToRemote = ToRemote;
  120. FMove = Move;
  121. FCopyParamAttrs = CopyParamAttrs;
  122. FCopyParam = CopyParam;
  123. FFilesSelected = FilesSelected;
  124. FPathsSample = false;
  125. FUrlCounted = false;
  126. FScriptCounted = false;
  127. FAssemblyCounted = false;
  128. if (FTransfer)
  129. {
  130. DebugAssert(FPaths.get() != NULL);
  131. const int MaxSample = 3;
  132. if ((FFilesSelected == fsList) && (FPaths->Count > MaxSample))
  133. {
  134. FPathsSample = true;
  135. while (FPaths->Count > MaxSample)
  136. {
  137. FPaths->Delete(FPaths->Count - 1);
  138. }
  139. }
  140. if (FToRemote)
  141. {
  142. UnicodeString FirstPath = Paths->Strings[0];
  143. FSourcePath = FToRemote ? ExcludeTrailingBackslashUnlessRoot(ExtractFilePath(FirstPath)) : UnixExtractFilePath(FirstPath);
  144. for (int Index = 0; Index < FPaths->Count; Index++)
  145. {
  146. FPaths->Strings[Index] = ExtractFileName(FPaths->Strings[Index]);
  147. }
  148. }
  149. else
  150. {
  151. FSourcePath = Data->RemoteDirectory;
  152. // should be noop as we get only file names for remote files
  153. for (int Index = 0; Index < FPaths->Count; Index++)
  154. {
  155. FPaths->Strings[Index] = UnixExtractFileName(FPaths->Strings[Index]);
  156. }
  157. }
  158. }
  159. FPath = Path;
  160. FChanging = false;
  161. FResultMemoWithLinks = new TRichEditWithLinks(this);
  162. FResultMemoWithLinks->Parent = ResultMemo->Parent;
  163. FResultMemoWithLinks->SetBounds(ResultMemo->Left, ResultMemo->Top, ResultMemo->Width, ResultMemo->Height);
  164. FResultMemoWithLinks->Anchors = ResultMemo->Anchors;
  165. FResultMemoWithLinks->BevelInner = ResultMemo->BevelInner;
  166. FResultMemoWithLinks->BevelOuter = ResultMemo->BevelOuter;
  167. FResultMemoWithLinks->BorderStyle = ResultMemo->BorderStyle;
  168. FResultMemoWithLinks->PopupMenu = ResultMemo->PopupMenu;
  169. FResultMemoWithLinks->TabOrder = ResultMemo->TabOrder;
  170. FResultMemoWithLinks->PlainText = false;
  171. FResultMemoWithLinks->WantReturns = false; // affects Esc too, what we want
  172. ResultMemo->Visible = false;
  173. ReadOnlyControl(FResultMemoWithLinks);
  174. }
  175. //---------------------------------------------------------------------------
  176. bool __fastcall TGenerateUrlDialog::IsFileUrl()
  177. {
  178. return (FPaths.get() != NULL) && !FTransfer;
  179. }
  180. //---------------------------------------------------------------------------
  181. UnicodeString __fastcall TGenerateUrlDialog::GenerateUrl(UnicodeString Path)
  182. {
  183. UnicodeString Url =
  184. FData->GenerateSessionUrl(
  185. FLAGMASK(WinSCPSpecificCheck->Checked, sufSpecific) |
  186. FLAGMASK(UserNameCheck->Enabled && UserNameCheck->Checked, sufUserName) |
  187. FLAGMASK(PasswordCheck->Enabled && PasswordCheck->Checked, sufPassword) |
  188. FLAGMASK(HostKeyCheck->Enabled && HostKeyCheck->Checked, sufHostKey) |
  189. FLAGMASK(RawSettingsCheck->Enabled && RawSettingsCheck->Checked, sufRawSettings) |
  190. FLAGMASK(CustomWinConfiguration->HttpForWebDAV, sufHttpForWebDAV));
  191. if ((RemoteDirectoryCheck->Enabled && RemoteDirectoryCheck->Checked) ||
  192. IsFileUrl())
  193. {
  194. if (StartsStr(L"/", Path));
  195. {
  196. Path.Delete(1, 1);
  197. }
  198. Url += EncodeUrlPath(Path);
  199. }
  200. if (SaveExtensionCheck->Enabled && SaveExtensionCheck->Checked)
  201. {
  202. Url += UnicodeString(UrlParamSeparator) + UrlSaveParamName;
  203. }
  204. return Url;
  205. }
  206. //---------------------------------------------------------------------------
  207. static UnicodeString __fastcall RtfColorEntry(int Color)
  208. {
  209. return FORMAT(L"\\red%d\\green%d\\blue%d;", ((Color & 0xFF0000) >> 16, (Color & 0x00FF00) >> 8, (Color & 0x0000FF) >> 0));
  210. }
  211. //---------------------------------------------------------------------
  212. static UnicodeString __fastcall RtfScriptComment(const UnicodeString & Text)
  213. {
  214. return RtfColorItalicText(7, Text);
  215. }
  216. //---------------------------------------------------------------------
  217. static UnicodeString __fastcall RtfScriptPlaceholder(const UnicodeString & Text)
  218. {
  219. return RtfColorText(7, Text);
  220. }
  221. //---------------------------------------------------------------------
  222. static UnicodeString __fastcall RtfScriptCommand(const UnicodeString & Command)
  223. {
  224. return RtfLink(ScriptCommandLink(Command), RtfKeyword(Command));
  225. }
  226. //---------------------------------------------------------------------
  227. UnicodeString __fastcall RtfCommandlineSwitch(const UnicodeString & Switch, const UnicodeString & Anchor)
  228. {
  229. return RtfLink(L"commandline#" + Anchor, RtfParameter(TProgramParams::FormatSwitch(Switch.LowerCase())));
  230. }
  231. //---------------------------------------------------------------------------
  232. static UnicodeString __fastcall QuoteStringParam(UnicodeString S)
  233. {
  234. return AddQuotes(RtfEscapeParam(S, false));
  235. }
  236. //---------------------------------------------------------------------------
  237. // Keep in sync with .NET Session.EscapeFileMask
  238. static UnicodeString __fastcall EscapeFileMask(UnicodeString S)
  239. {
  240. return
  241. ReplaceStr(ReplaceStr(ReplaceStr(ReplaceStr(ReplaceStr(
  242. S, L"[", L"[[]"), L"*", L"[*]"), L"?", L"[?]"), L">", L">>"), L"<", L"<<");
  243. }
  244. //---------------------------------------------------------------------------
  245. UnicodeString __fastcall TGenerateUrlDialog::GenerateUrl()
  246. {
  247. UnicodeString Result;
  248. if (!IsFileUrl())
  249. {
  250. UnicodeString Path = FData->RemoteDirectory;
  251. if (!Path.IsEmpty() && !EndsStr(L"/", Path))
  252. {
  253. Path += L"/";
  254. }
  255. Result = RtfText(GenerateUrl(Path));
  256. }
  257. else
  258. {
  259. for (int Index = 0; Index < FPaths->Count; Index++)
  260. {
  261. UnicodeString Url = GenerateUrl(FPaths->Strings[Index]);
  262. Result += RtfText(Url) + RtfPara;
  263. }
  264. }
  265. return Result;
  266. }
  267. //---------------------------------------------------------------------------
  268. void __fastcall TGenerateUrlDialog::AddSampleDescription(UnicodeString & Description)
  269. {
  270. if (FPathsSample)
  271. {
  272. Description += LoadStr(GENERATE_URL_FILE_SAMPLE) + L"\n";
  273. }
  274. }
  275. //---------------------------------------------------------------------------
  276. UnicodeString __fastcall TGenerateUrlDialog::GenerateScript(UnicodeString & ScriptDescription)
  277. {
  278. UnicodeString Result;
  279. UnicodeString ExeName = Application->ExeName;
  280. UnicodeString BaseExeName = ExtractFileBaseName(ExeName);
  281. UnicodeString OpenCommand = FData->GenerateOpenCommandArgs(true);
  282. UnicodeString CommandPlaceholder1 = FMTLOAD(GENERATE_URL_COMMAND, (1));
  283. UnicodeString CommandPlaceholder2 = FMTLOAD(GENERATE_URL_COMMAND, (2));
  284. UnicodeString LogPath = LoadStr(GENERATE_URL_WRITABLE_PATH_TO_LOG) + RtfText(BaseExeName + L".log");
  285. UnicodeString LogParameter =
  286. RtfCommandlineSwitch(LOG_SWITCH, L"logging") + RtfText(L"=") +
  287. RtfScriptPlaceholder(L"\"" + LogPath + L"\"");
  288. UnicodeString IniParameter =
  289. RtfCommandlineSwitch(INI_SWITCH, L"configuration") + RtfText(UnicodeString(L"=") + INI_NUL);
  290. UnicodeString CommandParameter = RtfCommandlineSwitch(COMMAND_SWITCH, L"scripting");
  291. typedef std::vector<UnicodeString> TCommands;
  292. TCommands Commands;
  293. Commands.push_back(RtfScriptCommand(L"open") + L" " + OpenCommand);
  294. Commands.push_back(UnicodeString());
  295. if (FTransfer)
  296. {
  297. UnicodeString TransferCommand;
  298. if (FToRemote)
  299. {
  300. Commands.push_back(RtfScriptCommand(L"lcd") + L" " + RtfText(QuoteStringParam(FSourcePath)));
  301. Commands.push_back(RtfScriptCommand(L"cd") + L" " + RtfText(QuoteStringParam(UnixExcludeTrailingBackslash(FPath))));
  302. TransferCommand = L"put";
  303. }
  304. else
  305. {
  306. Commands.push_back(RtfScriptCommand(L"cd") + L" " + RtfText(QuoteStringParam(FSourcePath)));
  307. Commands.push_back(RtfScriptCommand(L"lcd") + L" " + RtfText(QuoteStringParam(ExcludeTrailingBackslashUnlessRoot(FPath))));
  308. TransferCommand = L"get";
  309. }
  310. Commands.push_back(UnicodeString());
  311. UnicodeString TransferCommandLink = ScriptCommandLink(TransferCommand);
  312. UnicodeString TransferCommandArgs;
  313. if (FMove)
  314. {
  315. TransferCommandArgs += RtfSwitch(DELETE_SWITCH, TransferCommandLink);
  316. }
  317. TransferCommandArgs += FCopyParam.GenerateTransferCommandArgs(FCopyParamAttrs, TransferCommandLink);
  318. AddSampleDescription(ScriptDescription);
  319. TransferCommand = RtfScriptCommand(TransferCommand) + TransferCommandArgs;
  320. if (FFilesSelected == fsList)
  321. {
  322. for (int Index = 0; Index < FPaths->Count; Index++)
  323. {
  324. UnicodeString Path = ExtractFileName(FPaths->Strings[Index], !FToRemote);
  325. if (!FToRemote)
  326. {
  327. Path = EscapeFileMask(Path);
  328. }
  329. Commands.push_back(TransferCommand + L" " + RtfText(QuoteStringParam(Path)));
  330. }
  331. }
  332. else
  333. {
  334. Commands.push_back(TransferCommand + L" " + RtfText(AllFilesMask));
  335. }
  336. }
  337. else
  338. {
  339. Commands.push_back(L"# " + CommandPlaceholder1);
  340. Commands.push_back(L"# " + CommandPlaceholder2);
  341. }
  342. Commands.push_back(UnicodeString());
  343. Commands.push_back(RtfScriptCommand(L"exit"));
  344. UnicodeString ComExeName = ChangeFileExt(ExeName, L".com");
  345. if (ScriptFormatCombo->ItemIndex == sfScriptFile)
  346. {
  347. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  348. {
  349. UnicodeString Command = *I;
  350. if (!Command.IsEmpty())
  351. {
  352. if (Command[1] == L'#')
  353. {
  354. Result += RtfScriptComment(Command);
  355. }
  356. else
  357. {
  358. Result += Command;
  359. }
  360. }
  361. Result += RtfPara;
  362. }
  363. UnicodeString ScriptCommandLine =
  364. FORMAT("\"%s\" /%s=\"%s\" /%s=%s /%s=\"%s\"",
  365. (ExeName, LowerCase(LOG_SWITCH), LogPath, LowerCase(INI_SWITCH), INI_NUL, LowerCase(SCRIPT_SWITCH), LoadStr(GENERATE_URL_PATH_TO_SCRIPT)));
  366. Result +=
  367. RtfPara +
  368. RtfScriptComment(L"# " + LoadStr(GENERATE_URL_SCRIPT_DESC)) + RtfPara +
  369. RtfScriptComment(L"# " + ScriptCommandLine) + RtfPara;
  370. }
  371. else if (ScriptFormatCombo->ItemIndex == sfBatchFile)
  372. {
  373. Result =
  374. RtfScriptPlaceholder(L"@echo off") + RtfPara +
  375. RtfPara +
  376. RtfText(L"\"" + ComExeName + "\" ^") + RtfPara +
  377. RtfText(L" ") + LogParameter + L" " + IniParameter + RtfText(L" ^") + RtfPara +
  378. RtfText(L" ") + CommandParameter;
  379. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  380. {
  381. UnicodeString Command = *I;
  382. if (!Command.IsEmpty())
  383. {
  384. Result +=
  385. RtfText(L" ^") + RtfPara +
  386. RtfText(L" \"");
  387. if (Command[1] == L'#')
  388. {
  389. Command.Delete(1, 1);
  390. Result += RtfScriptPlaceholder(Command.TrimLeft());
  391. }
  392. else
  393. {
  394. Result += RtfEscapeParam(ReplaceStr(Command, L"%", L"%%"), false);
  395. }
  396. Result += L"\"";
  397. }
  398. }
  399. Result +=
  400. RtfPara +
  401. RtfPara +
  402. RtfKeyword(L"set") + RtfText(L" WINSCP_RESULT=%ERRORLEVEL%") + RtfPara +
  403. RtfKeyword(L"if") + RtfText(L" %WINSCP_RESULT% ") + RtfKeyword(L"equ") + RtfText(L" 0 (") + RtfPara +
  404. RtfText(L" ") + RtfKeyword(L"echo") + RtfText(L" Success") + RtfPara +
  405. RtfText(L") ") + RtfKeyword(L"else") + RtfText(L" (") + RtfPara +
  406. RtfText(L" ") + RtfKeyword(L"echo") + RtfText(L" Error") + RtfPara +
  407. RtfText(L")") + RtfPara +
  408. RtfPara +
  409. RtfKeyword(L"exit") + RtfText(L" /b %WINSCP_RESULT%") + RtfPara;
  410. }
  411. else if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  412. {
  413. Result =
  414. LogParameter + L" " +
  415. IniParameter + L" " +
  416. CommandParameter;
  417. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  418. {
  419. UnicodeString Command = *I;
  420. if (!Command.IsEmpty())
  421. {
  422. Result += RtfText(L" \"");
  423. if (Command[1] == L'#')
  424. {
  425. Command.Delete(1, 1);
  426. Result += RtfScriptPlaceholder(Command.TrimLeft());
  427. }
  428. else
  429. {
  430. Result += RtfEscapeParam(Command, false);
  431. }
  432. Result += L"\"";
  433. }
  434. }
  435. }
  436. else if (ScriptFormatCombo->ItemIndex == sfPowerShell)
  437. {
  438. // https://stackoverflow.com/q/74440303/850848
  439. UnicodeString PsArgPassingLink(L"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables#psnativecommandargumentpassing");
  440. Result =
  441. RtfLink(PsArgPassingLink, RtfScriptComment(FORMAT(L"# %s", (LoadStr(GENERATE_URL_PS_ARG_PASSING))))) + RtfPara +
  442. RtfLink(PsArgPassingLink, L"$PSNativeCommandArgumentPassing") + L" = " + AssemblyString(alPowerShell, L"Legacy") + RtfPara +
  443. RtfPara +
  444. RtfText(L"& \"" + ComExeName + "\" `") + RtfPara +
  445. RtfText(L" ") + LogParameter + L" " + IniParameter + RtfText(L" `") + RtfPara +
  446. RtfText(L" ") + CommandParameter;
  447. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  448. {
  449. UnicodeString Command = *I;
  450. if (!Command.IsEmpty())
  451. {
  452. Result += RtfText(L" `") + RtfPara + RtfText(L" \"");
  453. if (Command[1] == L'#')
  454. {
  455. Command.Delete(1, 1);
  456. Result += RtfScriptPlaceholder(Command.TrimLeft());
  457. }
  458. else
  459. {
  460. Command = ReplaceStr(Command, L"`", L"``");
  461. Command = ReplaceStr(Command, L"$", L"`$");
  462. Result += RtfEscapeParam(Command, true);
  463. }
  464. Result += L"\"";
  465. }
  466. }
  467. Result +=
  468. RtfPara +
  469. RtfPara +
  470. RtfText(L"$winscpResult = $LastExitCode") + RtfPara +
  471. RtfKeyword(L"if") + RtfText(L" ($winscpResult -eq 0)") + RtfPara +
  472. RtfText(L"{") + RtfPara +
  473. RtfText(L" ") + RtfKeyword(L"Write-Host") + L" " + RtfString(L"\"Success\"") + RtfPara +
  474. RtfText(L"}") + RtfPara +
  475. RtfText(L"else") + RtfPara +
  476. RtfText(L"{") + RtfPara +
  477. RtfText(L" ") + RtfKeyword(L"Write-Host") + L" " + RtfString(L"\"Error\"") + RtfPara +
  478. RtfText(L"}") + RtfPara +
  479. RtfPara +
  480. RtfKeyword(L"exit") + RtfText(L" $winscpResult") + RtfPara;
  481. }
  482. return Result;
  483. }
  484. //---------------------------------------------------------------------------
  485. UnicodeString __fastcall TGenerateUrlDialog::GenerateAssemblyCode(UnicodeString & AssemblyDescription)
  486. {
  487. TAssemblyLanguage Language = static_cast<TAssemblyLanguage>(AssemblyLanguageCombo->ItemIndex);
  488. UnicodeString Head;
  489. UnicodeString Tail;
  490. int Indent;
  491. FData->GenerateAssemblyCode(Language, Head, Tail, Indent);
  492. UnicodeString Result = Head;
  493. UnicodeString Code;
  494. if (FTransfer)
  495. {
  496. UnicodeString CopyParamProperties = FCopyParam.GenerateAssemblyCode(Language, FCopyParamAttrs);
  497. bool HasTransferOptions = !CopyParamProperties.IsEmpty();
  498. if (HasTransferOptions)
  499. {
  500. Code +=
  501. AssemblyCommentLine(Language, LoadStr(GENERATE_URL_COPY_PARAM)) +
  502. CopyParamProperties +
  503. RtfPara;
  504. }
  505. Code += AssemblyCommentLine(Language, LoadStr(GENERATE_URL_TRANSFER_FILES));
  506. AddSampleDescription(AssemblyDescription);
  507. UnicodeString DestPath = FPath;
  508. UnicodeString TransferMethodName;
  509. if (FToRemote)
  510. {
  511. TransferMethodName = L"PutFiles";
  512. DestPath = UnixIncludeTrailingBackslash(DestPath);
  513. }
  514. else
  515. {
  516. TransferMethodName = L"GetFiles";
  517. DestPath = IncludeTrailingBackslash(DestPath);
  518. }
  519. DestPath += NoOpOperationMask;
  520. UnicodeString DestPathVariableName = AssemblyVariableName(Language, L"remotePath");
  521. UnicodeString StatementSeparator = AssemblyStatementSeparator(Language);
  522. UnicodeString DestPathString = AssemblyString(Language, DestPath);
  523. UnicodeString DestPathCode;
  524. if ((FFilesSelected != fsList) || (FPaths->Count == 1))
  525. {
  526. DestPathCode = DestPathString;
  527. }
  528. else
  529. {
  530. switch (Language)
  531. {
  532. case alCSharp:
  533. Code += RtfKeyword(L"const") + L" " + RtfKeyword(L"string") + L" " + DestPathVariableName;
  534. break;
  535. case alVBNET:
  536. Code += RtfKeyword(L"Const") + L" " + DestPathVariableName;
  537. break;
  538. case alPowerShell:
  539. Code += DestPathVariableName;
  540. break;
  541. }
  542. Code += L" = " + DestPathString + StatementSeparator + RtfPara;
  543. DestPathCode = DestPathVariableName;
  544. }
  545. UnicodeString TransferMethodCallStart =
  546. AssemblyVariableName(Language, SessionClassName) + L"." +
  547. RtfLibraryMethod(SessionClassName, TransferMethodName, false) + L"(";
  548. const UnicodeString ParameterSeparator = L", ";
  549. UnicodeString TransferMethodCallEnd = ParameterSeparator + DestPathCode;
  550. if (FMove || HasTransferOptions)
  551. {
  552. TransferMethodCallEnd += ParameterSeparator + AssemblyBoolean(Language, FMove);
  553. }
  554. if (HasTransferOptions)
  555. {
  556. TransferMethodCallEnd += ParameterSeparator + AssemblyVariableName(Language, TransferOptionsClassName);
  557. }
  558. TransferMethodCallEnd +=
  559. L")." + RtfLibraryMethod(L"OperationResultBase", L"Check", true) + L"()" +
  560. StatementSeparator + RtfPara;
  561. if (FFilesSelected == fsList)
  562. {
  563. for (int Index = 0; Index < FPaths->Count; Index++)
  564. {
  565. UnicodeString FileName = FPaths->Strings[Index];
  566. UnicodeString Path;
  567. if (!FToRemote)
  568. {
  569. Path = UnixIncludeTrailingBackslash(FSourcePath) + FileName;
  570. }
  571. else
  572. {
  573. Path = IncludeTrailingBackslash(FSourcePath) + FileName;
  574. }
  575. UnicodeString PathCode = AssemblyString(Language, Path);
  576. if (!FToRemote && (FileName != EscapeFileMask(FileName)))
  577. {
  578. PathCode =
  579. AssemblyVariableName(Language, SessionClassName) + L"." +
  580. RtfLibraryMethod(SessionClassName, L"EscapeFileMask", false) + L"(" + PathCode + L")";
  581. }
  582. Code += TransferMethodCallStart + PathCode + TransferMethodCallEnd;
  583. }
  584. }
  585. else
  586. {
  587. UnicodeString SourcePath = FSourcePath;
  588. if (FToRemote)
  589. {
  590. SourcePath = IncludeTrailingBackslash(SourcePath);
  591. }
  592. else
  593. {
  594. SourcePath = UnixIncludeTrailingBackslash(SourcePath);
  595. }
  596. SourcePath += AllFilesMask;
  597. Code += TransferMethodCallStart + AssemblyString(Language, SourcePath) + TransferMethodCallEnd;
  598. }
  599. }
  600. else
  601. {
  602. Code = AssemblyCommentLine(Language, LoadStr(GENERATE_URL_YOUR_CODE));
  603. }
  604. UnicodeString Indentation = UnicodeString::StringOfChar(L' ', Indent);
  605. Code = Indentation + ReplaceStr(Code, RtfPara, RtfPara + Indentation);
  606. if (DebugAlwaysTrue(Code.SubString(Code.Length() - Indentation.Length() + 1, Indentation.Length()) == Indentation))
  607. {
  608. Code.SetLength(Code.Length() - Indentation.Length());
  609. }
  610. Result += Code;
  611. Result += Tail;
  612. return Result;
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TGenerateUrlDialog::UpdateControls()
  616. {
  617. if (!FChanging)
  618. {
  619. int CaptionId;
  620. if (FTransfer)
  621. {
  622. CaptionId = GENERATE_URL_TRANSFER_TITLE;
  623. }
  624. else
  625. {
  626. CaptionId = IsFileUrl() ? GENERATE_URL_FILE_TITLE : GENERATE_URL_SESSION_TITLE;
  627. }
  628. Caption = LoadStr(CaptionId);
  629. UrlSheet->TabVisible = !FTransfer;
  630. ScriptSheet->TabVisible = !IsFileUrl();
  631. AssemblySheet->TabVisible = !IsFileUrl();
  632. bool HostKeyUnknown = FData->UsesSsh && FData->HostKey.IsEmpty();
  633. UnicodeString ResultGroupCaption;
  634. if (OptionsPageControl->ActivePage == UrlSheet)
  635. {
  636. ResultGroupCaption = LoadStr(GENERATE_URL_URL);
  637. }
  638. else if (OptionsPageControl->ActivePage == ScriptSheet)
  639. {
  640. if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  641. {
  642. ResultGroupCaption = LoadStr(GENERATE_URL_COMMANDLINE_LABEL);
  643. }
  644. else
  645. {
  646. ResultGroupCaption = ScriptFormatCombo->Items->Strings[ScriptFormatCombo->ItemIndex];
  647. }
  648. }
  649. else if (DebugAlwaysTrue(OptionsPageControl->ActivePage == AssemblySheet))
  650. {
  651. ResultGroupCaption = LoadStr(GENERATE_URL_CODE);
  652. }
  653. ResultGroup->Caption = ResultGroupCaption;
  654. EnableControl(UserNameCheck, !FData->UserNameExpanded.IsEmpty());
  655. bool UserNameIncluded = UserNameCheck->Enabled && UserNameCheck->Checked;
  656. EnableControl(PasswordCheck, UserNameIncluded && FData->HasPassword());
  657. EnableControl(HostKeyCheck, UserNameIncluded && !FData->HostKey.IsEmpty());
  658. EnableControl(RemoteDirectoryCheck, !FData->RemoteDirectory.IsEmpty() && !IsFileUrl());
  659. EnableControl(SaveExtensionCheck, !IsFileUrl());
  660. EnableControl(RawSettingsCheck, UserNameIncluded && FData->HasRawSettingsForUrl());
  661. UnicodeString Result;
  662. bool * Counted = NULL;
  663. UnicodeString CounterName;
  664. bool WordWrap = false; // shut up
  665. bool FixedWidth = false; // shut up
  666. if (OptionsPageControl->ActivePage == UrlSheet)
  667. {
  668. Counted = &FUrlCounted;
  669. CounterName = L"GeneratedUrls";
  670. Result = GenerateUrl();
  671. WordWrap = true;
  672. FixedWidth = false;
  673. }
  674. else if (OptionsPageControl->ActivePage == ScriptSheet)
  675. {
  676. Counted = &FScriptCounted;
  677. CounterName = FTransfer ? L"GeneratedScriptsTransfer" : L"GeneratedScripts";
  678. UnicodeString ScriptDescription;
  679. if (ScriptFormatCombo->ItemIndex == sfScriptFile)
  680. {
  681. WordWrap = false;
  682. FixedWidth = true;
  683. }
  684. else if (ScriptFormatCombo->ItemIndex == sfBatchFile)
  685. {
  686. WordWrap = false;
  687. FixedWidth = true;
  688. }
  689. else if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  690. {
  691. WordWrap = true;
  692. FixedWidth = false;
  693. ScriptDescription = FMTLOAD(GENERATE_URL_COMMANDLINE_DESC, (FORMAT("\"%s\"", (Application->ExeName)))) + L"\n";
  694. }
  695. else if (ScriptFormatCombo->ItemIndex == sfPowerShell)
  696. {
  697. WordWrap = false;
  698. FixedWidth = true;
  699. }
  700. if (HostKeyUnknown)
  701. {
  702. ScriptDescription += LoadStr(GENERATE_URL_HOSTKEY_UNKNOWN) + L"\n";
  703. }
  704. Result = GenerateScript(ScriptDescription);
  705. ScriptDescriptionLabel->Caption = ScriptDescription;
  706. }
  707. else if (DebugAlwaysTrue(OptionsPageControl->ActivePage == AssemblySheet))
  708. {
  709. Counted = &FAssemblyCounted;
  710. CounterName = FTransfer ? L"GeneratedCodesTransfer" : L"GeneratedCodes";
  711. UnicodeString AssemblyDescription;
  712. if (HostKeyUnknown)
  713. {
  714. AssemblyDescription += LoadStr(GENERATE_URL_HOSTKEY_UNKNOWN) + L"\n";
  715. }
  716. Result = GenerateAssemblyCode(AssemblyDescription);
  717. AssemblyDescriptionLabel->Caption = AssemblyDescription;
  718. WordWrap = false;
  719. FixedWidth = true;
  720. }
  721. if (FixedWidth)
  722. {
  723. FResultMemoWithLinks->Font->Name = CustomWinConfiguration->DefaultFixedWidthFontName;
  724. }
  725. else
  726. {
  727. FResultMemoWithLinks->Font->Name = Font->Name;
  728. }
  729. if (!CounterName.IsEmpty() && !(*Counted))
  730. {
  731. (*Counted) = true;
  732. Configuration->Usage->Inc(CounterName);
  733. }
  734. Result =
  735. L"{\\rtf1\n"
  736. "{\\colortbl ;" +
  737. // The same RGB as on wiki
  738. RtfColorEntry(0x010101) + // near-black fake color to be used with no-style link to override the default blue underline
  739. RtfColorEntry(0x008000) + // code comment (green)
  740. RtfColorEntry(0x008080) + // class (teal)
  741. RtfColorEntry(0x800000) + // string (maroon)
  742. RtfColorEntry(0x0000FF) + // keyword (blue)
  743. RtfColorEntry(0x993333) + // command-line argument (reddish)
  744. RtfColorEntry(0x808080) + // script command (gray)
  745. L"}\n"
  746. "{\\fonttbl{\\f0\\fnil\\fcharset0 " + FResultMemoWithLinks->Font->Name + L";}}\n"
  747. "\\f0\\fs" + IntToStr(FResultMemoWithLinks->Font->Size * 2) + L" " +
  748. Result +
  749. "}";
  750. FResultMemoWithLinks->WordWrap = WordWrap;
  751. FResultMemoWithLinks->ScrollBars = WordWrap ? ssVertical : ssBoth;
  752. std::unique_ptr<TMemoryStream> Stream(new TMemoryStream());
  753. UTF8String ResultUtf = Result;
  754. Stream->Write(ResultUtf.c_str(), ResultUtf.Length());
  755. Stream->Position = 0;
  756. FResultMemoWithLinks->Perform(WM_VSCROLL, SB_TOP, 0);
  757. FResultMemoWithLinks->Lines->LoadFromStream(Stream.get(), TEncoding::UTF8);
  758. }
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TGenerateUrlDialog::Execute()
  762. {
  763. int Components = WinConfiguration->GenerateUrlComponents;
  764. if (Components < 0)
  765. {
  766. Components = UserNameCheck->Tag | RemoteDirectoryCheck->Tag;
  767. }
  768. TGenerateUrlCodeTarget Target = WinConfiguration->GenerateUrlCodeTarget;
  769. {
  770. TAutoFlag ChangingFlag(FChanging);
  771. if (IsFileUrl())
  772. {
  773. OptionsPageControl->ActivePage = UrlSheet;
  774. }
  775. else
  776. {
  777. switch (Target)
  778. {
  779. case guctUrl:
  780. OptionsPageControl->ActivePage = UrlSheet;
  781. break;
  782. case guctScript:
  783. OptionsPageControl->ActivePage = ScriptSheet;
  784. break;
  785. case guctAssembly:
  786. OptionsPageControl->ActivePage = AssemblySheet;
  787. break;
  788. default:
  789. DebugFail();
  790. }
  791. }
  792. for (int Index = 0; Index < UrlSheet->ControlCount; Index++)
  793. {
  794. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(UrlSheet->Controls[Index]);
  795. if (DebugAlwaysTrue((CheckBox != NULL) && (CheckBox->Tag != 0)))
  796. {
  797. CheckBox->Checked = FLAGSET(Components, CheckBox->Tag);
  798. }
  799. }
  800. ScriptFormatCombo->ItemIndex = WinConfiguration->GenerateUrlScriptFormat;
  801. AssemblyLanguageCombo->ItemIndex = WinConfiguration->GenerateUrlAssemblyLanguage;
  802. }
  803. UpdateControls();
  804. if (OptionsPageControl->ActivePage != UrlSheet)
  805. {
  806. ClientWidth = ScaleByTextHeightRunTime(this, 700);
  807. ClientHeight = ScaleByTextHeightRunTime(this, 600);
  808. }
  809. ShowModal();
  810. // Do not save the selection for files as the "URL" was selected implicitly
  811. if (!IsFileUrl())
  812. {
  813. if (OptionsPageControl->ActivePage == UrlSheet)
  814. {
  815. Target = guctUrl;
  816. }
  817. else if (OptionsPageControl->ActivePage == ScriptSheet)
  818. {
  819. Target = guctScript;
  820. }
  821. else if (OptionsPageControl->ActivePage == AssemblySheet)
  822. {
  823. Target = guctAssembly;
  824. }
  825. else
  826. {
  827. DebugFail();
  828. }
  829. WinConfiguration->GenerateUrlCodeTarget = Target;
  830. }
  831. if (Target == guctUrl)
  832. {
  833. Components = 0;
  834. for (int Index = 0; Index < UrlSheet->ControlCount; Index++)
  835. {
  836. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(UrlSheet->Controls[Index]);
  837. if (DebugAlwaysTrue((CheckBox != NULL) && (CheckBox->Tag != 0)) &&
  838. CheckBox->Checked)
  839. {
  840. Components |= CheckBox->Tag;
  841. }
  842. }
  843. WinConfiguration->GenerateUrlComponents = Components;
  844. }
  845. else if (Target == guctScript)
  846. {
  847. WinConfiguration->GenerateUrlScriptFormat = static_cast<TScriptFormat>(ScriptFormatCombo->ItemIndex);
  848. }
  849. else if (Target == guctAssembly)
  850. {
  851. WinConfiguration->GenerateUrlAssemblyLanguage = static_cast<TAssemblyLanguage>(AssemblyLanguageCombo->ItemIndex);
  852. }
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TGenerateUrlDialog::ControlChange(TObject * /*Sender*/)
  856. {
  857. UpdateControls();
  858. }
  859. //---------------------------------------------------------------------------
  860. void __fastcall TGenerateUrlDialog::ClipboardButtonClick(TObject * /*Sender*/)
  861. {
  862. TInstantOperationVisualizer Visualizer;
  863. // Cannot read the text from FResultMemoWithLinks->Lines as TRichEdit (as opposite to TMemo)
  864. // breaks wrapped lines
  865. UnicodeString Text = FResultMemoWithLinks->Text;
  866. UnicodeString EOL = sLineBreak;
  867. int P = Pos(EOL, Text);
  868. // Trim the EOL of the only string, what CopyToClipboard(FResultMemoWithLinks->Lines) would have done.
  869. // It probably never happens as rich edit does not return EOL on the last line.
  870. if (DebugAlwaysFalse(P == Text.Length() - EOL.Length() + 1))
  871. {
  872. Text.SetLength(Text.Length() - EOL.Length());
  873. }
  874. // Add trailing EOL, if there are multiple lines (see above)
  875. else if ((P > 0) && !EndsStr(EOL, Text))
  876. {
  877. Text += EOL;
  878. }
  879. Text = RtfRemoveHyperlinks(Text);
  880. CopyToClipboard(Text);
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TGenerateUrlDialog::HelpButtonClick(TObject * /*Sender*/)
  884. {
  885. FormHelp(this);
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall TGenerateUrlDialog::WMNCCreate(TWMNCCreate & Message)
  889. {
  890. // bypass TForm::WMNCCreate to prevent disabling "resize"
  891. // (which is done for bsDialog, see comments in CreateParams)
  892. DefaultHandler(&Message);
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall TGenerateUrlDialog::Dispatch(void * AMessage)
  896. {
  897. TMessage & Message = *reinterpret_cast<TMessage *>(AMessage);
  898. if (Message.Msg == WM_NCCREATE)
  899. {
  900. WMNCCreate(*reinterpret_cast<TWMNCCreate *>(AMessage));
  901. }
  902. else
  903. {
  904. TForm::Dispatch(AMessage);
  905. }
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TGenerateUrlDialog::CreateParams(TCreateParams & Params)
  909. {
  910. TForm::CreateParams(Params);
  911. // Allow resizing of the window, even if this is bsDialog.
  912. // This makes it more close to bsSizeable, but bsSizeable cannot for some
  913. // reason receive focus, if window is shown atop non-main window
  914. // (like editor)
  915. Params.Style = Params.Style | WS_THICKFRAME;
  916. }
  917. //---------------------------------------------------------------------------
  918. void __fastcall TGenerateUrlDialog::FormShow(TObject * /*Sender*/)
  919. {
  920. UpdateControls();
  921. }
  922. //---------------------------------------------------------------------------