GenerateUrl.cpp 33 KB

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