Tools.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Consts.hpp>
  5. #include <shlobj.h>
  6. #include <stdio.h>
  7. #define INITGUID
  8. #include <propkey.h>
  9. #include <powrprof.h>
  10. #include <Common.h>
  11. #include <TextsWin.h>
  12. #include <TextsCore.h>
  13. #include <HelpWin.h>
  14. #include <Exceptions.h>
  15. #include <CoreMain.h>
  16. #include <RemoteFiles.h>
  17. #include <PuttyTools.h>
  18. #include "GUITools.h"
  19. #include "VCLCommon.h"
  20. #include "Setup.h"
  21. #include "Tools.h"
  22. #include <WinHelpViewer.hpp>
  23. #include <PasTools.hpp>
  24. #include <System.Win.ComObj.hpp>
  25. #include <StrUtils.hpp>
  26. #include <WinConfiguration.h>
  27. #include <ProgParams.h>
  28. //---------------------------------------------------------------------------
  29. // WORKAROUND
  30. // VCL includes wininet.h (even with NO_WIN32_LEAN_AND_MEAN)
  31. // and it cannot be combined with winhttp.h as of current Windows SDK.
  32. // This is hack to allow that.
  33. // http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/8f468d9f-3f15-452c-803d-fc63ab3f684e/cannot-use-both-winineth-and-winhttph
  34. #undef BOOLAPI
  35. #undef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
  36. #undef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
  37. #define URL_COMPONENTS URL_COMPONENTS_ANOTHER
  38. #define URL_COMPONENTSA URL_COMPONENTSA_ANOTHER
  39. #define URL_COMPONENTSW URL_COMPONENTSW_ANOTHER
  40. #define LPURL_COMPONENTS LPURL_COMPONENTS_ANOTHER
  41. #define LPURL_COMPONENTSA LPURL_COMPONENTS_ANOTHER
  42. #define LPURL_COMPONENTSW LPURL_COMPONENTS_ANOTHER
  43. #define INTERNET_SCHEME INTERNET_SCHEME_ANOTHER
  44. #define LPINTERNET_SCHEME LPINTERNET_SCHEME_ANOTHER
  45. #define HTTP_VERSION_INFO HTTP_VERSION_INFO_ANOTHER
  46. #define LPHTTP_VERSION_INFO LPHTTP_VERSION_INFO_ANOTHER
  47. #include <winhttp.h>
  48. #undef URL_COMPONENTS
  49. #undef URL_COMPONENTSA
  50. #undef URL_COMPONENTSW
  51. #undef LPURL_COMPONENTS
  52. #undef LPURL_COMPONENTSA
  53. #undef LPURL_COMPONENTSW
  54. #undef INTERNET_SCHEME
  55. #undef LPINTERNET_SCHEME
  56. #undef HTTP_VERSION_INFO
  57. #undef LPHTTP_VERSION_INFO
  58. //---------------------------------------------------------------------------
  59. #pragma package(smart_init)
  60. //---------------------------------------------------------------------------
  61. TFontStyles __fastcall IntToFontStyles(int value)
  62. {
  63. TFontStyles Result;
  64. for (int i = fsBold; i <= fsStrikeOut; i++)
  65. {
  66. if (value & 1)
  67. {
  68. Result << (TFontStyle)i;
  69. }
  70. value >>= 1;
  71. }
  72. return Result;
  73. }
  74. //---------------------------------------------------------------------------
  75. int __fastcall FontStylesToInt(const TFontStyles value)
  76. {
  77. int Result = 0;
  78. for (int i = fsStrikeOut; i >= fsBold; i--)
  79. {
  80. Result <<= 1;
  81. if (value.Contains((TFontStyle)i))
  82. {
  83. Result |= 1;
  84. }
  85. }
  86. return Result;
  87. }
  88. //---------------------------------------------------------------------------
  89. bool __fastcall SameFont(TFont * Font1, TFont * Font2)
  90. {
  91. // keep in sync with TFontConfiguration::operator !=
  92. return SameText(Font1->Name, Font2->Name) && (Font1->Size == Font2->Size) &&
  93. (Font1->Charset == Font2->Charset) && (Font1->Style == Font2->Style);
  94. }
  95. //---------------------------------------------------------------------------
  96. void __fastcall CenterFormOn(TForm * Form, TControl * CenterOn)
  97. {
  98. TPoint ScreenPoint = CenterOn->ClientToScreen(TPoint(0, 0));
  99. Form->Left = ScreenPoint.x + (CenterOn->Width / 2) - (Form->Width / 2);
  100. Form->Top = ScreenPoint.y + (CenterOn->Height / 2) - (Form->Height / 2);
  101. }
  102. //---------------------------------------------------------------------------
  103. UnicodeString __fastcall GetListViewStr(TListView * ListView)
  104. {
  105. UnicodeString Result;
  106. for (int Index = 0; Index < ListView->Columns->Count; Index++)
  107. {
  108. AddToList(Result, IntToStr(ListView->Column[Index]->Width), L",");
  109. }
  110. // WORKAROUND
  111. // Adding an additional comma after the list,
  112. // to ensure that old versions that did not expect the pixels-per-inch part,
  113. // stop at the comma, otherwise they try to parse the
  114. // "last-column-width;pixels-per-inch" as integer and throw.
  115. // For the other instance of this hack, see TCustomListViewColProperties.GetParamsStr
  116. Result += L",;" + SavePixelsPerInch();
  117. return Result;
  118. }
  119. //---------------------------------------------------------------------------
  120. void __fastcall LoadListViewStr(TListView * ListView, UnicodeString ALayoutStr)
  121. {
  122. UnicodeString LayoutStr = ::CutToChar(ALayoutStr, L';', true);
  123. int PixelsPerInch = LoadPixelsPerInch(::CutToChar(ALayoutStr, L';', true));
  124. int Index = 0;
  125. while (!LayoutStr.IsEmpty() && (Index < ListView->Columns->Count))
  126. {
  127. int Width;
  128. if (TryStrToInt(::CutToChar(LayoutStr, L',', true), Width))
  129. {
  130. ListView->Column[Index]->Width = LoadDimension(Width, PixelsPerInch);
  131. }
  132. Index++;
  133. }
  134. }
  135. //---------------------------------------------------------------------------
  136. void __fastcall RestoreForm(UnicodeString Data, TForm * Form)
  137. {
  138. assert(Form);
  139. if (!Data.IsEmpty())
  140. {
  141. Forms::TMonitor * Monitor = FormMonitor(Form);
  142. UnicodeString LeftStr = ::CutToChar(Data, L';', true);
  143. UnicodeString TopStr = ::CutToChar(Data, L';', true);
  144. UnicodeString RightStr = ::CutToChar(Data, L';', true);
  145. UnicodeString BottomStr = ::CutToChar(Data, L';', true);
  146. TWindowState State = (TWindowState)StrToIntDef(::CutToChar(Data, L';', true), (int)wsNormal);
  147. int PixelsPerInch = LoadPixelsPerInch(::CutToChar(Data, L';', true));
  148. TRect Bounds = Form->BoundsRect;
  149. int Left = StrToDimensionDef(LeftStr, PixelsPerInch, Bounds.Left);
  150. int Top = StrToDimensionDef(TopStr, PixelsPerInch, Bounds.Top);
  151. bool DefaultPos = (Left == -1) && (Top == -1);
  152. if (!DefaultPos)
  153. {
  154. Bounds.Left = Left;
  155. Bounds.Top = Top;
  156. }
  157. else
  158. {
  159. Bounds.Left = 0;
  160. Bounds.Top = 0;
  161. }
  162. Bounds.Right = StrToDimensionDef(RightStr, PixelsPerInch, Bounds.Right);
  163. Bounds.Bottom = StrToDimensionDef(BottomStr, PixelsPerInch, Bounds.Bottom);
  164. Form->WindowState = State;
  165. if (State == wsNormal)
  166. {
  167. // move to the target monitor
  168. OffsetRect(Bounds, Monitor->Left, Monitor->Top);
  169. // reduce window size to that of monitor size
  170. // (this does not cut window into monitor!)
  171. if (Bounds.Width() > Monitor->WorkareaRect.Width())
  172. {
  173. Bounds.Right -= (Bounds.Width() - Monitor->WorkareaRect.Width());
  174. }
  175. if (Bounds.Height() > Monitor->WorkareaRect.Height())
  176. {
  177. Bounds.Bottom -= (Bounds.Height() - Monitor->WorkareaRect.Height());
  178. }
  179. if (DefaultPos ||
  180. ((Bounds.Left < Monitor->Left) ||
  181. (Bounds.Left > Monitor->Left + Monitor->WorkareaRect.Width() - 20) ||
  182. (Bounds.Top < Monitor->Top) ||
  183. (Bounds.Top > Monitor->Top + Monitor->WorkareaRect.Height() - 20)))
  184. {
  185. if (Monitor->Primary)
  186. {
  187. if ((Application->MainForm == NULL) || (Application->MainForm == Form))
  188. {
  189. Form->Position = poDefaultPosOnly;
  190. }
  191. else
  192. {
  193. Form->Position = poOwnerFormCenter;
  194. }
  195. Form->Width = Bounds.Width();
  196. Form->Height = Bounds.Height();
  197. }
  198. else
  199. {
  200. // when positioning on non-primary monitor, we need
  201. // to handle that ourselves, so place window to center
  202. Form->SetBounds(Monitor->Left + ((Monitor->Width - Bounds.Width()) / 2),
  203. Monitor->Top + ((Monitor->Height - Bounds.Height()) / 2),
  204. Bounds.Width(), Bounds.Height());
  205. Form->Position = poDesigned;
  206. }
  207. }
  208. else
  209. {
  210. Form->Position = poDesigned;
  211. Form->BoundsRect = Bounds;
  212. }
  213. }
  214. else if (State == wsMaximized)
  215. {
  216. Form->Position = poDesigned;
  217. Bounds = Form->BoundsRect;
  218. OffsetRect(Bounds, Monitor->Left, Monitor->Top);
  219. Form->BoundsRect = Bounds;
  220. }
  221. }
  222. else if (Form->Position == poDesigned)
  223. {
  224. Form->Position = poDefaultPosOnly;
  225. }
  226. }
  227. //---------------------------------------------------------------------------
  228. UnicodeString __fastcall StoreForm(TCustomForm * Form)
  229. {
  230. assert(Form);
  231. TRect Bounds = Form->BoundsRect;
  232. OffsetRect(Bounds, -Form->Monitor->Left, -Form->Monitor->Top);
  233. return FORMAT(L"%d;%d;%d;%d;%d;%s", (SaveDimension(Bounds.Left), SaveDimension(Bounds.Top),
  234. SaveDimension(Bounds.Right), SaveDimension(Bounds.Bottom),
  235. // we do not want WinSCP to start minimized next time (we cannot handle that anyway).
  236. // note that WindowState is wsNormal when window in minimized for some reason.
  237. // actually it is wsMinimized only when minimized by MSVDM
  238. (int)(Form->WindowState == wsMinimized ? wsNormal : Form->WindowState),
  239. SavePixelsPerInch()));
  240. }
  241. //---------------------------------------------------------------------------
  242. void __fastcall RestoreFormSize(UnicodeString Data, TForm * Form)
  243. {
  244. // This has to be called only after DoFormWindowProc(CM_SHOWINGCHANGED).
  245. // See comment in ResizeForm.
  246. UnicodeString WidthStr = ::CutToChar(Data, L',', true);
  247. UnicodeString HeightStr = ::CutToChar(Data, L',', true);
  248. int PixelsPerInch = LoadPixelsPerInch(::CutToChar(Data, L',', true));
  249. int Width = StrToDimensionDef(WidthStr, PixelsPerInch, Form->Width);
  250. int Height = StrToDimensionDef(HeightStr, PixelsPerInch, Form->Height);
  251. ResizeForm(Form, Width, Height);
  252. }
  253. //---------------------------------------------------------------------------
  254. UnicodeString __fastcall StoreFormSize(TForm * Form)
  255. {
  256. return FORMAT(L"%d,%d,%s", (Form->Width, Form->Height, SavePixelsPerInch()));
  257. }
  258. //---------------------------------------------------------------------------
  259. bool __fastcall ExecuteShellAndWait(const UnicodeString Path, const UnicodeString Params)
  260. {
  261. return ExecuteShellAndWait(Application->Handle, Path, Params,
  262. &Application->ProcessMessages);
  263. }
  264. //---------------------------------------------------------------------------
  265. bool __fastcall ExecuteShellAndWait(const UnicodeString Command)
  266. {
  267. return ExecuteShellAndWait(Application->Handle, Command,
  268. &Application->ProcessMessages);
  269. }
  270. //---------------------------------------------------------------------------
  271. bool __fastcall UseAlternativeFunction()
  272. {
  273. return FLAGSET(GetAsyncKeyState(VK_SHIFT), 0x8000);
  274. }
  275. //---------------------------------------------------------------------------
  276. bool __fastcall OpenInNewWindow()
  277. {
  278. return UseAlternativeFunction();
  279. }
  280. //---------------------------------------------------------------------------
  281. void __fastcall ExecuteNewInstance(const UnicodeString & Param)
  282. {
  283. UnicodeString Arg = Param;
  284. if (!Arg.IsEmpty())
  285. {
  286. Arg = FORMAT(L"\"%s\" %s", (Arg, TProgramParams::FormatSwitch(NEWINSTANCE_SWICH)));
  287. }
  288. if (!ExecuteShell(Application->ExeName, Arg))
  289. {
  290. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Application->ExeName)));
  291. }
  292. }
  293. //---------------------------------------------------------------------------
  294. IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
  295. const UnicodeString &File, const UnicodeString & Params, const UnicodeString & Description,
  296. int SpecialFolder, int IconIndex, bool Return)
  297. {
  298. IShellLink* pLink = NULL;
  299. if (SpecialFolder < 0)
  300. {
  301. SpecialFolder = CSIDL_DESKTOPDIRECTORY;
  302. }
  303. try
  304. {
  305. if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
  306. IID_IShellLink, (void **) &pLink)))
  307. {
  308. try
  309. {
  310. pLink->SetPath(File.c_str());
  311. pLink->SetDescription(Description.c_str());
  312. pLink->SetArguments(Params.c_str());
  313. pLink->SetShowCmd(SW_SHOW);
  314. // Explicitly setting icon file,
  315. // without this icons are not shown at least in Windows 7 jumplist
  316. pLink->SetIconLocation(File.c_str(), IconIndex);
  317. IPersistFile* pPersistFile;
  318. if (!Return &&
  319. SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
  320. {
  321. try
  322. {
  323. LPMALLOC ShellMalloc;
  324. LPITEMIDLIST DesktopPidl;
  325. wchar_t DesktopDir[MAX_PATH];
  326. OleCheck(SHGetMalloc(&ShellMalloc));
  327. try
  328. {
  329. OleCheck(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl));
  330. OleCheck(SHGetPathFromIDList(DesktopPidl, DesktopDir));
  331. }
  332. __finally
  333. {
  334. ShellMalloc->Free(DesktopPidl);
  335. ShellMalloc->Release();
  336. }
  337. WideString strShortCutLocation(DesktopDir);
  338. // Name can contain even path (e.g. to create quick launch icon)
  339. strShortCutLocation += UnicodeString(L"\\") + Name + L".lnk";
  340. OleCheck(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE));
  341. }
  342. __finally
  343. {
  344. pPersistFile->Release();
  345. }
  346. }
  347. // this is necessary for Windows 7 taskbar jump list links
  348. IPropertyStore * PropertyStore;
  349. if (SUCCEEDED(pLink->QueryInterface(IID_IPropertyStore, (void**)&PropertyStore)))
  350. {
  351. PROPVARIANT Prop;
  352. Prop.vt = VT_LPWSTR;
  353. Prop.pwszVal = Name.c_str();
  354. PropertyStore->SetValue(PKEY_Title, Prop);
  355. PropertyStore->Commit();
  356. PropertyStore->Release();
  357. }
  358. }
  359. catch(...)
  360. {
  361. pLink->Release();
  362. throw;
  363. }
  364. if (!Return)
  365. {
  366. pLink->Release();
  367. pLink = NULL;
  368. }
  369. }
  370. }
  371. catch(Exception & E)
  372. {
  373. throw ExtException(&E, LoadStr(CREATE_SHORTCUT_ERROR));
  374. }
  375. return pLink;
  376. }
  377. //---------------------------------------------------------------------------
  378. IShellLink * __fastcall CreateDesktopSessionShortCut(
  379. const UnicodeString & SessionName, UnicodeString Name,
  380. const UnicodeString & AdditionalParams, int SpecialFolder, int IconIndex,
  381. bool Return)
  382. {
  383. bool DefaultsOnly;
  384. UnicodeString InfoTip;
  385. bool IsFolder = StoredSessions->IsFolder(SessionName);
  386. bool IsWorkspace = StoredSessions->IsWorkspace(SessionName);
  387. if (IsFolder || IsWorkspace)
  388. {
  389. InfoTip = FMTLOAD(
  390. (IsFolder ? SHORTCUT_INFO_TIP_FOLDER : SHORTCUT_INFO_TIP_WORKSPACE),
  391. (SessionName));
  392. if (Name.IsEmpty())
  393. {
  394. // no slashes in filename
  395. Name = UnixExtractFileName(SessionName);
  396. }
  397. }
  398. else
  399. {
  400. // this should not be done for workspaces and folders
  401. TSessionData * SessionData =
  402. StoredSessions->ParseUrl(SessionName, NULL, DefaultsOnly);
  403. InfoTip =
  404. FMTLOAD(SHORTCUT_INFO_TIP, (SessionName, SessionData->InfoTip));
  405. if (Name.IsEmpty())
  406. {
  407. // no slashes in filename
  408. Name = SessionData->LocalName;
  409. }
  410. delete SessionData;
  411. }
  412. return
  413. CreateDesktopShortCut(ValidLocalFileName(Name), Application->ExeName,
  414. FORMAT(L"\"%s\"%s%s", (SessionName, (AdditionalParams.IsEmpty() ? L"" : L" "), AdditionalParams)),
  415. InfoTip, SpecialFolder, IconIndex, Return);
  416. }
  417. //---------------------------------------------------------------------------
  418. template<class TEditControl>
  419. void __fastcall ValidateMaskEditT(const UnicodeString & Mask, TEditControl * Edit, int ForceDirectoryMasks)
  420. {
  421. assert(Edit != NULL);
  422. TFileMasks Masks(ForceDirectoryMasks);
  423. try
  424. {
  425. Masks = Mask;
  426. }
  427. catch(EFileMasksException & E)
  428. {
  429. ShowExtendedException(&E);
  430. Edit->SetFocus();
  431. // This does not work for TEdit and TMemo (descendants of TCustomEdit) anymore,
  432. // as it re-selects whole text on exception in TCustomEdit.CMExit
  433. Edit->SelStart = E.ErrorStart - 1;
  434. Edit->SelLength = E.ErrorLen;
  435. Abort();
  436. }
  437. }
  438. //---------------------------------------------------------------------------
  439. void __fastcall ValidateMaskEdit(TComboBox * Edit)
  440. {
  441. ValidateMaskEditT(Edit->Text, Edit, -1);
  442. }
  443. //---------------------------------------------------------------------------
  444. void __fastcall ValidateMaskEdit(TEdit * Edit)
  445. {
  446. ValidateMaskEditT(Edit->Text, Edit, -1);
  447. }
  448. //---------------------------------------------------------------------------
  449. void __fastcall ValidateMaskEdit(TMemo * Edit, bool Directory)
  450. {
  451. UnicodeString Mask = TFileMasks::ComposeMaskStr(GetUnwrappedMemoLines(Edit), Directory);
  452. ValidateMaskEditT(Mask, Edit, Directory ? 1 : 0);
  453. }
  454. //---------------------------------------------------------------------------
  455. TStrings * __fastcall GetUnwrappedMemoLines(TMemo * Memo)
  456. {
  457. // This removes soft linebreakes when text in memo wraps
  458. // (Memo->Lines includes soft linebreaks, while Memo->Text does not)
  459. return TextToStringList(Memo->Text);
  460. }
  461. //---------------------------------------------------------------------------
  462. void __fastcall ExitActiveControl(TForm * Form)
  463. {
  464. if (Form->ActiveControl != NULL)
  465. {
  466. TNotifyEvent OnExit = ((TEdit*)Form->ActiveControl)->OnExit;
  467. if (OnExit != NULL)
  468. {
  469. OnExit(Form->ActiveControl);
  470. }
  471. }
  472. }
  473. //---------------------------------------------------------------------------
  474. void __fastcall OpenBrowser(UnicodeString URL)
  475. {
  476. UnicodeString HomePageUrl = LoadStr(HOMEPAGE_URL);
  477. if (SameText(URL.SubString(1, HomePageUrl.Length()), HomePageUrl))
  478. {
  479. URL = CampaignUrl(URL);
  480. }
  481. ShellExecute(Application->Handle, L"open", URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
  482. }
  483. //---------------------------------------------------------------------------
  484. bool __fastcall IsFormatInClipboard(unsigned int Format)
  485. {
  486. bool Result = OpenClipboard(0);
  487. if (Result)
  488. {
  489. Result = IsClipboardFormatAvailable(Format);
  490. CloseClipboard();
  491. }
  492. return Result;
  493. }
  494. //---------------------------------------------------------------------------
  495. HANDLE __fastcall OpenTextFromClipboard(const wchar_t *& Text)
  496. {
  497. HANDLE Result = NULL;
  498. if (OpenClipboard(0))
  499. {
  500. // Check also for CF_TEXT?
  501. Result = GetClipboardData(CF_UNICODETEXT);
  502. if (Result != NULL)
  503. {
  504. Text = static_cast<const wchar_t*>(GlobalLock(Result));
  505. }
  506. else
  507. {
  508. CloseClipboard();
  509. }
  510. }
  511. return Result;
  512. }
  513. //---------------------------------------------------------------------------
  514. void __fastcall CloseTextFromClipboard(HANDLE Handle)
  515. {
  516. if (Handle != NULL)
  517. {
  518. GlobalUnlock(Handle);
  519. }
  520. CloseClipboard();
  521. }
  522. //---------------------------------------------------------------------------
  523. bool __fastcall TextFromClipboard(UnicodeString & Text, bool Trim)
  524. {
  525. const wchar_t * AText = NULL;
  526. HANDLE Handle = OpenTextFromClipboard(AText);
  527. bool Result = (Handle != NULL);
  528. if (Result)
  529. {
  530. Text = AText;
  531. if (Trim)
  532. {
  533. Text = Text.Trim();
  534. }
  535. CloseTextFromClipboard(Handle);
  536. }
  537. return Result;
  538. }
  539. //---------------------------------------------------------------------------
  540. static bool __fastcall GetResource(
  541. const UnicodeString ResName, void *& Content, unsigned long & Size)
  542. {
  543. HRSRC Resource = FindResourceEx(HInstance, RT_RCDATA, ResName.c_str(),
  544. MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
  545. bool Result = (Resource != NULL);
  546. if (Result)
  547. {
  548. Size = SizeofResource(HInstance, Resource);
  549. if (!Size)
  550. {
  551. throw Exception(FORMAT(L"Cannot get size of resource %s", (ResName)));
  552. }
  553. Content = LoadResource(HInstance, Resource);
  554. if (!Content)
  555. {
  556. throw Exception(FORMAT(L"Cannot read resource %s", (ResName)));
  557. }
  558. Content = LockResource(Content);
  559. if (!Content)
  560. {
  561. throw Exception(FORMAT(L"Cannot lock resource %s", (ResName)));
  562. }
  563. }
  564. return Result;
  565. }
  566. //---------------------------------------------------------------------------
  567. bool __fastcall DumpResourceToFile(const UnicodeString ResName,
  568. const UnicodeString FileName)
  569. {
  570. void * Content;
  571. unsigned long Size;
  572. bool Result = GetResource(ResName, Content, Size);
  573. if (Result)
  574. {
  575. FILE * f = _wfopen(::ApiPath(FileName).c_str(), L"wb");
  576. if (!f)
  577. {
  578. throw Exception(FORMAT(L"Cannot create file %s", (FileName)));
  579. }
  580. if (fwrite(Content, 1, Size, f) != Size)
  581. {
  582. throw Exception(FORMAT(L"Cannot write to file %s", (FileName)));
  583. }
  584. fclose(f);
  585. }
  586. return Result;
  587. }
  588. //---------------------------------------------------------------------------
  589. UnicodeString __fastcall ReadResource(const UnicodeString ResName)
  590. {
  591. void * Content;
  592. unsigned long Size;
  593. UnicodeString Result;
  594. if (GetResource(ResName, Content, Size))
  595. {
  596. Result = UnicodeString(UTF8String(static_cast<char*>(Content), Size));
  597. }
  598. return Result;
  599. }
  600. //---------------------------------------------------------------------------
  601. template <class T>
  602. void __fastcall BrowseForExecutableT(T * Control, UnicodeString Title,
  603. UnicodeString Filter, bool FileNameCommand, bool Escape)
  604. {
  605. UnicodeString Executable, Program, Params, Dir;
  606. Executable = Control->Text;
  607. if (FileNameCommand)
  608. {
  609. ReformatFileNameCommand(Executable);
  610. }
  611. SplitCommand(Executable, Program, Params, Dir);
  612. TOpenDialog * FileDialog = new TOpenDialog(Application);
  613. try
  614. {
  615. if (Escape)
  616. {
  617. Program = ReplaceStr(Program, L"\\\\", L"\\");
  618. }
  619. UnicodeString ExpandedProgram = ExpandEnvironmentVariables(Program);
  620. FileDialog->FileName = ExpandedProgram;
  621. UnicodeString InitialDir = ExtractFilePath(ExpandedProgram);
  622. if (!InitialDir.IsEmpty())
  623. {
  624. FileDialog->InitialDir = InitialDir;
  625. }
  626. FileDialog->Filter = Filter;
  627. FileDialog->Title = Title;
  628. if (FileDialog->Execute())
  629. {
  630. TNotifyEvent PrevOnChange = Control->OnChange;
  631. Control->OnChange = NULL;
  632. try
  633. {
  634. // preserve unexpanded file, if the destination has not changed actually
  635. if (!CompareFileName(ExpandedProgram, FileDialog->FileName))
  636. {
  637. Program = FileDialog->FileName;
  638. if (Escape)
  639. {
  640. Program = ReplaceStr(Program, L"\\", L"\\\\");
  641. }
  642. }
  643. Control->Text = FormatCommand(Program, Params);
  644. }
  645. __finally
  646. {
  647. Control->OnChange = PrevOnChange;
  648. }
  649. if (Control->OnExit != NULL)
  650. {
  651. Control->OnExit(Control);
  652. }
  653. }
  654. }
  655. __finally
  656. {
  657. delete FileDialog;
  658. }
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall BrowseForExecutable(TEdit * Control, UnicodeString Title,
  662. UnicodeString Filter, bool FileNameCommand, bool Escape)
  663. {
  664. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  665. }
  666. //---------------------------------------------------------------------------
  667. void __fastcall BrowseForExecutable(TComboBox * Control, UnicodeString Title,
  668. UnicodeString Filter, bool FileNameCommand, bool Escape)
  669. {
  670. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  671. }
  672. //---------------------------------------------------------------------------
  673. bool __fastcall FontDialog(TFont * Font)
  674. {
  675. bool Result;
  676. TFontDialog * Dialog = new TFontDialog(Application);
  677. try
  678. {
  679. Dialog->Device = fdScreen;
  680. Dialog->Options = TFontDialogOptions() << fdForceFontExist;
  681. Dialog->Font = Font;
  682. Result = Dialog->Execute();
  683. if (Result)
  684. {
  685. Font->Assign(Dialog->Font);
  686. }
  687. }
  688. __finally
  689. {
  690. delete Dialog;
  691. }
  692. return Result;
  693. }
  694. //---------------------------------------------------------------------------
  695. bool __fastcall SaveDialog(UnicodeString Title, UnicodeString Filter,
  696. UnicodeString DefaultExt, UnicodeString & FileName)
  697. {
  698. bool Result;
  699. #if 0
  700. TFileSaveDialog * Dialog = new TFileSaveDialog(Application);
  701. try
  702. {
  703. Dialog->Title = Title;
  704. FilterToFileTypes(Filter, Dialog->FileTypes);
  705. Dialog->DefaultExtension = DefaultExt;
  706. Dialog->FileName = FileName;
  707. UnicodeString DefaultFolder = ExtractFilePath(FileName);
  708. if (!DefaultFolder.IsEmpty())
  709. {
  710. Dialog->DefaultFolder = DefaultFolder;
  711. }
  712. Dialog->Options = Dialog->Options << fdoOverWritePrompt << fdoForceFileSystem <<
  713. fdoPathMustExist << fdoNoReadOnlyReturn;
  714. Result = Dialog->Execute();
  715. if (Result)
  716. {
  717. FileName = Dialog->FileName;
  718. }
  719. }
  720. __finally
  721. {
  722. delete Dialog;
  723. }
  724. #else
  725. TSaveDialog * Dialog = new TSaveDialog(Application);
  726. try
  727. {
  728. Dialog->Title = Title;
  729. Dialog->Filter = Filter;
  730. Dialog->DefaultExt = DefaultExt;
  731. Dialog->FileName = FileName;
  732. UnicodeString InitialDir = ExtractFilePath(FileName);
  733. if (!InitialDir.IsEmpty())
  734. {
  735. Dialog->InitialDir = InitialDir;
  736. }
  737. Dialog->Options = Dialog->Options << ofOverwritePrompt << ofPathMustExist <<
  738. ofNoReadOnlyReturn;
  739. Result = Dialog->Execute();
  740. if (Result)
  741. {
  742. FileName = Dialog->FileName;
  743. }
  744. }
  745. __finally
  746. {
  747. delete Dialog;
  748. }
  749. #endif
  750. return Result;
  751. }
  752. //---------------------------------------------------------------------------
  753. void __fastcall CopyToClipboard(UnicodeString Text)
  754. {
  755. HANDLE Data;
  756. void * DataPtr;
  757. if (OpenClipboard(0))
  758. {
  759. try
  760. {
  761. size_t Size = (Text.Length() + 1) * sizeof(wchar_t);
  762. Data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Size);
  763. try
  764. {
  765. DataPtr = GlobalLock(Data);
  766. try
  767. {
  768. memcpy(DataPtr, Text.c_str(), Size);
  769. EmptyClipboard();
  770. SetClipboardData(CF_UNICODETEXT, Data);
  771. }
  772. __finally
  773. {
  774. GlobalUnlock(Data);
  775. }
  776. }
  777. catch(...)
  778. {
  779. GlobalFree(Data);
  780. throw;
  781. }
  782. }
  783. __finally
  784. {
  785. CloseClipboard();
  786. }
  787. }
  788. else
  789. {
  790. throw Exception(Vcl_Consts_SCannotOpenClipboard);
  791. }
  792. }
  793. //---------------------------------------------------------------------------
  794. void __fastcall CopyToClipboard(TStrings * Strings)
  795. {
  796. if (Strings->Count > 0)
  797. {
  798. if (Strings->Count == 1)
  799. {
  800. CopyToClipboard(Strings->Strings[0]);
  801. }
  802. else
  803. {
  804. CopyToClipboard(Strings->Text);
  805. }
  806. }
  807. }
  808. //---------------------------------------------------------------------------
  809. bool __fastcall IsWin64()
  810. {
  811. static int Result = -1;
  812. if (Result < 0)
  813. {
  814. Result = 0;
  815. BOOL Wow64Process = FALSE;
  816. if (IsWow64Process(GetCurrentProcess(), &Wow64Process))
  817. {
  818. if (Wow64Process)
  819. {
  820. Result = 1;
  821. }
  822. }
  823. }
  824. return (Result > 0);
  825. }
  826. //---------------------------------------------------------------------------
  827. static void __fastcall AcquireShutDownPrivileges()
  828. {
  829. HANDLE Token;
  830. // Get a token for this process.
  831. Win32Check(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token));
  832. TOKEN_PRIVILEGES Priv;
  833. ZeroMemory(&Priv, sizeof(Priv));
  834. // Get the LUID for the shutdown privilege.
  835. // For hibernate/suspend, you need the same:
  836. // http://stackoverflow.com/questions/959589/is-there-any-win32-api-to-trigger-the-hibernate-or-suspend-mode-in-windows
  837. Win32Check(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &Priv.Privileges[0].Luid));
  838. Priv.PrivilegeCount = 1; // one privilege to set
  839. Priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  840. // Get the shutdown privilege for this process.
  841. Win32Check(AdjustTokenPrivileges(Token, FALSE, &Priv, 0, (PTOKEN_PRIVILEGES)NULL, 0));
  842. }
  843. //---------------------------------------------------------------------------
  844. void __fastcall ShutDownWindows()
  845. {
  846. AcquireShutDownPrivileges();
  847. // Shut down the system and force all applications to close.
  848. Win32Check(ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF,
  849. SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED));
  850. }
  851. //---------------------------------------------------------------------------
  852. void __fastcall SuspendWindows()
  853. {
  854. AcquireShutDownPrivileges();
  855. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa373201.aspx
  856. Win32Check(SetSuspendState(false, false, false));
  857. }
  858. //---------------------------------------------------------------------------
  859. void __fastcall EditSelectBaseName(HWND Edit)
  860. {
  861. UnicodeString Text;
  862. Text.SetLength(GetWindowTextLength(Edit) + 1);
  863. GetWindowText(Edit, Text.c_str(), Text.Length());
  864. int P = Text.LastDelimiter(L".");
  865. if (P > 0)
  866. {
  867. // SendMessage does not work, if edit control is not fully
  868. // initialized yet
  869. PostMessage(Edit, EM_SETSEL, 0, P - 1);
  870. }
  871. }
  872. //---------------------------------------------------------------------------
  873. static void __fastcall DoVerifyKey(
  874. UnicodeString FileName, bool TypeOnly, TSshProt SshProt)
  875. {
  876. if (!FileName.Trim().IsEmpty())
  877. {
  878. FileName = ExpandEnvironmentVariables(FileName);
  879. TKeyType Type = KeyType(FileName);
  880. // reason _wfopen failed
  881. int Error = errno;
  882. UnicodeString Message;
  883. UnicodeString HelpKeyword = HELP_LOGIN_KEY_TYPE;
  884. UnicodeString PuttygenPath;
  885. std::unique_ptr<TStrings> MoreMessages;
  886. bool TryPuttygen = false;
  887. switch (Type)
  888. {
  889. case ktOpenSSH:
  890. case ktSSHCom:
  891. {
  892. UnicodeString TypeName = (Type == ktOpenSSH) ? L"OpenSSH SSH-2" : L"ssh.com SSH-2";
  893. TryPuttygen = FindTool(PuttygenTool, PuttygenPath);
  894. Message = FMTLOAD(KEY_TYPE_UNSUPPORTED, (FileName, TypeName));
  895. if (TryPuttygen)
  896. {
  897. Message = FMTLOAD(KEY_TYPE_CONVERT2, (TypeName, RemoveMainInstructionsTag(Message)));
  898. }
  899. }
  900. HelpKeyword = HELP_KEY_TYPE_UNSUPPORTED;
  901. break;
  902. case ktSSH1:
  903. case ktSSH2:
  904. // on file select do not check for SSH version as user may
  905. // intend to change it only after he/she selects key file
  906. if (!TypeOnly)
  907. {
  908. if ((Type == ktSSH1) !=
  909. ((SshProt == ssh1only) || (SshProt == ssh1)))
  910. {
  911. Message =
  912. MainInstructions(
  913. FMTLOAD(KEY_TYPE_DIFFERENT_SSH,
  914. (FileName, (Type == ktSSH1 ? L"SSH-1" : L"PuTTY SSH-2"))));
  915. }
  916. }
  917. break;
  918. case ktUnopenable:
  919. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNOPENABLE, (FileName)));
  920. if (Error != ERROR_SUCCESS)
  921. {
  922. MoreMessages.reset(TextToStringList(SysErrorMessageForError(Error)));
  923. }
  924. break;
  925. default:
  926. FAIL;
  927. // fallthru
  928. case ktUnknown:
  929. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNKNOWN2, (FileName)));
  930. break;
  931. }
  932. if (!Message.IsEmpty())
  933. {
  934. if (TryPuttygen)
  935. {
  936. Configuration->Usage->Inc(L"PrivateKeyConvertSuggestions");
  937. if (MoreMessageDialog(Message, MoreMessages.get(), qtConfirmation, qaOK | qaCancel, HelpKeyword) == qaOK)
  938. {
  939. if (!ExecuteShell(PuttygenPath, AddPathQuotes(FileName)))
  940. {
  941. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (PuttygenPath)));
  942. }
  943. }
  944. Abort();
  945. }
  946. else
  947. {
  948. Configuration->Usage->Inc(L"PrivateKeySelectErrors");
  949. if (MoreMessageDialog(Message, MoreMessages.get(), qtWarning, qaIgnore | qaAbort,
  950. HelpKeyword) == qaAbort)
  951. {
  952. Abort();
  953. }
  954. }
  955. }
  956. }
  957. }
  958. //---------------------------------------------------------------------------
  959. void __fastcall VerifyKey(UnicodeString FileName)
  960. {
  961. DoVerifyKey(FileName, true, TSshProt(0));
  962. }
  963. //---------------------------------------------------------------------------
  964. void __fastcall VerifyKeyIncludingVersion(UnicodeString FileName, TSshProt SshProt)
  965. {
  966. DoVerifyKey(FileName, false, SshProt);
  967. }
  968. //---------------------------------------------------------------------------
  969. bool __fastcall DetectSystemExternalEditor(
  970. bool AllowDefaultEditor,
  971. UnicodeString & Executable, UnicodeString & ExecutableDescription,
  972. UnicodeString & UsageState, bool & TryNextTime)
  973. {
  974. bool Result = false;
  975. UnicodeString TempName = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir()) + L".txt";
  976. if (FileExists(::ApiPath(TempName)))
  977. {
  978. TryNextTime = true;
  979. UsageState = "F";
  980. }
  981. else
  982. {
  983. unsigned int File = FileCreate(::ApiPath(TempName));
  984. if (File == (unsigned int)INVALID_HANDLE_VALUE)
  985. {
  986. TryNextTime = true;
  987. UsageState = "F";
  988. }
  989. else
  990. {
  991. FileClose(File);
  992. try
  993. {
  994. wchar_t ExecutableBuf[MAX_PATH];
  995. if (!SUCCEEDED(FindExecutable(TempName.c_str(), NULL, ExecutableBuf)))
  996. {
  997. UsageState = "N";
  998. }
  999. else
  1000. {
  1001. Executable = ExecutableBuf;
  1002. if (Executable.IsEmpty() ||
  1003. !FileExists(::ApiPath(Executable)))
  1004. {
  1005. UsageState = "N";
  1006. }
  1007. else
  1008. {
  1009. UnicodeString ExecutableName = ExtractFileName(Executable);
  1010. if (!AllowDefaultEditor &&
  1011. SameText(ExecutableName, TEditorPreferences::GetDefaultExternalEditor()))
  1012. {
  1013. UsageState = "P";
  1014. Executable = L"";
  1015. }
  1016. else if (SameText(ExecutableName, "openwith.exe"))
  1017. {
  1018. UsageState = "W";
  1019. Executable = L"";
  1020. }
  1021. else
  1022. {
  1023. try
  1024. {
  1025. ExecutableDescription = Configuration->GetFileDescription(Executable);
  1026. }
  1027. catch(...)
  1028. {
  1029. }
  1030. if (ExecutableDescription.IsEmpty())
  1031. {
  1032. ExecutableDescription = ExecutableName;
  1033. }
  1034. Result = true;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. __finally
  1040. {
  1041. DeleteFile(::ApiPath(TempName));
  1042. }
  1043. }
  1044. }
  1045. return Result;
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. // Code from http://gentoo.osuosl.org/distfiles/cl331.zip/io/
  1049. //---------------------------------------------------------------------------
  1050. // this was moved to global scope in past in some attempt to fix crashes,
  1051. // not sure it really helped
  1052. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG IEProxyInfo;
  1053. //---------------------------------------------------------------------------
  1054. static bool __fastcall GetProxyUrlFromIE(UnicodeString & Proxy)
  1055. {
  1056. bool Result = false;
  1057. memset(&IEProxyInfo, 0, sizeof(IEProxyInfo));
  1058. if (WinHttpGetIEProxyConfigForCurrentUser(&IEProxyInfo))
  1059. {
  1060. if (IEProxyInfo.lpszProxy != NULL)
  1061. {
  1062. UnicodeString IEProxy = IEProxyInfo.lpszProxy;
  1063. Proxy = L"";
  1064. while (Proxy.IsEmpty() && !IEProxy.IsEmpty())
  1065. {
  1066. UnicodeString Str = ::CutToChar(IEProxy, L';', true);
  1067. if (Str.Pos(L"=") == 0)
  1068. {
  1069. Proxy = Str;
  1070. }
  1071. else
  1072. {
  1073. UnicodeString Protocol = ::CutToChar(Str, L'=', true);
  1074. if (SameText(Protocol, L"http"))
  1075. {
  1076. Proxy = Str;
  1077. }
  1078. }
  1079. }
  1080. GlobalFree(IEProxyInfo.lpszProxy);
  1081. Result = true;
  1082. }
  1083. if (IEProxyInfo.lpszAutoConfigUrl != NULL)
  1084. {
  1085. GlobalFree(IEProxyInfo.lpszAutoConfigUrl);
  1086. }
  1087. if (IEProxyInfo.lpszProxyBypass != NULL)
  1088. {
  1089. GlobalFree(IEProxyInfo.lpszProxyBypass);
  1090. }
  1091. }
  1092. return Result;
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. bool __fastcall AutodetectProxyUrl(UnicodeString & Proxy)
  1096. {
  1097. bool Result = false;
  1098. /* First we try for proxy info direct from the registry if
  1099. it's available. */
  1100. WINHTTP_PROXY_INFO ProxyInfo;
  1101. memset(&ProxyInfo, 0, sizeof(ProxyInfo));
  1102. if (WinHttpGetDefaultProxyConfiguration(&ProxyInfo))
  1103. {
  1104. if (ProxyInfo.lpszProxy != NULL)
  1105. {
  1106. Proxy = ProxyInfo.lpszProxy;
  1107. GlobalFree(ProxyInfo.lpszProxy);
  1108. Result = true;
  1109. }
  1110. if (ProxyInfo.lpszProxyBypass != NULL)
  1111. {
  1112. GlobalFree(ProxyInfo.lpszProxyBypass);
  1113. }
  1114. }
  1115. /* The next fallback is to get the proxy info from MSIE. This is also
  1116. usually much quicker than WinHttpGetProxyForUrl(), although sometimes
  1117. it seems to fall back to that, based on the longish delay involved.
  1118. Another issue with this is that it won't work in a service process
  1119. that isn't impersonating an interactive user (since there isn't a
  1120. current user), but in that case we just fall back to
  1121. WinHttpGetProxyForUrl() */
  1122. if (!Result)
  1123. {
  1124. Result = GetProxyUrlFromIE(Proxy);
  1125. }
  1126. // We can also use WinHttpGetProxyForUrl, but it is lengthy
  1127. // See the source address of the code for example
  1128. return Result;
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. //---------------------------------------------------------------------------
  1132. class TWinHelpTester : public TInterfacedObject, public IWinHelpTester
  1133. {
  1134. public:
  1135. virtual bool __fastcall CanShowALink(const UnicodeString ALink, const UnicodeString FileName);
  1136. virtual bool __fastcall CanShowTopic(const UnicodeString Topic, const UnicodeString FileName);
  1137. virtual bool __fastcall CanShowContext(const int Context, const UnicodeString FileName);
  1138. virtual TStringList * __fastcall GetHelpStrings(const UnicodeString ALink);
  1139. virtual UnicodeString __fastcall GetHelpPath();
  1140. virtual UnicodeString __fastcall GetDefaultHelpFile();
  1141. IUNKNOWN
  1142. };
  1143. //---------------------------------------------------------------------------
  1144. class TCustomHelpSelector : public TInterfacedObject, public IHelpSelector
  1145. {
  1146. public:
  1147. __fastcall TCustomHelpSelector(const UnicodeString & Name);
  1148. virtual int __fastcall SelectKeyword(TStrings * Keywords);
  1149. virtual int __fastcall TableOfContents(TStrings * Contents);
  1150. IUNKNOWN
  1151. private:
  1152. UnicodeString FName;
  1153. };
  1154. //---------------------------------------------------------------------------
  1155. void __fastcall AssignHelpSelector(IHelpSelector * HelpSelector)
  1156. {
  1157. _di_IHelpSystem HelpSystem;
  1158. if (GetHelpSystem(HelpSystem))
  1159. {
  1160. HelpSystem->AssignHelpSelector(HelpSelector);
  1161. }
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall InitializeCustomHelp(ICustomHelpViewer * HelpViewer)
  1165. {
  1166. _di_IHelpManager HelpManager;
  1167. RegisterViewer(HelpViewer, HelpManager);
  1168. // Register dummy tester that disables win help
  1169. WinHelpTester = new TWinHelpTester();
  1170. AssignHelpSelector(new TCustomHelpSelector(HelpViewer->GetViewerName()));
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall FinalizeCustomHelp()
  1174. {
  1175. AssignHelpSelector(NULL);
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. //---------------------------------------------------------------------------
  1179. bool __fastcall TWinHelpTester::CanShowALink(const UnicodeString ALink,
  1180. const UnicodeString FileName)
  1181. {
  1182. return !Application->HelpFile.IsEmpty();
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. bool __fastcall TWinHelpTester::CanShowTopic(const UnicodeString Topic,
  1186. const UnicodeString FileName)
  1187. {
  1188. FAIL;
  1189. return !Application->HelpFile.IsEmpty();
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. bool __fastcall TWinHelpTester::CanShowContext(const int /*Context*/,
  1193. const UnicodeString FileName)
  1194. {
  1195. FAIL;
  1196. return !Application->HelpFile.IsEmpty();
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. TStringList * __fastcall TWinHelpTester::GetHelpStrings(const UnicodeString ALink)
  1200. {
  1201. FAIL;
  1202. TStringList * Result = new TStringList();
  1203. Result->Add(ViewerName + L": " + ALink);
  1204. return Result;
  1205. }
  1206. //---------------------------------------------------------------------------
  1207. UnicodeString __fastcall TWinHelpTester::GetHelpPath()
  1208. {
  1209. // never called on windows anyway
  1210. return ExtractFilePath(Application->HelpFile);
  1211. }
  1212. //---------------------------------------------------------------------------
  1213. UnicodeString __fastcall TWinHelpTester::GetDefaultHelpFile()
  1214. {
  1215. return Application->HelpFile;
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. //---------------------------------------------------------------------------
  1219. __fastcall TCustomHelpSelector::TCustomHelpSelector(const UnicodeString & Name) :
  1220. FName(Name)
  1221. {
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. int __fastcall TCustomHelpSelector::SelectKeyword(TStrings * /*Keywords*/)
  1225. {
  1226. FAIL;
  1227. return 0;
  1228. }
  1229. //---------------------------------------------------------------------------
  1230. int __fastcall TCustomHelpSelector::TableOfContents(TStrings * Contents)
  1231. {
  1232. return Contents->IndexOf(FName);
  1233. }