GenerateUrl.cpp 34 KB

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