GUITools.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Consts.hpp>
  6. #include <shlobj.h>
  7. #include <Common.h>
  8. #include "GUITools.h"
  9. #include "GUIConfiguration.h"
  10. #include <TextsWin.h>
  11. #include <TextsCore.h>
  12. #include <CoreMain.h>
  13. #include <SessionData.h>
  14. //---------------------------------------------------------------------------
  15. #pragma package(smart_init)
  16. //---------------------------------------------------------------------------
  17. bool __fastcall FindFile(AnsiString & Path)
  18. {
  19. bool Result = FileExists(Path);
  20. if (!Result)
  21. {
  22. int Len = GetEnvironmentVariable("PATH", NULL, 0);
  23. if (Len > 0)
  24. {
  25. AnsiString Paths;
  26. Paths.SetLength(Len - 1);
  27. GetEnvironmentVariable("PATH", Paths.c_str(), Len);
  28. AnsiString NewPath = FileSearch(ExtractFileName(Path), Paths);
  29. Result = !NewPath.IsEmpty();
  30. if (Result)
  31. {
  32. Path = NewPath;
  33. }
  34. }
  35. }
  36. return Result;
  37. }
  38. //---------------------------------------------------------------------------
  39. bool __fastcall FileExistsEx(AnsiString Path)
  40. {
  41. return FindFile(Path);
  42. }
  43. //---------------------------------------------------------------------------
  44. void __fastcall OpenSessionInPutty(const AnsiString PuttyPath,
  45. TSessionData * SessionData, const AnsiString Password)
  46. {
  47. AnsiString Program, Params, Dir;
  48. SplitCommand(PuttyPath, Program, Params, Dir);
  49. Program = ExpandEnvironmentVariables(Program);
  50. if (FindFile(Program))
  51. {
  52. AnsiString SessionName;
  53. TRegistryStorage * Storage = NULL;
  54. TSessionData * ExportData = NULL;
  55. TRegistryStorage * SourceStorage = NULL;
  56. try
  57. {
  58. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  59. Storage->AccessMode = smReadWrite;
  60. if (Storage->OpenRootKey(true))
  61. {
  62. if (Storage->KeyExists(SessionData->StorageKey))
  63. {
  64. SessionName = SessionData->SessionName;
  65. }
  66. else
  67. {
  68. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  69. if (SourceStorage->OpenSubKey(MungeStr(StoredSessions->DefaultSettings->Name), false) &&
  70. Storage->OpenSubKey(MungeStr(GUIConfiguration->PuttySession), true))
  71. {
  72. Storage->Copy(SourceStorage);
  73. Storage->CloseSubKey();
  74. }
  75. ExportData = new TSessionData("");
  76. ExportData->Assign(SessionData);
  77. ExportData->Modified = true;
  78. ExportData->Name = GUIConfiguration->PuttySession;
  79. ExportData->Password = "";
  80. ExportData->Save(Storage, true);
  81. SessionName = GUIConfiguration->PuttySession;
  82. }
  83. }
  84. }
  85. __finally
  86. {
  87. delete Storage;
  88. delete ExportData;
  89. delete SourceStorage;
  90. }
  91. if (!Params.IsEmpty())
  92. {
  93. Params += " ";
  94. }
  95. if (!Password.IsEmpty())
  96. {
  97. Params += FORMAT("-pw \"%s\" ", (Password));
  98. }
  99. Params += FORMAT("-load \"%s\"", (SessionName));
  100. if (!ExecuteShell(Program, Params))
  101. {
  102. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  103. }
  104. }
  105. else
  106. {
  107. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  108. }
  109. }
  110. //---------------------------------------------------------------------------
  111. bool __fastcall ExecuteShell(const AnsiString Path, const AnsiString Params)
  112. {
  113. return ((int)ShellExecute(NULL, "open", (char*)Path.data(),
  114. (char*)Params.data(), NULL, SW_SHOWNORMAL) > 32);
  115. }
  116. //---------------------------------------------------------------------------
  117. bool __fastcall ExecuteShell(const AnsiString Path, const AnsiString Params,
  118. HANDLE & Handle)
  119. {
  120. bool Result;
  121. TShellExecuteInfo ExecuteInfo;
  122. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  123. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  124. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  125. ExecuteInfo.hwnd = Application->Handle;
  126. ExecuteInfo.lpFile = (char*)Path.data();
  127. ExecuteInfo.lpParameters = (char*)Params.data();
  128. ExecuteInfo.nShow = SW_SHOW;
  129. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  130. if (Result)
  131. {
  132. Handle = ExecuteInfo.hProcess;
  133. }
  134. return Result;
  135. }
  136. //---------------------------------------------------------------------------
  137. bool __fastcall ExecuteShellAndWait(HWND Handle, const AnsiString Path,
  138. const AnsiString Params, TProcessMessagesEvent ProcessMessages)
  139. {
  140. bool Result;
  141. TShellExecuteInfo ExecuteInfo;
  142. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  143. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  144. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  145. ExecuteInfo.hwnd = Handle;
  146. ExecuteInfo.lpFile = (char*)Path.data();
  147. ExecuteInfo.lpParameters = (char*)Params.data();
  148. ExecuteInfo.nShow = SW_SHOW;
  149. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  150. if (Result)
  151. {
  152. if (ProcessMessages != NULL)
  153. {
  154. unsigned long WaitResult;
  155. do
  156. {
  157. WaitResult = WaitForSingleObject(ExecuteInfo.hProcess, 200);
  158. if (WaitResult == WAIT_FAILED)
  159. {
  160. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  161. }
  162. ProcessMessages();
  163. }
  164. while (WaitResult == WAIT_TIMEOUT);
  165. }
  166. else
  167. {
  168. WaitForSingleObject(ExecuteInfo.hProcess, INFINITE);
  169. }
  170. }
  171. return Result;
  172. }
  173. //---------------------------------------------------------------------------
  174. bool __fastcall ExecuteShellAndWait(HWND Handle, const AnsiString Command,
  175. TProcessMessagesEvent ProcessMessages)
  176. {
  177. AnsiString Program, Params, Dir;
  178. SplitCommand(Command, Program, Params, Dir);
  179. return ExecuteShellAndWait(Handle, Program, Params, ProcessMessages);
  180. }
  181. //---------------------------------------------------------------------------
  182. bool __fastcall SpecialFolderLocation(int PathID, AnsiString & Path)
  183. {
  184. LPITEMIDLIST Pidl;
  185. char Buf[256];
  186. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  187. SHGetPathFromIDList(Pidl, Buf))
  188. {
  189. Path = AnsiString(Buf);
  190. return true;
  191. }
  192. return false;
  193. }
  194. //---------------------------------------------------------------------------
  195. AnsiString __fastcall ItemsFormatString(const AnsiString SingleItemFormat,
  196. const AnsiString MultiItemsFormat, int Count, const AnsiString FirstItem)
  197. {
  198. AnsiString Result;
  199. if (Count == 1)
  200. {
  201. Result = FORMAT(SingleItemFormat, (FirstItem));
  202. }
  203. else
  204. {
  205. Result = FORMAT(MultiItemsFormat, (Count));
  206. }
  207. return Result;
  208. }
  209. //---------------------------------------------------------------------------
  210. AnsiString __fastcall ItemsFormatString(const AnsiString SingleItemFormat,
  211. const AnsiString MultiItemsFormat, TStrings * Items)
  212. {
  213. return ItemsFormatString(SingleItemFormat, MultiItemsFormat,
  214. Items->Count, (Items->Count > 0 ? Items->Strings[0] : AnsiString()));
  215. }
  216. //---------------------------------------------------------------------------
  217. AnsiString __fastcall FileNameFormatString(const AnsiString SingleFileFormat,
  218. const AnsiString MultiFilesFormat, TStrings * Files, bool Remote)
  219. {
  220. assert(Files != NULL);
  221. AnsiString Item;
  222. if (Files->Count > 0)
  223. {
  224. Item = Remote ? UnixExtractFileName(Files->Strings[0]) :
  225. ExtractFileName(Files->Strings[0]);
  226. }
  227. return ItemsFormatString(SingleFileFormat, MultiFilesFormat,
  228. Files->Count, Item);
  229. }
  230. //---------------------------------------------------------------------
  231. AnsiString __fastcall FormatBytes(__int64 Bytes, bool UseOrders)
  232. {
  233. AnsiString Result;
  234. if (!UseOrders || (Bytes < __int64(100*1024)))
  235. {
  236. Result = FormatFloat("#,##0 \"B\"", Bytes);
  237. }
  238. else if (Bytes < __int64(100*1024*1024))
  239. {
  240. Result = FormatFloat("#,##0 \"KB\"", Bytes / 1024);
  241. }
  242. else
  243. {
  244. Result = FormatFloat("#,##0 \"MB\"", Bytes / (1024*1024));
  245. }
  246. return Result;
  247. }
  248. //---------------------------------------------------------------------------
  249. void __fastcall CopyToClipboard(AnsiString Text)
  250. {
  251. HANDLE Data;
  252. void * DataPtr;
  253. if (OpenClipboard(0))
  254. {
  255. try
  256. {
  257. Data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Text.Length() + 1);
  258. try
  259. {
  260. DataPtr = GlobalLock(Data);
  261. try
  262. {
  263. memcpy(DataPtr, Text.c_str(), Text.Length() + 1);
  264. EmptyClipboard();
  265. SetClipboardData(CF_TEXT, Data);
  266. }
  267. __finally
  268. {
  269. GlobalUnlock(Data);
  270. }
  271. }
  272. catch(...)
  273. {
  274. GlobalFree(Data);
  275. throw;
  276. }
  277. }
  278. __finally
  279. {
  280. CloseClipboard();
  281. }
  282. }
  283. else
  284. {
  285. throw Exception(Consts_SCannotOpenClipboard);
  286. }
  287. }
  288. //---------------------------------------------------------------------------
  289. void __fastcall CopyToClipboard(TStrings * Strings)
  290. {
  291. if (Strings->Count > 0)
  292. {
  293. if (Strings->Count == 1)
  294. {
  295. CopyToClipboard(Strings->Strings[0]);
  296. }
  297. else
  298. {
  299. CopyToClipboard(Strings->Text);
  300. }
  301. }
  302. }
  303. //---------------------------------------------------------------------------
  304. AnsiString __fastcall UniqTempDir(const AnsiString BaseDir, const AnsiString Identity,
  305. bool Mask)
  306. {
  307. AnsiString TempDir;
  308. do
  309. {
  310. TempDir = BaseDir.IsEmpty() ? SystemTemporaryDirectory() : BaseDir;
  311. TempDir = IncludeTrailingBackslash(TempDir) + Identity;
  312. if (Mask)
  313. {
  314. TempDir += "?????";
  315. }
  316. else
  317. {
  318. TempDir += IncludeTrailingBackslash(FormatDateTime("nnzzz", Now()));
  319. };
  320. }
  321. while (!Mask && DirectoryExists(TempDir));
  322. return TempDir;
  323. }
  324. //---------------------------------------------------------------------------
  325. bool __fastcall DeleteDirectory(const AnsiString DirName)
  326. {
  327. TSearchRec sr;
  328. bool retval = true;
  329. if (FindFirst(DirName + "\\*", faAnyFile, sr) == 0) // VCL Function
  330. {
  331. if (FLAGSET(sr.Attr, faDirectory))
  332. {
  333. if (sr.Name != "." && sr.Name != "..")
  334. retval = DeleteDirectory(DirName + "\\" + sr.Name);
  335. }
  336. else
  337. {
  338. retval = DeleteFile(DirName + "\\" + sr.Name);
  339. }
  340. if (retval)
  341. {
  342. while (FindNext(sr) == 0)
  343. { // VCL Function
  344. if (FLAGSET(sr.Attr, faDirectory))
  345. {
  346. if (sr.Name != "." && sr.Name != "..")
  347. retval = DeleteDirectory(DirName + "\\" + sr.Name);
  348. }
  349. else
  350. {
  351. retval = DeleteFile(DirName + "\\" + sr.Name);
  352. }
  353. if (!retval) break;
  354. }
  355. }
  356. }
  357. FindClose(sr);
  358. if (retval) retval = RemoveDir(DirName); // VCL function
  359. return retval;
  360. }
  361. //---------------------------------------------------------------------------
  362. AnsiString __fastcall TranslateExceptionMessage(const Exception * E)
  363. {
  364. if (dynamic_cast<const EAccessViolation*>(E) != NULL)
  365. {
  366. return LoadStr(ACCESS_VIOLATION_ERROR);
  367. }
  368. else
  369. {
  370. return E->Message;
  371. }
  372. }
  373. //---------------------------------------------------------------------------
  374. AnsiString __fastcall FormatDateTimeSpan(const AnsiString TimeFormat, TDateTime DateTime)
  375. {
  376. AnsiString Result;
  377. if (int(DateTime) > 0)
  378. {
  379. Result = IntToStr(int(DateTime)) + ", ";
  380. }
  381. // days are decremented, because when there is to many of them,
  382. // "integer overflow" error occures
  383. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  384. return Result;
  385. }
  386. //---------------------------------------------------------------------------
  387. TLocalCustomCommand::TLocalCustomCommand()
  388. {
  389. }
  390. //---------------------------------------------------------------------------
  391. TLocalCustomCommand::TLocalCustomCommand(const AnsiString & FileName,
  392. const AnsiString & LocalFileName, const AnsiString & FileList) :
  393. TFileCustomCommand(FileName, FileList)
  394. {
  395. FLocalFileName = LocalFileName;
  396. }
  397. //---------------------------------------------------------------------------
  398. int __fastcall TLocalCustomCommand::PatternLen(int Index, char PatternCmd)
  399. {
  400. int Len;
  401. if (PatternCmd == '^')
  402. {
  403. Len = 3;
  404. }
  405. else
  406. {
  407. Len = TFileCustomCommand::PatternLen(Index, PatternCmd);
  408. }
  409. return Len;
  410. }
  411. //---------------------------------------------------------------------------
  412. bool __fastcall TLocalCustomCommand::PatternReplacement(int Index,
  413. const AnsiString & Pattern, AnsiString & Replacement, bool & Delimit)
  414. {
  415. bool Result;
  416. if (Pattern == "!^!")
  417. {
  418. Replacement = FLocalFileName;
  419. Result = true;
  420. }
  421. else
  422. {
  423. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  424. }
  425. return Result;
  426. }
  427. //---------------------------------------------------------------------------
  428. void __fastcall TLocalCustomCommand::DelimitReplacement(
  429. AnsiString & /*Replacement*/, char /*Quote*/)
  430. {
  431. // never delimit local commands
  432. }
  433. //---------------------------------------------------------------------------
  434. bool __fastcall TLocalCustomCommand::HasLocalFileName(const AnsiString & Command)
  435. {
  436. return FindPattern(Command, '^');
  437. }
  438. //---------------------------------------------------------------------------
  439. bool __fastcall TLocalCustomCommand::IsFileCommand(const AnsiString & Command)
  440. {
  441. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  442. }