GenerateUrl.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. 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 ReplaceStr(ReplaceStr(ReplaceStr(S, L"[", L"[[]"), L"*", L"[*]"), L"?", L"[?]");
  235. }
  236. //---------------------------------------------------------------------------
  237. UnicodeString __fastcall TGenerateUrlDialog::GenerateUrl()
  238. {
  239. UnicodeString Result;
  240. if (!IsFileUrl())
  241. {
  242. UnicodeString Path = FData->RemoteDirectory;
  243. if (!Path.IsEmpty() && !EndsStr(L"/", Path))
  244. {
  245. Path += L"/";
  246. }
  247. Result = RtfText(GenerateUrl(Path));
  248. }
  249. else
  250. {
  251. for (int Index = 0; Index < FPaths->Count; Index++)
  252. {
  253. UnicodeString Url = GenerateUrl(FPaths->Strings[Index]);
  254. Result += RtfText(Url) + RtfPara;
  255. }
  256. }
  257. return Result;
  258. }
  259. //---------------------------------------------------------------------------
  260. void __fastcall TGenerateUrlDialog::AddSampleDescription(UnicodeString & Description)
  261. {
  262. if (FPathsSample)
  263. {
  264. Description += LoadStr(GENERATE_URL_FILE_SAMPLE) + L"\n";
  265. }
  266. }
  267. //---------------------------------------------------------------------------
  268. UnicodeString __fastcall TGenerateUrlDialog::GenerateScript(UnicodeString & ScriptDescription)
  269. {
  270. UnicodeString Result;
  271. UnicodeString ExeName = Application->ExeName;
  272. UnicodeString BaseExeName = ExtractFileBaseName(ExeName);
  273. UnicodeString OpenCommand = FData->GenerateOpenCommandArgs(true);
  274. UnicodeString CommandPlaceholder1 = FMTLOAD(GENERATE_URL_COMMAND, (1));
  275. UnicodeString CommandPlaceholder2 = FMTLOAD(GENERATE_URL_COMMAND, (2));
  276. UnicodeString LogPath = LoadStr(GENERATE_URL_WRITABLE_PATH_TO_LOG) + RtfText(BaseExeName + L".log");
  277. UnicodeString LogParameter =
  278. RtfCommandlineSwitch(LOG_SWITCH, L"logging") + RtfText(L"=") +
  279. RtfScriptPlaceholder(L"\"" + LogPath + L"\"");
  280. UnicodeString IniParameter =
  281. RtfCommandlineSwitch(INI_SWITCH, L"configuration") + RtfText(UnicodeString(L"=") + INI_NUL);
  282. UnicodeString CommandParameter = RtfCommandlineSwitch(COMMAND_SWITCH, L"scripting");
  283. typedef std::vector<UnicodeString> TCommands;
  284. TCommands Commands;
  285. Commands.push_back(RtfScriptCommand(L"open") + L" " + OpenCommand);
  286. Commands.push_back(UnicodeString());
  287. if (FTransfer)
  288. {
  289. UnicodeString TransferCommand;
  290. if (FToRemote)
  291. {
  292. Commands.push_back(RtfScriptCommand(L"lcd") + L" " + RtfText(QuoteStringParam(FSourcePath)));
  293. Commands.push_back(RtfScriptCommand(L"cd") + L" " + RtfText(QuoteStringParam(UnixExcludeTrailingBackslash(FPath))));
  294. TransferCommand = L"put";
  295. }
  296. else
  297. {
  298. Commands.push_back(RtfScriptCommand(L"cd") + L" " + RtfText(QuoteStringParam(FSourcePath)));
  299. Commands.push_back(RtfScriptCommand(L"lcd") + L" " + RtfText(QuoteStringParam(ExcludeTrailingBackslashUnlessRoot(FPath))));
  300. TransferCommand = L"get";
  301. }
  302. Commands.push_back(UnicodeString());
  303. UnicodeString TransferCommandLink = ScriptCommandLink(TransferCommand);
  304. UnicodeString TransferCommandArgs;
  305. if (FMove)
  306. {
  307. TransferCommandArgs += RtfSwitch(DELETE_SWITCH, TransferCommandLink);
  308. }
  309. bool NoArgs;
  310. TransferCommandArgs += FCopyParam.GenerateTransferCommandArgs(FCopyParamAttrs, TransferCommandLink, NoArgs);
  311. if (NoArgs)
  312. {
  313. ScriptDescription += LoadStr(GENERATE_URL_COPY_PARAM_SCRIPT_REMAINING) + L"\n";
  314. }
  315. AddSampleDescription(ScriptDescription);
  316. TransferCommand = RtfScriptCommand(TransferCommand) + TransferCommandArgs;
  317. if (FFilesSelected == fsList)
  318. {
  319. for (int Index = 0; Index < FPaths->Count; Index++)
  320. {
  321. UnicodeString Path = ExtractFileName(FPaths->Strings[Index], !FToRemote);
  322. if (!FToRemote)
  323. {
  324. Path = EscapeFileMask(Path);
  325. }
  326. Commands.push_back(TransferCommand + L" " + RtfText(QuoteStringParam(Path)));
  327. }
  328. }
  329. else
  330. {
  331. Commands.push_back(TransferCommand + L" " + RtfText(AllFilesMask));
  332. }
  333. }
  334. else
  335. {
  336. Commands.push_back(L"# " + CommandPlaceholder1);
  337. Commands.push_back(L"# " + CommandPlaceholder2);
  338. }
  339. Commands.push_back(UnicodeString());
  340. Commands.push_back(RtfScriptCommand(L"exit"));
  341. UnicodeString ComExeName = ChangeFileExt(ExeName, L".com");
  342. if (ScriptFormatCombo->ItemIndex == sfScriptFile)
  343. {
  344. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  345. {
  346. UnicodeString Command = *I;
  347. if (!Command.IsEmpty())
  348. {
  349. if (Command[1] == L'#')
  350. {
  351. Result += RtfScriptComment(Command);
  352. }
  353. else
  354. {
  355. Result += Command;
  356. }
  357. }
  358. Result += RtfPara;
  359. }
  360. UnicodeString ScriptCommandLine =
  361. FORMAT("\"%s\" /%s=\"%s\" /%s=%s /%s=\"%s\"",
  362. (ExeName, LowerCase(LOG_SWITCH), LogPath, LowerCase(INI_SWITCH), INI_NUL, LowerCase(SCRIPT_SWITCH), LoadStr(GENERATE_URL_PATH_TO_SCRIPT)));
  363. Result +=
  364. RtfPara +
  365. RtfScriptComment(L"# " + LoadStr(GENERATE_URL_SCRIPT_DESC)) + RtfPara +
  366. RtfScriptComment(L"# " + ScriptCommandLine) + RtfPara;
  367. }
  368. else if (ScriptFormatCombo->ItemIndex == sfBatchFile)
  369. {
  370. Result =
  371. RtfScriptPlaceholder(L"@echo off") + RtfPara +
  372. RtfPara +
  373. RtfText(L"\"" + ComExeName + "\" ^") + RtfPara +
  374. RtfText(L" ") + LogParameter + L" " + IniParameter + RtfText(L" ^") + RtfPara +
  375. RtfText(L" ") + CommandParameter;
  376. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  377. {
  378. UnicodeString Command = *I;
  379. if (!Command.IsEmpty())
  380. {
  381. Result +=
  382. RtfText(L" ^") + RtfPara +
  383. RtfText(L" \"");
  384. if (Command[1] == L'#')
  385. {
  386. Command.Delete(1, 1);
  387. Result += RtfScriptPlaceholder(Command.TrimLeft());
  388. }
  389. else
  390. {
  391. Result += RtfEscapeParam(ReplaceStr(Command, L"%", L"%%"), false);
  392. }
  393. Result += L"\"";
  394. }
  395. }
  396. Result +=
  397. RtfPara +
  398. RtfPara +
  399. RtfKeyword(L"set") + RtfText(L" WINSCP_RESULT=%ERRORLEVEL%") + RtfPara +
  400. RtfKeyword(L"if") + RtfText(L" %WINSCP_RESULT% ") + RtfKeyword(L"equ") + RtfText(L" 0 (") + RtfPara +
  401. RtfText(L" ") + RtfKeyword(L"echo") + RtfText(L" Success") + RtfPara +
  402. RtfText(L") ") + RtfKeyword(L"else") + RtfText(L" (") + RtfPara +
  403. RtfText(L" ") + RtfKeyword(L"echo") + RtfText(L" Error") + RtfPara +
  404. RtfText(L")") + RtfPara +
  405. RtfPara +
  406. RtfKeyword(L"exit") + RtfText(L" /b %WINSCP_RESULT%") + RtfPara;
  407. }
  408. else if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  409. {
  410. Result =
  411. LogParameter + L" " +
  412. IniParameter + L" " +
  413. CommandParameter;
  414. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  415. {
  416. UnicodeString Command = *I;
  417. if (!Command.IsEmpty())
  418. {
  419. Result += RtfText(L" \"");
  420. if (Command[1] == L'#')
  421. {
  422. Command.Delete(1, 1);
  423. Result += RtfScriptPlaceholder(Command.TrimLeft());
  424. }
  425. else
  426. {
  427. Result += RtfEscapeParam(Command, false);
  428. }
  429. Result += L"\"";
  430. }
  431. }
  432. }
  433. else if (ScriptFormatCombo->ItemIndex == sfPowerShell)
  434. {
  435. Result =
  436. RtfText(L"& \"" + ComExeName + "\" `") + RtfPara +
  437. RtfText(L" ") + LogParameter + L" " + IniParameter + RtfText(L" `") + RtfPara +
  438. RtfText(L" ") + CommandParameter;
  439. for (TCommands::const_iterator I = Commands.begin(); I != Commands.end(); I++)
  440. {
  441. UnicodeString Command = *I;
  442. if (!Command.IsEmpty())
  443. {
  444. Result += RtfText(L" `") + RtfPara + RtfText(L" \"");
  445. if (Command[1] == L'#')
  446. {
  447. Command.Delete(1, 1);
  448. Result += RtfScriptPlaceholder(Command.TrimLeft());
  449. }
  450. else
  451. {
  452. Command = ReplaceStr(Command, L"`", L"``");
  453. Command = ReplaceStr(Command, L"$", L"`$");
  454. Result += RtfEscapeParam(Command, true);
  455. }
  456. Result += L"\"";
  457. }
  458. }
  459. Result +=
  460. RtfPara +
  461. RtfPara +
  462. RtfText(L"$winscpResult = $LastExitCode") + RtfPara +
  463. RtfKeyword(L"if") + RtfText(L" ($winscpResult -eq 0)") + RtfPara +
  464. RtfText(L"{") + RtfPara +
  465. RtfText(L" ") + RtfKeyword(L"Write-Host") + L" " + RtfString(L"\"Success\"") + RtfPara +
  466. RtfText(L"}") + RtfPara +
  467. RtfText(L"else") + RtfPara +
  468. RtfText(L"{") + RtfPara +
  469. RtfText(L" ") + RtfKeyword(L"Write-Host") + L" " + RtfString(L"\"Error\"") + RtfPara +
  470. RtfText(L"}") + RtfPara +
  471. RtfPara +
  472. RtfKeyword(L"exit") + RtfText(L" $winscpResult") + RtfPara;
  473. }
  474. return Result;
  475. }
  476. //---------------------------------------------------------------------------
  477. UnicodeString __fastcall TGenerateUrlDialog::GenerateAssemblyCode(UnicodeString & AssemblyDescription)
  478. {
  479. TAssemblyLanguage Language = static_cast<TAssemblyLanguage>(AssemblyLanguageCombo->ItemIndex);
  480. UnicodeString Head;
  481. UnicodeString Tail;
  482. int Indent;
  483. FData->GenerateAssemblyCode(Language, Head, Tail, Indent);
  484. UnicodeString Result = Head;
  485. UnicodeString Code;
  486. if (FTransfer)
  487. {
  488. bool NoCodeProperties;
  489. UnicodeString CopyParamProperties =
  490. FCopyParam.GenerateAssemblyCode(Language, FCopyParamAttrs, NoCodeProperties);
  491. if (NoCodeProperties)
  492. {
  493. AssemblyDescription += LoadStr(GENERATE_URL_COPY_PARAM_CODE_REMAINING) + L"\n";
  494. }
  495. bool HasTransferOptions = !CopyParamProperties.IsEmpty();
  496. if (HasTransferOptions)
  497. {
  498. Code +=
  499. AssemblyCommentLine(Language, LoadStr(GENERATE_URL_COPY_PARAM)) +
  500. AssemblyNewClassInstanceStart(Language, TransferOptionsClassName, false) +
  501. CopyParamProperties +
  502. AssemblyNewClassInstanceEnd(Language, false) +
  503. RtfPara;
  504. }
  505. Code += AssemblyCommentLine(Language, LoadStr(GENERATE_URL_TRANSFER_FILES));
  506. AddSampleDescription(AssemblyDescription);
  507. UnicodeString DestPath = FPath;
  508. UnicodeString TransferMethodName;
  509. if (FToRemote)
  510. {
  511. TransferMethodName = L"PutFiles";
  512. DestPath = UnixIncludeTrailingBackslash(DestPath);
  513. }
  514. else
  515. {
  516. TransferMethodName = L"GetFiles";
  517. DestPath = IncludeTrailingBackslash(DestPath);
  518. }
  519. DestPath += NoOpOperationMask;
  520. UnicodeString DestPathVariableName = AssemblyVariableName(Language, L"remotePath");
  521. UnicodeString StatementSeparator = AssemblyStatementSeparator(Language);
  522. UnicodeString DestPathString = AssemblyString(Language, DestPath);
  523. UnicodeString DestPathCode;
  524. if ((FFilesSelected != fsList) || (FPaths->Count == 1))
  525. {
  526. DestPathCode = DestPathString;
  527. }
  528. else
  529. {
  530. switch (Language)
  531. {
  532. case alCSharp:
  533. Code += RtfKeyword(L"const") + L" " + RtfKeyword(L"string") + L" " + DestPathVariableName;
  534. break;
  535. case alVBNET:
  536. Code += RtfKeyword(L"Const") + L" " + DestPathVariableName;
  537. break;
  538. case alPowerShell:
  539. Code += DestPathVariableName;
  540. break;
  541. }
  542. Code += L" = " + DestPathString + StatementSeparator + RtfPara;
  543. DestPathCode = DestPathVariableName;
  544. }
  545. UnicodeString TransferMethodCallStart =
  546. AssemblyVariableName(Language, SessionClassName) + L"." +
  547. RtfLibraryMethod(SessionClassName, TransferMethodName, false) + L"(";
  548. const UnicodeString ParameterSeparator = L", ";
  549. UnicodeString TransferMethodCallEnd = ParameterSeparator + DestPathCode;
  550. if (FMove || HasTransferOptions)
  551. {
  552. TransferMethodCallEnd += ParameterSeparator + AssemblyBoolean(Language, FMove);
  553. }
  554. if (HasTransferOptions)
  555. {
  556. TransferMethodCallEnd += ParameterSeparator + AssemblyVariableName(Language, TransferOptionsClassName);
  557. }
  558. TransferMethodCallEnd +=
  559. L")." + RtfLibraryMethod(L"OperationResultBase", L"Check", true) + L"()" +
  560. StatementSeparator + RtfPara;
  561. if (FFilesSelected == fsList)
  562. {
  563. for (int Index = 0; Index < FPaths->Count; Index++)
  564. {
  565. UnicodeString FileName = FPaths->Strings[Index];
  566. UnicodeString Path;
  567. if (!FToRemote)
  568. {
  569. Path = UnixIncludeTrailingBackslash(FSourcePath) + FileName;
  570. }
  571. else
  572. {
  573. Path = IncludeTrailingBackslash(FSourcePath) + FileName;
  574. }
  575. UnicodeString PathCode = AssemblyString(Language, Path);
  576. if (!FToRemote && (FileName != EscapeFileMask(FileName)))
  577. {
  578. PathCode =
  579. AssemblyVariableName(Language, SessionClassName) + L"." +
  580. RtfLibraryMethod(SessionClassName, L"EscapeFileMask", false) + L"(" + PathCode + L")";
  581. }
  582. Code += TransferMethodCallStart + PathCode + TransferMethodCallEnd;
  583. }
  584. }
  585. else
  586. {
  587. UnicodeString SourcePath = FSourcePath;
  588. if (FToRemote)
  589. {
  590. SourcePath = IncludeTrailingBackslash(SourcePath);
  591. }
  592. else
  593. {
  594. SourcePath = UnixIncludeTrailingBackslash(SourcePath);
  595. }
  596. SourcePath += AllFilesMask;
  597. Code += TransferMethodCallStart + AssemblyString(Language, SourcePath) + TransferMethodCallEnd;
  598. }
  599. }
  600. else
  601. {
  602. Code = AssemblyCommentLine(Language, LoadStr(GENERATE_URL_YOUR_CODE));
  603. }
  604. UnicodeString Indentation = UnicodeString::StringOfChar(L' ', Indent);
  605. Code = Indentation + ReplaceStr(Code, RtfPara, RtfPara + Indentation);
  606. if (DebugAlwaysTrue(Code.SubString(Code.Length() - Indentation.Length() + 1, Indentation.Length()) == Indentation))
  607. {
  608. Code.SetLength(Code.Length() - Indentation.Length());
  609. }
  610. Result += Code;
  611. Result += Tail;
  612. return Result;
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TGenerateUrlDialog::UpdateControls()
  616. {
  617. if (!FChanging)
  618. {
  619. int CaptionId;
  620. if (FTransfer)
  621. {
  622. CaptionId = GENERATE_URL_TRANSFER_TITLE;
  623. }
  624. else
  625. {
  626. CaptionId = IsFileUrl() ? GENERATE_URL_FILE_TITLE : GENERATE_URL_SESSION_TITLE;
  627. }
  628. Caption = LoadStr(CaptionId);
  629. UrlSheet->TabVisible = !FTransfer;
  630. ScriptSheet->TabVisible = !IsFileUrl();
  631. AssemblySheet->TabVisible = !IsFileUrl();
  632. bool HostKeyUnknown = FData->UsesSsh && FData->HostKey.IsEmpty();
  633. UnicodeString ResultGroupCaption;
  634. if (OptionsPageControl->ActivePage == UrlSheet)
  635. {
  636. ResultGroupCaption = LoadStr(GENERATE_URL_URL);
  637. }
  638. else if (OptionsPageControl->ActivePage == ScriptSheet)
  639. {
  640. if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  641. {
  642. ResultGroupCaption = LoadStr(GENERATE_URL_COMMANDLINE_LABEL);
  643. }
  644. else
  645. {
  646. ResultGroupCaption = ScriptFormatCombo->Items->Strings[ScriptFormatCombo->ItemIndex];
  647. }
  648. }
  649. else if (DebugAlwaysTrue(OptionsPageControl->ActivePage == AssemblySheet))
  650. {
  651. ResultGroupCaption = LoadStr(GENERATE_URL_CODE);
  652. }
  653. ResultGroup->Caption = ResultGroupCaption;
  654. EnableControl(UserNameCheck, !FData->UserNameExpanded.IsEmpty());
  655. bool UserNameIncluded = UserNameCheck->Enabled && UserNameCheck->Checked;
  656. EnableControl(PasswordCheck, UserNameIncluded && FData->HasPassword());
  657. EnableControl(HostKeyCheck, UserNameIncluded && !FData->HostKey.IsEmpty());
  658. EnableControl(RemoteDirectoryCheck, !FData->RemoteDirectory.IsEmpty() && !IsFileUrl());
  659. EnableControl(SaveExtensionCheck, !IsFileUrl());
  660. EnableControl(RawSettingsCheck, UserNameIncluded && FData->HasRawSettingsForUrl());
  661. UnicodeString Result;
  662. bool * Counted = NULL;
  663. UnicodeString CounterName;
  664. bool WordWrap = false; // shut up
  665. bool FixedWidth = false; // shut up
  666. if (OptionsPageControl->ActivePage == UrlSheet)
  667. {
  668. Counted = &FUrlCounted;
  669. CounterName = L"GeneratedUrls";
  670. Result = GenerateUrl();
  671. WordWrap = true;
  672. FixedWidth = false;
  673. }
  674. else if (OptionsPageControl->ActivePage == ScriptSheet)
  675. {
  676. Counted = &FScriptCounted;
  677. CounterName = FTransfer ? L"GeneratedScriptsTransfer" : L"GeneratedScripts";
  678. UnicodeString ScriptDescription;
  679. if (ScriptFormatCombo->ItemIndex == sfScriptFile)
  680. {
  681. WordWrap = false;
  682. FixedWidth = true;
  683. }
  684. else if (ScriptFormatCombo->ItemIndex == sfBatchFile)
  685. {
  686. WordWrap = false;
  687. FixedWidth = true;
  688. }
  689. else if (ScriptFormatCombo->ItemIndex == sfCommandLine)
  690. {
  691. WordWrap = true;
  692. FixedWidth = false;
  693. ScriptDescription = FMTLOAD(GENERATE_URL_COMMANDLINE_DESC, (FORMAT("\"%s\"", (Application->ExeName)))) + L"\n";
  694. }
  695. else if (ScriptFormatCombo->ItemIndex == sfPowerShell)
  696. {
  697. WordWrap = false;
  698. FixedWidth = true;
  699. }
  700. if (HostKeyUnknown)
  701. {
  702. ScriptDescription += LoadStr(GENERATE_URL_HOSTKEY_UNKNOWN) + L"\n";
  703. }
  704. Result = GenerateScript(ScriptDescription);
  705. ScriptDescriptionLabel->Caption = ScriptDescription;
  706. }
  707. else if (DebugAlwaysTrue(OptionsPageControl->ActivePage == AssemblySheet))
  708. {
  709. Counted = &FAssemblyCounted;
  710. CounterName = FTransfer ? L"GeneratedCodesTransfer" : L"GeneratedCodes";
  711. UnicodeString AssemblyDescription;
  712. if (HostKeyUnknown)
  713. {
  714. AssemblyDescription += LoadStr(GENERATE_URL_HOSTKEY_UNKNOWN) + L"\n";
  715. }
  716. Result = GenerateAssemblyCode(AssemblyDescription);
  717. AssemblyDescriptionLabel->Caption = AssemblyDescription;
  718. WordWrap = false;
  719. FixedWidth = true;
  720. }
  721. if (FixedWidth)
  722. {
  723. FResultMemoWithLinks->Font->Name = CustomWinConfiguration->DefaultFixedWidthFontName;
  724. }
  725. else
  726. {
  727. FResultMemoWithLinks->Font->Name = Font->Name;
  728. }
  729. if (!CounterName.IsEmpty() && !(*Counted))
  730. {
  731. (*Counted) = true;
  732. Configuration->Usage->Inc(CounterName);
  733. }
  734. Result =
  735. L"{\\rtf1\n"
  736. "{\\colortbl ;" +
  737. // The same RGB as on wiki
  738. RtfColorEntry(0x010101) + // near-black fake color to be used with no-style link to override the default blue underline
  739. RtfColorEntry(0x008000) + // code comment (green)
  740. RtfColorEntry(0x008080) + // class (teal)
  741. RtfColorEntry(0x800000) + // string (maroon)
  742. RtfColorEntry(0x0000FF) + // keyword (blue)
  743. RtfColorEntry(0x993333) + // command-line argument (reddish)
  744. RtfColorEntry(0x808080) + // script command (gray)
  745. L"}\n"
  746. "{\\fonttbl{\\f0\\fnil\\fcharset0 " + FResultMemoWithLinks->Font->Name + L";}}\n"
  747. "\\f0\\fs" + IntToStr(FResultMemoWithLinks->Font->Size * 2) + L" " +
  748. Result +
  749. "}";
  750. FResultMemoWithLinks->WordWrap = WordWrap;
  751. FResultMemoWithLinks->ScrollBars = WordWrap ? ssVertical : ssBoth;
  752. std::unique_ptr<TMemoryStream> Stream(new TMemoryStream());
  753. UTF8String ResultUtf = Result;
  754. Stream->Write(ResultUtf.c_str(), ResultUtf.Length());
  755. Stream->Position = 0;
  756. FResultMemoWithLinks->Perform(WM_VSCROLL, SB_TOP, 0);
  757. FResultMemoWithLinks->Lines->LoadFromStream(Stream.get(), TEncoding::UTF8);
  758. }
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TGenerateUrlDialog::Execute()
  762. {
  763. int Components = WinConfiguration->GenerateUrlComponents;
  764. if (Components < 0)
  765. {
  766. Components = UserNameCheck->Tag | RemoteDirectoryCheck->Tag;
  767. }
  768. TGenerateUrlCodeTarget Target = WinConfiguration->GenerateUrlCodeTarget;
  769. {
  770. TAutoFlag ChangingFlag(FChanging);
  771. if (IsFileUrl())
  772. {
  773. OptionsPageControl->ActivePage = UrlSheet;
  774. }
  775. else
  776. {
  777. switch (Target)
  778. {
  779. case guctUrl:
  780. OptionsPageControl->ActivePage = UrlSheet;
  781. break;
  782. case guctScript:
  783. OptionsPageControl->ActivePage = ScriptSheet;
  784. break;
  785. case guctAssembly:
  786. OptionsPageControl->ActivePage = AssemblySheet;
  787. break;
  788. default:
  789. DebugFail();
  790. }
  791. }
  792. for (int Index = 0; Index < UrlSheet->ControlCount; Index++)
  793. {
  794. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(UrlSheet->Controls[Index]);
  795. if (DebugAlwaysTrue((CheckBox != NULL) && (CheckBox->Tag != 0)))
  796. {
  797. CheckBox->Checked = FLAGSET(Components, CheckBox->Tag);
  798. }
  799. }
  800. ScriptFormatCombo->ItemIndex = WinConfiguration->GenerateUrlScriptFormat;
  801. AssemblyLanguageCombo->ItemIndex = WinConfiguration->GenerateUrlAssemblyLanguage;
  802. }
  803. UpdateControls();
  804. if (OptionsPageControl->ActivePage != UrlSheet)
  805. {
  806. ClientWidth = ScaleByTextHeightRunTime(this, 700);
  807. ClientHeight = ScaleByTextHeightRunTime(this, 600);
  808. }
  809. ShowModal();
  810. // Do not save the selection for files as the "URL" was selected implicitly
  811. if (!IsFileUrl())
  812. {
  813. if (OptionsPageControl->ActivePage == UrlSheet)
  814. {
  815. Target = guctUrl;
  816. }
  817. else if (OptionsPageControl->ActivePage == ScriptSheet)
  818. {
  819. Target = guctScript;
  820. }
  821. else if (OptionsPageControl->ActivePage == AssemblySheet)
  822. {
  823. Target = guctAssembly;
  824. }
  825. else
  826. {
  827. DebugFail();
  828. }
  829. WinConfiguration->GenerateUrlCodeTarget = Target;
  830. }
  831. if (Target == guctUrl)
  832. {
  833. Components = 0;
  834. for (int Index = 0; Index < UrlSheet->ControlCount; Index++)
  835. {
  836. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(UrlSheet->Controls[Index]);
  837. if (DebugAlwaysTrue((CheckBox != NULL) && (CheckBox->Tag != 0)) &&
  838. CheckBox->Checked)
  839. {
  840. Components |= CheckBox->Tag;
  841. }
  842. }
  843. WinConfiguration->GenerateUrlComponents = Components;
  844. }
  845. else if (Target == guctScript)
  846. {
  847. WinConfiguration->GenerateUrlScriptFormat = static_cast<TScriptFormat>(ScriptFormatCombo->ItemIndex);
  848. }
  849. else if (Target == guctAssembly)
  850. {
  851. WinConfiguration->GenerateUrlAssemblyLanguage = static_cast<TAssemblyLanguage>(AssemblyLanguageCombo->ItemIndex);
  852. }
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TGenerateUrlDialog::ControlChange(TObject * /*Sender*/)
  856. {
  857. UpdateControls();
  858. }
  859. //---------------------------------------------------------------------------
  860. void __fastcall TGenerateUrlDialog::ClipboardButtonClick(TObject * /*Sender*/)
  861. {
  862. TInstantOperationVisualizer Visualizer;
  863. // Cannot read the text from FResultMemoWithLinks->Lines as TRichEdit (as opposite to TMemo)
  864. // breaks wrapped lines
  865. UnicodeString Text = FResultMemoWithLinks->Text;
  866. UnicodeString EOL = sLineBreak;
  867. int P = Pos(EOL, Text);
  868. // Trim the EOL of the only string, what CopyToClipboard(FResultMemoWithLinks->Lines) would have done.
  869. // It probably never happens as rich edit does not return EOL on the last line.
  870. if (DebugAlwaysFalse(P == Text.Length() - EOL.Length() + 1))
  871. {
  872. Text.SetLength(Text.Length() - EOL.Length());
  873. }
  874. // Add trailing EOL, if there are multiple lines (see above)
  875. else if ((P > 0) && !EndsStr(EOL, Text))
  876. {
  877. Text += EOL;
  878. }
  879. Text = RtfRemoveHyperlinks(Text);
  880. CopyToClipboard(Text);
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TGenerateUrlDialog::HelpButtonClick(TObject * /*Sender*/)
  884. {
  885. FormHelp(this);
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall TGenerateUrlDialog::WMNCCreate(TWMNCCreate & Message)
  889. {
  890. // bypass TForm::WMNCCreate to prevent disabling "resize"
  891. // (which is done for bsDialog, see comments in CreateParams)
  892. DefaultHandler(&Message);
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall TGenerateUrlDialog::Dispatch(void * AMessage)
  896. {
  897. TMessage & Message = *reinterpret_cast<TMessage *>(AMessage);
  898. if (Message.Msg == WM_NCCREATE)
  899. {
  900. WMNCCreate(*reinterpret_cast<TWMNCCreate *>(AMessage));
  901. }
  902. else
  903. {
  904. TForm::Dispatch(AMessage);
  905. }
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TGenerateUrlDialog::CreateParams(TCreateParams & Params)
  909. {
  910. TForm::CreateParams(Params);
  911. // Allow resizing of the window, even if this is bsDialog.
  912. // This makes it more close to bsSizeable, but bsSizeable cannot for some
  913. // reason receive focus, if window is shown atop non-main window
  914. // (like editor)
  915. Params.Style = Params.Style | WS_THICKFRAME;
  916. }
  917. //---------------------------------------------------------------------------
  918. void __fastcall TGenerateUrlDialog::FormShow(TObject * /*Sender*/)
  919. {
  920. UpdateControls();
  921. }
  922. //---------------------------------------------------------------------------