GenerateUrl.cpp 33 KB

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