Tools.cpp 33 KB

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