Tools.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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 <stdio.h>
  8. #include <Common.h>
  9. #include <TextsWin.h>
  10. #include "GUITools.h"
  11. #include "VCLCommon.h"
  12. #include "Tools.h"
  13. //---------------------------------------------------------------------------
  14. #pragma package(smart_init)
  15. //---------------------------------------------------------------------------
  16. TFontStyles __fastcall IntToFontStyles(int value)
  17. {
  18. TFontStyles Result;
  19. for (int i = fsBold; i <= fsStrikeOut; i++)
  20. {
  21. if (value & 1)
  22. {
  23. Result << (TFontStyle)i;
  24. }
  25. value >>= 1;
  26. }
  27. return Result;
  28. }
  29. //---------------------------------------------------------------------------
  30. int __fastcall FontStylesToInt(const TFontStyles value)
  31. {
  32. int Result = 0;
  33. for (int i = fsStrikeOut; i >= fsBold; i--)
  34. {
  35. Result <<= 1;
  36. if (value.Contains((TFontStyle)i))
  37. {
  38. Result |= 1;
  39. }
  40. }
  41. return Result;
  42. }
  43. //---------------------------------------------------------------------------
  44. void __fastcall CenterFormOn(TForm * Form, TControl * CenterOn)
  45. {
  46. TPoint ScreenPoint = CenterOn->ClientToScreen(TPoint(0, 0));
  47. Form->Left = ScreenPoint.x + (CenterOn->Width / 2) - (Form->Width / 2);
  48. Form->Top = ScreenPoint.y + (CenterOn->Height / 2) - (Form->Height / 2);
  49. }
  50. //---------------------------------------------------------------------------
  51. AnsiString __fastcall GetListViewStr(TListView * ListView)
  52. {
  53. AnsiString Result;
  54. for (int Index = 0; Index < ListView->Columns->Count; Index++)
  55. {
  56. if (!Result.IsEmpty())
  57. {
  58. Result += ",";
  59. }
  60. Result += IntToStr(ListView->Column[Index]->Width);
  61. }
  62. return Result;
  63. }
  64. //---------------------------------------------------------------------------
  65. void __fastcall LoadListViewStr(TListView * ListView, AnsiString LayoutStr)
  66. {
  67. int Index = 0;
  68. while (!LayoutStr.IsEmpty() && (Index < ListView->Columns->Count))
  69. {
  70. ListView->Column[Index]->Width = StrToIntDef(
  71. CutToChar(LayoutStr, ',', true), ListView->Column[Index]->Width);
  72. Index++;
  73. }
  74. }
  75. //---------------------------------------------------------------------------
  76. void __fastcall RestoreForm(AnsiString Data, TForm * Form)
  77. {
  78. assert(Form);
  79. if (!Data.IsEmpty())
  80. {
  81. TMonitor * Monitor = FormMonitor(Form);
  82. TRect Bounds = Form->BoundsRect;
  83. int Left = StrToIntDef(::CutToChar(Data, ';', true), Bounds.Left);
  84. int Top = StrToIntDef(::CutToChar(Data, ';', true), Bounds.Top);
  85. bool DefaultPos = (Left == -1) && (Top == -1);
  86. if (!DefaultPos)
  87. {
  88. Bounds.Left = Left;
  89. Bounds.Top = Top;
  90. }
  91. else
  92. {
  93. Bounds.Left = 0;
  94. Bounds.Top = 0;
  95. }
  96. Bounds.Right = StrToIntDef(::CutToChar(Data, ';', true), Bounds.Right);
  97. Bounds.Bottom = StrToIntDef(::CutToChar(Data, ';', true), Bounds.Bottom);
  98. TWindowState State = (TWindowState)StrToIntDef(::CutToChar(Data, ';', true), (int)wsNormal);
  99. Form->WindowState = State;
  100. if (State == wsNormal)
  101. {
  102. // move to the target monitor
  103. OffsetRect(Bounds, Monitor->Left, Monitor->Top);
  104. // reduce window size to that of monitor size
  105. // (this does not cut window into monitor!)
  106. if (Bounds.Width() > Monitor->WorkareaRect.Width())
  107. {
  108. Bounds.Right -= (Bounds.Width() - Monitor->WorkareaRect.Width());
  109. }
  110. if (Bounds.Height() > Monitor->WorkareaRect.Height())
  111. {
  112. Bounds.Bottom -= (Bounds.Height() - Monitor->WorkareaRect.Height());
  113. }
  114. if (DefaultPos ||
  115. ((Bounds.Left < Monitor->Left) ||
  116. (Bounds.Left > Monitor->Left + Monitor->WorkareaRect.Width() - 20) ||
  117. (Bounds.Top < Monitor->Top) ||
  118. (Bounds.Top > Monitor->Top + Monitor->WorkareaRect.Height() - 20)))
  119. {
  120. if (Monitor->Primary)
  121. {
  122. if ((Application->MainForm == NULL) || (Application->MainForm == Form))
  123. {
  124. Form->Position = poDefaultPosOnly;
  125. }
  126. else
  127. {
  128. Form->Position = poMainFormCenter;
  129. }
  130. Form->Width = Bounds.Width();
  131. Form->Height = Bounds.Height();
  132. }
  133. else
  134. {
  135. // when positioning on non-primary monitor, we need
  136. // to handle that ourselves, so place window to center
  137. Form->SetBounds(Monitor->Left + ((Monitor->Width - Bounds.Width()) / 2),
  138. Monitor->Top + ((Monitor->Height - Bounds.Height()) / 2),
  139. Bounds.Width(), Bounds.Height());
  140. Form->Position = poDesigned;
  141. }
  142. }
  143. else
  144. {
  145. Form->Position = poDesigned;
  146. Form->BoundsRect = Bounds;
  147. }
  148. }
  149. else if (State == wsMaximized)
  150. {
  151. Form->Position = poDesigned;
  152. Bounds = Form->BoundsRect;
  153. OffsetRect(Bounds, Monitor->Left, Monitor->Top);
  154. Form->BoundsRect = Bounds;
  155. }
  156. }
  157. else if (Form->Position == poDesigned)
  158. {
  159. Form->Position = poDefaultPosOnly;
  160. }
  161. }
  162. //---------------------------------------------------------------------------
  163. AnsiString __fastcall StoreForm(TCustomForm * Form)
  164. {
  165. assert(Form);
  166. TRect Bounds = Form->BoundsRect;
  167. OffsetRect(Bounds, -Form->Monitor->Left, -Form->Monitor->Top);
  168. return FORMAT("%d;%d;%d;%d;%d", ((int)Bounds.Left, (int)Bounds.Top,
  169. (int)Bounds.Right, (int)Bounds.Bottom,
  170. // we do not want WinSCP to start minimized next time (we cannot handle that anyway).
  171. // note that WindowState is wsNormal when window in minimized for some reason.
  172. // actually it is wsMinimized only when minimized by MSVDM
  173. (int)(Form->WindowState == wsMinimized ? wsNormal : Form->WindowState)));
  174. }
  175. //---------------------------------------------------------------------------
  176. bool __fastcall ExecuteShellAndWait(const AnsiString Path, const AnsiString Params)
  177. {
  178. return ExecuteShellAndWait(Application->Handle, Path, Params,
  179. &Application->ProcessMessages);
  180. }
  181. //---------------------------------------------------------------------------
  182. bool __fastcall ExecuteShellAndWait(const AnsiString Command)
  183. {
  184. return ExecuteShellAndWait(Application->Handle, Command,
  185. &Application->ProcessMessages);
  186. }
  187. //---------------------------------------------------------------------------
  188. void __fastcall CreateDesktopShortCut(const AnsiString &Name,
  189. const AnsiString &File, const AnsiString & Params, const AnsiString & Description,
  190. int SpecialFolder)
  191. {
  192. IShellLink* pLink;
  193. IPersistFile* pPersistFile;
  194. LPMALLOC ShellMalloc;
  195. LPITEMIDLIST DesktopPidl;
  196. char DesktopDir[MAX_PATH];
  197. if (SpecialFolder < 0)
  198. {
  199. SpecialFolder = CSIDL_DESKTOPDIRECTORY;
  200. }
  201. try
  202. {
  203. if (FAILED(SHGetMalloc(&ShellMalloc))) throw Exception("");
  204. if (FAILED(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl)))
  205. {
  206. throw Exception("");
  207. }
  208. if (!SHGetPathFromIDList(DesktopPidl, DesktopDir))
  209. {
  210. ShellMalloc->Free(DesktopPidl);
  211. ShellMalloc->Release();
  212. throw Exception("");
  213. }
  214. ShellMalloc->Free(DesktopPidl);
  215. ShellMalloc->Release();
  216. if (SUCCEEDED(CoInitialize(NULL)))
  217. {
  218. if(SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
  219. IID_IShellLink, (void **) &pLink)))
  220. {
  221. try
  222. {
  223. pLink->SetPath(File.c_str());
  224. pLink->SetDescription(Description.c_str());
  225. pLink->SetArguments(Params.c_str());
  226. pLink->SetShowCmd(SW_SHOW);
  227. if (SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
  228. {
  229. try
  230. {
  231. WideString strShortCutLocation(DesktopDir);
  232. // Name can contain even path (e.g. to create quick launch icon)
  233. strShortCutLocation += AnsiString("\\") + Name + ".lnk";
  234. if (!SUCCEEDED(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE)))
  235. {
  236. throw Exception("");
  237. }
  238. }
  239. __finally
  240. {
  241. pPersistFile->Release();
  242. }
  243. }
  244. }
  245. __finally
  246. {
  247. pLink->Release();
  248. }
  249. }
  250. CoUninitialize();
  251. }
  252. }
  253. catch(...)
  254. {
  255. throw Exception(CREATE_SHORTCUT_ERROR);
  256. }
  257. }
  258. //---------------------------------------------------------------------------
  259. void __fastcall ValidateMaskEdit(TComboBox * Edit)
  260. {
  261. assert(Edit != NULL);
  262. TFileMasks Masks = Edit->Text;
  263. int Start, Length;
  264. if (!Masks.IsValid(Start, Length))
  265. {
  266. SimpleErrorDialog(FMTLOAD(MASK_ERROR, (Masks.Masks.SubString(Start + 1, Length))));
  267. Edit->SetFocus();
  268. Edit->SelStart = Start;
  269. Edit->SelLength = Length;
  270. Abort();
  271. }
  272. }
  273. //---------------------------------------------------------------------------
  274. void __fastcall ValidateMaskEdit(TEdit * Edit)
  275. {
  276. assert(Edit != NULL);
  277. TFileMasks Masks = Edit->Text;
  278. int Start, Length;
  279. if (!Masks.IsValid(Start, Length))
  280. {
  281. SimpleErrorDialog(FMTLOAD(MASK_ERROR, (Masks.Masks.SubString(Start + 1, Length))));
  282. Edit->SetFocus();
  283. Edit->SelStart = Start;
  284. Edit->SelLength = Length;
  285. Abort();
  286. }
  287. }
  288. //---------------------------------------------------------------------------
  289. void __fastcall ExitActiveControl(TForm * Form)
  290. {
  291. if (Form->ActiveControl != NULL)
  292. {
  293. TNotifyEvent OnExit = ((TEdit*)Form->ActiveControl)->OnExit;
  294. if (OnExit != NULL)
  295. {
  296. OnExit(Form->ActiveControl);
  297. }
  298. }
  299. }
  300. //---------------------------------------------------------------------------
  301. void __fastcall OpenBrowser(AnsiString URL)
  302. {
  303. ShellExecute(Application->Handle, "open", URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
  304. }
  305. //---------------------------------------------------------------------------
  306. bool __fastcall IsFormatInClipboard(unsigned int Format)
  307. {
  308. bool Result = OpenClipboard(0);
  309. if (Result)
  310. {
  311. Result = IsClipboardFormatAvailable(Format);
  312. CloseClipboard();
  313. }
  314. return Result;
  315. }
  316. //---------------------------------------------------------------------------
  317. HANDLE __fastcall OpenTextFromClipboard(const char *& Text)
  318. {
  319. HANDLE Result = NULL;
  320. if (OpenClipboard(0))
  321. {
  322. Result = GetClipboardData(CF_TEXT);
  323. if (Result != NULL)
  324. {
  325. Text = static_cast<const char*>(GlobalLock(Result));
  326. }
  327. else
  328. {
  329. CloseClipboard();
  330. }
  331. }
  332. return Result;
  333. }
  334. //---------------------------------------------------------------------------
  335. void __fastcall CloseTextFromClipboard(HANDLE Handle)
  336. {
  337. if (Handle != NULL)
  338. {
  339. GlobalUnlock(Handle);
  340. }
  341. CloseClipboard();
  342. }
  343. //---------------------------------------------------------------------------
  344. bool __fastcall TextFromClipboard(AnsiString & Text)
  345. {
  346. const char * AText = NULL;
  347. HANDLE Handle = OpenTextFromClipboard(AText);
  348. bool Result = (Handle != NULL);
  349. if (Result)
  350. {
  351. Text = AText;
  352. CloseTextFromClipboard(Handle);
  353. }
  354. return Result;
  355. }
  356. //---------------------------------------------------------------------------
  357. static bool __fastcall GetResource(
  358. const AnsiString ResName, void *& Content, unsigned long & Size)
  359. {
  360. HRSRC Resource = FindResourceEx(HInstance, RT_RCDATA, ResName.c_str(),
  361. MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
  362. bool Result = (Resource != NULL);
  363. if (Result)
  364. {
  365. Size = SizeofResource(HInstance, Resource);
  366. if (!Size)
  367. {
  368. throw Exception(FORMAT("Cannot get size of resource %s", (ResName)));
  369. }
  370. Content = LoadResource(HInstance, Resource);
  371. if (!Content)
  372. {
  373. throw Exception(FORMAT("Cannot read resource %s", (ResName)));
  374. }
  375. Content = LockResource(Content);
  376. if (!Content)
  377. {
  378. throw Exception(FORMAT("Cannot lock resource %s", (ResName)));
  379. }
  380. }
  381. return Result;
  382. }
  383. //---------------------------------------------------------------------------
  384. bool __fastcall DumpResourceToFile(const AnsiString ResName,
  385. const AnsiString FileName)
  386. {
  387. void * Content;
  388. unsigned long Size;
  389. bool Result = GetResource(ResName, Content, Size);
  390. if (Result)
  391. {
  392. FILE * f = fopen(FileName.c_str(), "wb");
  393. if (!f)
  394. {
  395. throw Exception(FORMAT("Cannot create file %s", (FileName)));
  396. }
  397. if (fwrite(Content, 1, Size, f) != Size)
  398. {
  399. throw Exception(FORMAT("Cannot write to file %s", (FileName)));
  400. }
  401. fclose(f);
  402. }
  403. return Result;
  404. }
  405. //---------------------------------------------------------------------------
  406. AnsiString __fastcall ReadResource(const AnsiString ResName)
  407. {
  408. void * Content;
  409. unsigned long Size;
  410. AnsiString Result;
  411. if (GetResource(ResName, Content, Size))
  412. {
  413. Result = AnsiString(static_cast<char*>(Content), Size);
  414. }
  415. return Result;
  416. }
  417. //---------------------------------------------------------------------------
  418. template <class T>
  419. class TChildCommonDialog : public T
  420. {
  421. public:
  422. __fastcall TChildCommonDialog(TComponent * AOwner) :
  423. T(AOwner)
  424. {
  425. }
  426. protected:
  427. // all common-dialog structures we use (save, open, font) start like this:
  428. typedef struct
  429. {
  430. DWORD lStructSize;
  431. HWND hwndOwner;
  432. } COMMONDLG;
  433. virtual BOOL __fastcall TaskModalDialog(void * DialogFunc, void * DialogData)
  434. {
  435. COMMONDLG * CommonDlg = static_cast<COMMONDLG *>(DialogData);
  436. HWND Parent = GetCorrectFormParent();
  437. if (Parent != NULL)
  438. {
  439. CommonDlg->hwndOwner = Parent;
  440. }
  441. return T::TaskModalDialog(DialogFunc, DialogData);
  442. }
  443. };
  444. //---------------------------------------------------------------------------
  445. // without this intermediate class, failure occurs during construction in release version
  446. #define CHILDCOMMONDIALOG(DIALOG) \
  447. class TChild ## DIALOG ## Dialog : public TChildCommonDialog<T ## DIALOG ## Dialog> \
  448. { \
  449. public: \
  450. __fastcall TChild ## DIALOG ## Dialog(TComponent * AOwner) : \
  451. TChildCommonDialog<T ## DIALOG ## Dialog>(AOwner) \
  452. { \
  453. } \
  454. }
  455. //---------------------------------------------------------------------------
  456. CHILDCOMMONDIALOG(Open);
  457. CHILDCOMMONDIALOG(Save);
  458. CHILDCOMMONDIALOG(Font);
  459. //---------------------------------------------------------------------------
  460. TOpenDialog * __fastcall CreateOpenDialog(TComponent * AOwner)
  461. {
  462. return new TChildOpenDialog(AOwner);
  463. }
  464. //---------------------------------------------------------------------------
  465. template <class T>
  466. void __fastcall BrowseForExecutableT(T * Control, AnsiString Title,
  467. AnsiString Filter, bool FileNameCommand, bool Escape)
  468. {
  469. AnsiString Executable, Program, Params, Dir;
  470. Executable = Control->Text;
  471. if (FileNameCommand)
  472. {
  473. ReformatFileNameCommand(Executable);
  474. }
  475. SplitCommand(Executable, Program, Params, Dir);
  476. TOpenDialog * FileDialog = CreateOpenDialog(Application);
  477. try
  478. {
  479. if (Escape)
  480. {
  481. Program = StringReplace(Program, "\\\\", "\\", TReplaceFlags() << rfReplaceAll);
  482. }
  483. AnsiString ExpandedProgram = ExpandEnvironmentVariables(Program);
  484. FileDialog->FileName = ExpandedProgram;
  485. FileDialog->Filter = Filter;
  486. FileDialog->Title = Title;
  487. if (FileDialog->Execute())
  488. {
  489. TNotifyEvent PrevOnChange = Control->OnChange;
  490. Control->OnChange = NULL;
  491. try
  492. {
  493. // preserve unexpanded file, if the destination has not changed actually
  494. if (!CompareFileName(ExpandedProgram, FileDialog->FileName))
  495. {
  496. Program = FileDialog->FileName;
  497. if (Escape)
  498. {
  499. Program = StringReplace(Program, "\\", "\\\\", TReplaceFlags() << rfReplaceAll);
  500. }
  501. }
  502. Control->Text = FormatCommand(Program, Params);
  503. }
  504. __finally
  505. {
  506. Control->OnChange = PrevOnChange;
  507. }
  508. if (Control->OnExit != NULL)
  509. {
  510. Control->OnExit(Control);
  511. }
  512. }
  513. }
  514. __finally
  515. {
  516. delete FileDialog;
  517. }
  518. }
  519. //---------------------------------------------------------------------------
  520. void __fastcall BrowseForExecutable(TEdit * Control, AnsiString Title,
  521. AnsiString Filter, bool FileNameCommand, bool Escape)
  522. {
  523. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  524. }
  525. //---------------------------------------------------------------------------
  526. void __fastcall BrowseForExecutable(TComboBox * Control, AnsiString Title,
  527. AnsiString Filter, bool FileNameCommand, bool Escape)
  528. {
  529. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  530. }
  531. //---------------------------------------------------------------------------
  532. bool __fastcall FontDialog(TFont * Font)
  533. {
  534. bool Result;
  535. TFontDialog * Dialog = new TChildFontDialog(Application);
  536. try
  537. {
  538. Dialog->Device = fdScreen;
  539. Dialog->Options = TFontDialogOptions() << fdForceFontExist;
  540. Dialog->Font = Font;
  541. Result = Dialog->Execute();
  542. if (Result)
  543. {
  544. Font->Assign(Dialog->Font);
  545. }
  546. }
  547. __finally
  548. {
  549. delete Dialog;
  550. }
  551. return Result;
  552. }
  553. //---------------------------------------------------------------------------
  554. bool __fastcall SaveDialog(AnsiString Title, AnsiString Filter,
  555. AnsiString DefaultExt, AnsiString & FileName)
  556. {
  557. bool Result;
  558. TSaveDialog * Dialog = new TChildSaveDialog(Application);
  559. try
  560. {
  561. Dialog->Title = Title;
  562. Dialog->Filter = Filter;
  563. Dialog->DefaultExt = DefaultExt;
  564. Dialog->FileName = FileName;
  565. Dialog->Options = Dialog->Options << ofOverwritePrompt << ofPathMustExist <<
  566. ofNoReadOnlyReturn;
  567. Result = Dialog->Execute();
  568. if (Result)
  569. {
  570. FileName = Dialog->FileName;
  571. }
  572. }
  573. __finally
  574. {
  575. delete Dialog;
  576. }
  577. return Result;
  578. }
  579. //---------------------------------------------------------------------------
  580. void __fastcall CopyToClipboard(AnsiString Text)
  581. {
  582. HANDLE Data;
  583. void * DataPtr;
  584. if (OpenClipboard(0))
  585. {
  586. try
  587. {
  588. Data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Text.Length() + 1);
  589. try
  590. {
  591. DataPtr = GlobalLock(Data);
  592. try
  593. {
  594. memcpy(DataPtr, Text.c_str(), Text.Length() + 1);
  595. EmptyClipboard();
  596. SetClipboardData(CF_TEXT, Data);
  597. }
  598. __finally
  599. {
  600. GlobalUnlock(Data);
  601. }
  602. }
  603. catch(...)
  604. {
  605. GlobalFree(Data);
  606. throw;
  607. }
  608. }
  609. __finally
  610. {
  611. CloseClipboard();
  612. }
  613. }
  614. else
  615. {
  616. throw Exception(Consts_SCannotOpenClipboard);
  617. }
  618. }
  619. //---------------------------------------------------------------------------
  620. void __fastcall CopyToClipboard(TStrings * Strings)
  621. {
  622. if (Strings->Count > 0)
  623. {
  624. if (Strings->Count == 1)
  625. {
  626. CopyToClipboard(Strings->Strings[0]);
  627. }
  628. else
  629. {
  630. CopyToClipboard(Strings->Text);
  631. }
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. bool __fastcall IsWin64()
  636. {
  637. static int Result = -1;
  638. if (Result < 0)
  639. {
  640. typedef BOOL WINAPI (*IsWow64ProcessType)(HANDLE Process, PBOOL Wow64Process);
  641. Result = 0;
  642. HMODULE Kernel = GetModuleHandle(kernel32);
  643. if (Kernel != NULL)
  644. {
  645. IsWow64ProcessType IsWow64Process =
  646. (IsWow64ProcessType)GetProcAddress(Kernel, "IsWow64Process");
  647. if (IsWow64Process != NULL)
  648. {
  649. BOOL Wow64Process = FALSE;
  650. if (IsWow64Process(GetCurrentProcess(), &Wow64Process))
  651. {
  652. if (Wow64Process)
  653. {
  654. Result = 1;
  655. }
  656. }
  657. }
  658. }
  659. }
  660. return (Result > 0);
  661. }
  662. //---------------------------------------------------------------------------
  663. // Code from http://gentoo.osuosl.org/distfiles/cl331.zip/io/
  664. // The autoproxy functions were only documented in WinHTTP 5.1, so we have to
  665. // provide the necessary defines and structures ourselves
  666. #ifndef WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
  667. #define HINTERNET HANDLE
  668. typedef struct
  669. {
  670. WORD dwAccessType;
  671. LPWSTR lpszProxy;
  672. LPWSTR lpszProxyBypass;
  673. } WINHTTP_PROXY_INFO;
  674. typedef struct {
  675. BOOL fAutoDetect;
  676. LPWSTR lpszAutoConfigUrl;
  677. LPWSTR lpszProxy;
  678. LPWSTR lpszProxyBypass;
  679. } WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
  680. #endif /* WinHTTP 5.1 defines and structures */
  681. typedef BOOL (*WINHTTPGETDEFAULTPROXYCONFIGURATION)(WINHTTP_PROXY_INFO * pProxyInfo);
  682. typedef BOOL (*WINHTTPGETIEPROXYCONFIGFORCURRENTUSER)(
  683. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG * pProxyConfig);
  684. //---------------------------------------------------------------------------
  685. bool __fastcall AutodetectProxyUrl(AnsiString & Proxy)
  686. {
  687. static HMODULE WinHTTP = NULL;
  688. static WINHTTPGETDEFAULTPROXYCONFIGURATION WinHttpGetDefaultProxyConfiguration = NULL;
  689. static WINHTTPGETIEPROXYCONFIGFORCURRENTUSER WinHttpGetIEProxyConfigForCurrentUser = NULL;
  690. bool Result = true;
  691. /* Under Win2K SP3, XP and 2003 (or at least Windows versions with
  692. WinHTTP 5.1 installed in some way, it officially shipped with the
  693. versions mentioned earlier) we can use WinHTTP AutoProxy support,
  694. which implements the Web Proxy Auto-Discovery (WPAD) protocol from
  695. an internet draft that expired in May 2001. Under older versions of
  696. Windows we have to use the WinINet InternetGetProxyInfo, however this
  697. consists of a ghastly set of kludges that were never meant to be
  698. exposed to the outside world (they were only crowbarred out of MS
  699. as part of the DoJ consent decree), and user experience with them is
  700. that they don't really work except in the one special way in which
  701. MS-internal code calls them. Since we don't know what this is, we
  702. use the WinHTTP functions instead */
  703. if (WinHTTP == NULL)
  704. {
  705. if ((WinHTTP = LoadLibrary("WinHTTP.dll")) == NULL)
  706. {
  707. Result = false;
  708. }
  709. else
  710. {
  711. WinHttpGetDefaultProxyConfiguration = (WINHTTPGETDEFAULTPROXYCONFIGURATION)
  712. GetProcAddress(WinHTTP, "WinHttpGetDefaultProxyConfiguration");
  713. WinHttpGetIEProxyConfigForCurrentUser = (WINHTTPGETIEPROXYCONFIGFORCURRENTUSER)
  714. GetProcAddress(WinHTTP, "WinHttpGetIEProxyConfigForCurrentUser");
  715. if ((WinHttpGetDefaultProxyConfiguration == NULL) ||
  716. (WinHttpGetIEProxyConfigForCurrentUser == NULL))
  717. {
  718. FreeLibrary(WinHTTP);
  719. Result = false;
  720. }
  721. }
  722. }
  723. if (Result)
  724. {
  725. Result = false;
  726. /* Forst we try for proxy info direct from the registry if
  727. it's available. */
  728. if (!Result)
  729. {
  730. WINHTTP_PROXY_INFO ProxyInfo;
  731. memset(&ProxyInfo, 0, sizeof(ProxyInfo));
  732. if ((WinHttpGetDefaultProxyConfiguration != NULL) &&
  733. WinHttpGetDefaultProxyConfiguration(&ProxyInfo))
  734. {
  735. if (ProxyInfo.lpszProxy != NULL)
  736. {
  737. Proxy = ProxyInfo.lpszProxy;
  738. GlobalFree(ProxyInfo.lpszProxy);
  739. Result = true;
  740. }
  741. if (ProxyInfo.lpszProxyBypass != NULL)
  742. {
  743. GlobalFree(ProxyInfo.lpszProxyBypass);
  744. }
  745. }
  746. }
  747. /* The next fallback is to get the proxy info from MSIE. This is also
  748. usually much quicker than WinHttpGetProxyForUrl(), although sometimes
  749. it seems to fall back to that, based on the longish delay involved.
  750. Another issue with this is that it won't work in a service process
  751. that isn't impersonating an interactive user (since there isn't a
  752. current user), but in that case we just fall back to
  753. WinHttpGetProxyForUrl() */
  754. if (!Result)
  755. {
  756. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG IEProxyInfo;
  757. memset(&IEProxyInfo, 0, sizeof(IEProxyInfo));
  758. if ((WinHttpGetIEProxyConfigForCurrentUser != NULL) &&
  759. WinHttpGetIEProxyConfigForCurrentUser(&IEProxyInfo))
  760. {
  761. if (IEProxyInfo.lpszProxy != NULL)
  762. {
  763. Proxy = IEProxyInfo.lpszProxy;
  764. GlobalFree(IEProxyInfo.lpszProxy);
  765. Result = true;
  766. }
  767. if (IEProxyInfo.lpszAutoConfigUrl != NULL)
  768. {
  769. GlobalFree(IEProxyInfo.lpszAutoConfigUrl);
  770. }
  771. if (IEProxyInfo.lpszProxyBypass != NULL)
  772. {
  773. GlobalFree(IEProxyInfo.lpszProxyBypass);
  774. }
  775. }
  776. }
  777. // We can also use WinHttpGetProxyForUrl, but it is lengthy
  778. // See the source address of the code for example
  779. }
  780. return Result;
  781. }
  782. //---------------------------------------------------------------------------
  783. //---------------------------------------------------------------------------
  784. class TWinHelpTester : public TInterfacedObject, public IWinHelpTester
  785. {
  786. public:
  787. virtual __fastcall ~TWinHelpTester();
  788. virtual bool __fastcall CanShowALink(const AnsiString ALink, const AnsiString FileName);
  789. virtual bool __fastcall CanShowTopic(const AnsiString Topic, const AnsiString FileName);
  790. virtual bool __fastcall CanShowContext(const int Context, const AnsiString FileName);
  791. virtual TStringList * __fastcall GetHelpStrings(const AnsiString ALink);
  792. virtual AnsiString __fastcall GetHelpPath();
  793. virtual AnsiString __fastcall GetDefaultHelpFile();
  794. IUNKNOWN
  795. };
  796. //---------------------------------------------------------------------------
  797. ICustomHelpViewer * CustomHelpViewer = NULL;
  798. _di_IHelpManager * PHelpManager = NULL;
  799. IUnknown * HelpManagerUnknown = NULL;
  800. TObjectList * ViewerList = NULL;
  801. ICustomHelpViewer * WinHelpViewer = NULL;
  802. //---------------------------------------------------------------------------
  803. static int __fastcall ViewerID(int Index)
  804. {
  805. // 8 is offset from THelpViewerNode to THelpViewerNode::FViewer
  806. return
  807. *reinterpret_cast<int *>(reinterpret_cast<char *>(ViewerList->Items[Index])
  808. + 8);
  809. }
  810. //---------------------------------------------------------------------------
  811. static void __fastcall InternalShutdown(int Index)
  812. {
  813. assert(PHelpManager != NULL);
  814. if (PHelpManager != NULL)
  815. {
  816. // override conflict of two Release() methods by getting
  817. // IHelpManager explicitly using operator *
  818. (**PHelpManager).Release(ViewerID(Index));
  819. // registration to help manager increases refcount by 2, but deregistration
  820. // by one only
  821. CustomHelpViewer->Release();
  822. }
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall InitializeCustomHelp(ICustomHelpViewer * HelpViewer)
  826. {
  827. assert(PHelpManager == NULL);
  828. CustomHelpViewer = HelpViewer;
  829. // workaround
  830. // _di_IHelpManager cannot be instantiated due to either bug in compiler or
  831. // VCL code
  832. PHelpManager = (_di_IHelpManager*)malloc(sizeof(_di_IHelpManager));
  833. // our own reference
  834. CustomHelpViewer->AddRef();
  835. RegisterViewer(CustomHelpViewer, *PHelpManager);
  836. HelpManagerUnknown = dynamic_cast<IUnknown *>(&**PHelpManager);
  837. // 40 is offset from IHelpManager to THelpManager
  838. // 16 is offset from THelpManager to THelpManager::FViewerList
  839. ViewerList =
  840. *reinterpret_cast<TObjectList **>(reinterpret_cast<char *>(&**PHelpManager)
  841. - 40 + 16);
  842. assert(ViewerList->Count == 2);
  843. // gross hack
  844. // Due to major bugs in VCL help system, unregister winhelp at all.
  845. // To do this we must call RegisterViewer first to get HelpManager.
  846. // Due to another bug, viewers must be unregistred in order reversed to
  847. // registration order, so we must unregister out help viewer first
  848. // and register it again at the end
  849. InternalShutdown(1);
  850. assert(ViewerList->Count == 1);
  851. int WinHelpViewerID = ViewerID(0);
  852. // 4 is offset from THelpViewerNode to THelpViewerNode::FViewer
  853. WinHelpViewer =
  854. *reinterpret_cast<_di_ICustomHelpViewer *>(reinterpret_cast<char *>(ViewerList->Items[0])
  855. + 4);
  856. // our reference
  857. // we cannot release win help viewer completelly here as finalization code of
  858. // WinHelpViewer expect it to exist
  859. WinHelpViewer->AddRef();
  860. (**PHelpManager).Release(WinHelpViewerID);
  861. // remove forgoten 3 references of manager
  862. WinHelpViewer->Release();
  863. WinHelpViewer->Release();
  864. WinHelpViewer->Release();
  865. assert(ViewerList->Count == 0);
  866. // this clears reference to manager in TWinHelpViewer::FHelpManager,
  867. // preventing call to TWinHelpViewer::InternalShutdown from finalization code
  868. // of WinHelpViewer
  869. WinHelpViewer->ShutDown();
  870. RegisterViewer(CustomHelpViewer, *PHelpManager);
  871. // we've got second reference to the same pointer here, release it
  872. HelpManagerUnknown->Release();
  873. assert(ViewerList->Count == 1);
  874. // now when winhelp is not registered, the tester is not used anyway
  875. // for any real work, but we use it as a hook to be called after
  876. // finalization of WinHelpViewer (see its finalization section)
  877. WinHelpTester = new TWinHelpTester();
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall FinalizeCustomHelp()
  881. {
  882. if (CustomHelpViewer != NULL)
  883. {
  884. // unregister ourselves to release both references
  885. InternalShutdown(0);
  886. // our own reference
  887. CustomHelpViewer->Release();
  888. }
  889. if (PHelpManager != NULL)
  890. {
  891. assert(ViewerList->Count == 0);
  892. // our reference
  893. HelpManagerUnknown->Release();
  894. free(PHelpManager);
  895. PHelpManager = NULL;
  896. HelpManagerUnknown = NULL;
  897. }
  898. }
  899. //---------------------------------------------------------------------------
  900. void __fastcall CleanUpWinHelp()
  901. {
  902. // WinHelpViewer finalization code should have been called by now already,
  903. // so we can safely remove the last reference to destroy it
  904. assert(WinHelpViewer != NULL);
  905. WinHelpViewer->Release();
  906. }
  907. //---------------------------------------------------------------------------
  908. //---------------------------------------------------------------------------
  909. __fastcall TWinHelpTester::~TWinHelpTester()
  910. {
  911. CleanUpWinHelp();
  912. }
  913. //---------------------------------------------------------------------------
  914. bool __fastcall TWinHelpTester::CanShowALink(const AnsiString ALink,
  915. const AnsiString FileName)
  916. {
  917. assert(false);
  918. return !Application->HelpFile.IsEmpty();
  919. }
  920. //---------------------------------------------------------------------------
  921. bool __fastcall TWinHelpTester::CanShowTopic(const AnsiString Topic,
  922. const AnsiString FileName)
  923. {
  924. assert(false);
  925. return !Application->HelpFile.IsEmpty();
  926. }
  927. //---------------------------------------------------------------------------
  928. bool __fastcall TWinHelpTester::CanShowContext(const int /*Context*/,
  929. const AnsiString FileName)
  930. {
  931. assert(false);
  932. return !Application->HelpFile.IsEmpty();
  933. }
  934. //---------------------------------------------------------------------------
  935. TStringList * __fastcall TWinHelpTester::GetHelpStrings(const AnsiString ALink)
  936. {
  937. assert(false);
  938. TStringList * Result = new TStringList();
  939. Result->Add(ViewerName + ": " + ALink);
  940. return Result;
  941. }
  942. //---------------------------------------------------------------------------
  943. AnsiString __fastcall TWinHelpTester::GetHelpPath()
  944. {
  945. assert(false);
  946. // never called on windows anyway
  947. return ExtractFilePath(Application->HelpFile);
  948. }
  949. //---------------------------------------------------------------------------
  950. AnsiString __fastcall TWinHelpTester::GetDefaultHelpFile()
  951. {
  952. assert(false);
  953. return Application->HelpFile;
  954. }