Tools.cpp 31 KB

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