1
0

WinInterface.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlwapi.h>
  5. #include <Common.h>
  6. #include <Exceptions.h>
  7. #include <CoreMain.h>
  8. #include <TextsCore.h>
  9. #include <TextsWin.h>
  10. #include <HelpWin.h>
  11. #include <HelpCore.h>
  12. #include <Interface.h>
  13. #include <VCLCommon.h>
  14. #include <Glyphs.h>
  15. #include <PasTools.hpp>
  16. #include <DateUtils.hpp>
  17. #include "WinInterface.h"
  18. #include "GUITools.h"
  19. #include "JclDebug.hpp"
  20. #include "JclHookExcept.hpp"
  21. #include <StrUtils.hpp>
  22. #include <WinApi.h>
  23. #include "Tools.h"
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. #define WM_TRAY_ICON (WM_WINSCP_USER + 5)
  28. //---------------------------------------------------------------------
  29. TNotifyEvent GlobalOnMinimize = NULL;
  30. //---------------------------------------------------------------------
  31. const IID IID_IListView_Win7 = {0xE5B16AF2, 0x3990, 0x4681, {0xA6, 0x09, 0x1F, 0x06, 0x0C, 0xD1, 0x42, 0x69}};
  32. //---------------------------------------------------------------------
  33. void __fastcall FormHelp(TCustomForm * Form)
  34. {
  35. InvokeHelp(Form->ActiveControl != NULL ? Form->ActiveControl : Form);
  36. }
  37. //---------------------------------------------------------------------------
  38. TMessageParams::TMessageParams(unsigned int AParams)
  39. {
  40. Reset();
  41. Params = AParams;
  42. }
  43. //---------------------------------------------------------------------------
  44. TMessageParams::TMessageParams(const TQueryParams * AParams)
  45. {
  46. Reset();
  47. if (AParams != NULL)
  48. {
  49. Aliases = AParams->Aliases;
  50. AliasesCount = AParams->AliasesCount;
  51. Timer = AParams->Timer;
  52. TimerEvent = AParams->TimerEvent;
  53. TimerMessage = AParams->TimerMessage;
  54. TimerAnswers = AParams->TimerAnswers;
  55. TimerQueryType = AParams->TimerQueryType;
  56. Timeout = AParams->Timeout;
  57. TimeoutAnswer = AParams->TimeoutAnswer;
  58. if (FLAGSET(AParams->Params, qpNeverAskAgainCheck))
  59. {
  60. Params |= mpNeverAskAgainCheck;
  61. }
  62. if (FLAGSET(AParams->Params, qpAllowContinueOnError))
  63. {
  64. Params |= mpAllowContinueOnError;
  65. }
  66. }
  67. }
  68. //---------------------------------------------------------------------------
  69. inline void TMessageParams::Reset()
  70. {
  71. Params = 0;
  72. Aliases = NULL;
  73. AliasesCount = 0;
  74. Timer = 0;
  75. TimerEvent = NULL;
  76. TimerMessage = L"";
  77. TimerAnswers = 0;
  78. TimerQueryType = static_cast<TQueryType>(-1);
  79. Timeout = 0;
  80. TimeoutAnswer = 0;
  81. NeverAskAgainTitle = L"";
  82. NeverAskAgainAnswer = 0;
  83. NeverAskAgainCheckedInitially = false;
  84. AllowHelp = true;
  85. ImageName = L"";
  86. MoreMessagesUrl = L"";
  87. MoreMessagesSize = TSize();
  88. CustomCaption = L"";
  89. }
  90. //---------------------------------------------------------------------------
  91. static bool __fastcall IsPositiveAnswer(unsigned int Answer)
  92. {
  93. return (Answer == qaYes) || (Answer == qaOK) || (Answer == qaYesToAll);
  94. }
  95. //---------------------------------------------------------------------------
  96. static void __fastcall NeverAskAgainCheckClick(void * /*Data*/, TObject * Sender)
  97. {
  98. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(Sender);
  99. DebugAssert(CheckBox != NULL);
  100. TForm * Dialog = dynamic_cast<TForm *>(CheckBox->Owner);
  101. DebugAssert(Dialog != NULL);
  102. unsigned int PositiveAnswer = 0;
  103. if (CheckBox->Checked)
  104. {
  105. if (CheckBox->Tag > 0)
  106. {
  107. PositiveAnswer = CheckBox->Tag;
  108. }
  109. else
  110. {
  111. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  112. {
  113. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  114. if (Button != NULL)
  115. {
  116. if (IsPositiveAnswer(Button->ModalResult))
  117. {
  118. PositiveAnswer = Button->ModalResult;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. DebugAssert(PositiveAnswer != 0);
  125. }
  126. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  127. {
  128. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  129. if (Button != NULL)
  130. {
  131. if ((Button->ModalResult != 0) && (Button->ModalResult != static_cast<int>(qaCancel)))
  132. {
  133. Button->Enabled = !CheckBox->Checked || (Button->ModalResult == static_cast<int>(PositiveAnswer));
  134. }
  135. if (Button->DropDownMenu != NULL)
  136. {
  137. for (int iii = 0; iii < Button->DropDownMenu->Items->Count; iii++)
  138. {
  139. TMenuItem * Item = Button->DropDownMenu->Items->Items[iii];
  140. Item->Enabled = Item->Default || !CheckBox->Checked;
  141. }
  142. }
  143. }
  144. }
  145. }
  146. //---------------------------------------------------------------------------
  147. static TCheckBox * __fastcall FindNeverAskAgainCheck(TForm * Dialog)
  148. {
  149. return DebugNotNull(dynamic_cast<TCheckBox *>(Dialog->FindComponent(L"NeverAskAgainCheck")));
  150. }
  151. //---------------------------------------------------------------------------
  152. TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg,
  153. TStrings * MoreMessages, TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword,
  154. const TMessageParams * Params, TButton *& TimeoutButton)
  155. {
  156. TMsgDlgType DlgType;
  157. switch (Type) {
  158. case qtConfirmation: DlgType = mtConfirmation; break;
  159. case qtInformation: DlgType = mtInformation; break;
  160. case qtError: DlgType = mtError; break;
  161. case qtWarning: DlgType = mtWarning; break;
  162. default: DebugFail();
  163. }
  164. unsigned int TimeoutAnswer = (Params != NULL) ? Params->TimeoutAnswer : 0;
  165. unsigned int ActualAnswers = Answers;
  166. if ((Params == NULL) || Params->AllowHelp)
  167. {
  168. Answers = Answers | qaHelp;
  169. }
  170. if (IsInternalErrorHelpKeyword(HelpKeyword))
  171. {
  172. Answers = Answers | qaReport;
  173. }
  174. if ((MoreMessages != NULL) && (MoreMessages->Count == 0))
  175. {
  176. MoreMessages = NULL;
  177. }
  178. UnicodeString ImageName;
  179. UnicodeString MoreMessagesUrl;
  180. TSize MoreMessagesSize;
  181. UnicodeString CustomCaption;
  182. if (Params != NULL)
  183. {
  184. ImageName = Params->ImageName;
  185. MoreMessagesUrl = Params->MoreMessagesUrl;
  186. MoreMessagesSize = Params->MoreMessagesSize;
  187. CustomCaption = Params->CustomCaption;
  188. }
  189. const TQueryButtonAlias * Aliases = (Params != NULL) ? Params->Aliases : NULL;
  190. unsigned int AliasesCount = (Params != NULL) ? Params->AliasesCount : 0;
  191. UnicodeString NeverAskAgainCaption;
  192. bool HasNeverAskAgain = (Params != NULL) && FLAGSET(Params->Params, mpNeverAskAgainCheck);
  193. if (HasNeverAskAgain)
  194. {
  195. NeverAskAgainCaption =
  196. !Params->NeverAskAgainTitle.IsEmpty() ?
  197. (UnicodeString)Params->NeverAskAgainTitle :
  198. // qaOK | qaIgnore is used, when custom "non-answer" button is required
  199. LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ?
  200. NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN);
  201. }
  202. TForm * Dialog = CreateMoreMessageDialog(Msg, MoreMessages, DlgType, Answers,
  203. Aliases, AliasesCount, TimeoutAnswer, &TimeoutButton, ImageName, NeverAskAgainCaption,
  204. MoreMessagesUrl, MoreMessagesSize, CustomCaption);
  205. try
  206. {
  207. if (HasNeverAskAgain && DebugAlwaysTrue(Params != NULL))
  208. {
  209. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  210. NeverAskAgainCheck->Checked = Params->NeverAskAgainCheckedInitially;
  211. if (Params->NeverAskAgainAnswer > 0)
  212. {
  213. NeverAskAgainCheck->Tag = Params->NeverAskAgainAnswer;
  214. }
  215. TNotifyEvent OnClick;
  216. ((TMethod*)&OnClick)->Code = NeverAskAgainCheckClick;
  217. NeverAskAgainCheck->OnClick = OnClick;
  218. }
  219. Dialog->HelpKeyword = HelpKeyword;
  220. if (FLAGSET(Answers, qaHelp))
  221. {
  222. Dialog->BorderIcons = Dialog->BorderIcons << biHelp;
  223. }
  224. ResetSystemSettings(Dialog);
  225. }
  226. catch(...)
  227. {
  228. delete Dialog;
  229. throw;
  230. }
  231. return Dialog;
  232. }
  233. //---------------------------------------------------------------------------
  234. unsigned int __fastcall ExecuteMessageDialog(TForm * Dialog, unsigned int Answers, const TMessageParams * Params)
  235. {
  236. FlashOnBackground();
  237. unsigned int Answer = Dialog->ShowModal();
  238. // mrCancel is returned always when X button is pressed, despite
  239. // no Cancel button was on the dialog. Find valid "cancel" answer.
  240. // mrNone is retuned when Windows session is closing (log off)
  241. if ((Answer == mrCancel) || (Answer == mrNone))
  242. {
  243. Answer = CancelAnswer(Answers);
  244. }
  245. if ((Params != NULL) && (Params->Params & mpNeverAskAgainCheck))
  246. {
  247. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  248. if (NeverAskAgainCheck->Checked)
  249. {
  250. bool PositiveAnswer =
  251. (Params->NeverAskAgainAnswer > 0) ?
  252. (Answer == Params->NeverAskAgainAnswer) :
  253. IsPositiveAnswer(Answer);
  254. if (PositiveAnswer)
  255. {
  256. Answer = qaNeverAskAgain;
  257. }
  258. }
  259. }
  260. return Answer;
  261. }
  262. //---------------------------------------------------------------------------
  263. class TMessageTimer : public TTimer
  264. {
  265. public:
  266. TQueryParamsTimerEvent Event;
  267. TForm * Dialog;
  268. __fastcall TMessageTimer(TComponent * AOwner);
  269. protected:
  270. void __fastcall DoTimer(TObject * Sender);
  271. };
  272. //---------------------------------------------------------------------------
  273. __fastcall TMessageTimer::TMessageTimer(TComponent * AOwner) : TTimer(AOwner)
  274. {
  275. Event = NULL;
  276. OnTimer = DoTimer;
  277. Dialog = NULL;
  278. }
  279. //---------------------------------------------------------------------------
  280. void __fastcall TMessageTimer::DoTimer(TObject * /*Sender*/)
  281. {
  282. if (Event != NULL)
  283. {
  284. unsigned int Result = 0;
  285. Event(Result);
  286. if (Result != 0)
  287. {
  288. Dialog->ModalResult = Result;
  289. }
  290. }
  291. }
  292. //---------------------------------------------------------------------------
  293. class TMessageTimeout : public TTimer
  294. {
  295. public:
  296. __fastcall TMessageTimeout(TComponent * AOwner, unsigned int Timeout,
  297. TButton * Button);
  298. void __fastcall MouseMove();
  299. void __fastcall Cancel();
  300. protected:
  301. unsigned int FOrigTimeout;
  302. unsigned int FTimeout;
  303. TButton * FButton;
  304. UnicodeString FOrigCaption;
  305. TPoint FOrigCursorPos;
  306. void __fastcall DoTimer(TObject * Sender);
  307. void __fastcall UpdateButton();
  308. };
  309. //---------------------------------------------------------------------------
  310. __fastcall TMessageTimeout::TMessageTimeout(TComponent * AOwner,
  311. unsigned int Timeout, TButton * Button) :
  312. TTimer(AOwner), FOrigTimeout(Timeout), FTimeout(Timeout), FButton(Button)
  313. {
  314. OnTimer = DoTimer;
  315. Interval = MSecsPerSec;
  316. FOrigCaption = FButton->Caption;
  317. FOrigCursorPos = Mouse->CursorPos;
  318. UpdateButton();
  319. }
  320. //---------------------------------------------------------------------------
  321. void __fastcall TMessageTimeout::MouseMove()
  322. {
  323. TPoint CursorPos = Mouse->CursorPos;
  324. int Delta = std::max(std::abs(FOrigCursorPos.X - CursorPos.X), std::abs(FOrigCursorPos.Y - CursorPos.Y));
  325. int Threshold = 8;
  326. if (DebugAlwaysTrue(FButton != NULL))
  327. {
  328. Threshold = ScaleByTextHeight(FButton, Threshold);
  329. }
  330. if (Delta > Threshold)
  331. {
  332. FOrigCursorPos = CursorPos;
  333. const unsigned int SuspendTime = 30 * MSecsPerSec;
  334. FTimeout = std::max(FOrigTimeout, SuspendTime);
  335. UpdateButton();
  336. }
  337. }
  338. //---------------------------------------------------------------------------
  339. void __fastcall TMessageTimeout::Cancel()
  340. {
  341. Enabled = false;
  342. UpdateButton();
  343. }
  344. //---------------------------------------------------------------------------
  345. void __fastcall TMessageTimeout::UpdateButton()
  346. {
  347. DebugAssert(FButton != NULL);
  348. FButton->Caption =
  349. !Enabled ? FOrigCaption : FMTLOAD(TIMEOUT_BUTTON, (FOrigCaption, int(FTimeout / MSecsPerSec)));
  350. }
  351. //---------------------------------------------------------------------------
  352. void __fastcall TMessageTimeout::DoTimer(TObject * /*Sender*/)
  353. {
  354. if (FTimeout <= Interval)
  355. {
  356. DebugAssert(FButton != NULL);
  357. TForm * Dialog = dynamic_cast<TForm *>(FButton->Parent);
  358. DebugAssert(Dialog != NULL);
  359. Dialog->ModalResult = FButton->ModalResult;
  360. }
  361. else
  362. {
  363. FTimeout -= Interval;
  364. UpdateButton();
  365. }
  366. }
  367. //---------------------------------------------------------------------
  368. class TPublicControl : public TControl
  369. {
  370. friend void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled);
  371. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  372. };
  373. //---------------------------------------------------------------------
  374. class TPublicWinControl : public TWinControl
  375. {
  376. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  377. };
  378. //---------------------------------------------------------------------------
  379. static void __fastcall MessageDialogMouseMove(void * Data, TObject * /*Sender*/,
  380. TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  381. {
  382. DebugAssert(Data != NULL);
  383. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  384. Timeout->MouseMove();
  385. }
  386. //---------------------------------------------------------------------------
  387. static void __fastcall MessageDialogMouseDown(void * Data, TObject * /*Sender*/,
  388. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  389. {
  390. DebugAssert(Data != NULL);
  391. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  392. Timeout->Cancel();
  393. }
  394. //---------------------------------------------------------------------------
  395. static void __fastcall MessageDialogKeyDownUp(void * Data, TObject * /*Sender*/,
  396. Word & /*Key*/, TShiftState /*Shift*/)
  397. {
  398. DebugAssert(Data != NULL);
  399. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  400. Timeout->Cancel();
  401. }
  402. //---------------------------------------------------------------------------
  403. void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout)
  404. {
  405. TPublicControl * PublicControl = reinterpret_cast<TPublicControl *>(Control);
  406. DebugAssert(PublicControl->OnMouseMove == NULL);
  407. PublicControl->OnMouseMove = MakeMethod<TMouseMoveEvent>(Timeout, MessageDialogMouseMove);
  408. DebugAssert(PublicControl->OnMouseDown == NULL);
  409. PublicControl->OnMouseDown = MakeMethod<TMouseEvent>(Timeout, MessageDialogMouseDown);
  410. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  411. if (WinControl != NULL)
  412. {
  413. TPublicWinControl * PublicWinControl = reinterpret_cast<TPublicWinControl *>(Control);
  414. DebugAssert(PublicWinControl->OnKeyDown == NULL);
  415. PublicWinControl->OnKeyDown = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  416. DebugAssert(PublicWinControl->OnKeyUp == NULL);
  417. PublicWinControl->OnKeyUp = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  418. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  419. {
  420. SetTimeoutEvents(WinControl->Controls[Index], Timeout);
  421. }
  422. }
  423. }
  424. //---------------------------------------------------------------------------
  425. // Merge with CreateMessageDialogEx
  426. TForm * __fastcall CreateMoreMessageDialogEx(const UnicodeString Message, TStrings * MoreMessages,
  427. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  428. {
  429. std::unique_ptr<TForm> Dialog;
  430. UnicodeString AMessage = Message;
  431. TMessageTimer * Timer = NULL;
  432. if ((Params != NULL) && (Params->Timer > 0))
  433. {
  434. Timer = new TMessageTimer(Application);
  435. Timer->Interval = Params->Timer;
  436. Timer->Event = Params->TimerEvent;
  437. if (Params->TimerAnswers > 0)
  438. {
  439. Answers = Params->TimerAnswers;
  440. }
  441. if (Params->TimerQueryType >= 0)
  442. {
  443. Type = Params->TimerQueryType;
  444. }
  445. if (!Params->TimerMessage.IsEmpty())
  446. {
  447. AMessage = Params->TimerMessage;
  448. }
  449. Timer->Name = L"MessageTimer";
  450. }
  451. TButton * TimeoutButton = NULL;
  452. Dialog.reset(
  453. CreateMessageDialogEx(
  454. AMessage, MoreMessages, Type, Answers, HelpKeyword, Params, TimeoutButton));
  455. if (Timer != NULL)
  456. {
  457. Timer->Dialog = Dialog.get();
  458. Dialog->InsertComponent(Timer);
  459. }
  460. if (Params != NULL)
  461. {
  462. if (Params->Timeout > 0)
  463. {
  464. TMessageTimeout * Timeout = new TMessageTimeout(Application, Params->Timeout, TimeoutButton);
  465. SetTimeoutEvents(Dialog.get(), Timeout);
  466. Timeout->Name = L"MessageTimeout";
  467. Dialog->InsertComponent(Timeout);
  468. }
  469. }
  470. return Dialog.release();
  471. }
  472. //---------------------------------------------------------------------------
  473. unsigned int __fastcall MoreMessageDialog(const UnicodeString Message, TStrings * MoreMessages,
  474. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  475. {
  476. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, MoreMessages, Type, Answers, HelpKeyword, Params));
  477. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, Params);
  478. return Result;
  479. }
  480. //---------------------------------------------------------------------------
  481. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  482. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  483. {
  484. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  485. }
  486. //---------------------------------------------------------------------------
  487. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  488. {
  489. unsigned int Result;
  490. TStrings * More = NULL;
  491. try
  492. {
  493. if (!MoreMessages.IsEmpty())
  494. {
  495. More = TextToStringList(MoreMessages);
  496. }
  497. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  498. }
  499. __finally
  500. {
  501. delete More;
  502. }
  503. return Result;
  504. }
  505. //---------------------------------------------------------------------------
  506. static TStrings * __fastcall StackInfoListToStrings(
  507. TJclStackInfoList * StackInfoList)
  508. {
  509. std::unique_ptr<TStrings> StackTrace(new TStringList());
  510. StackInfoList->AddToStrings(StackTrace.get(), true, false, true, true);
  511. for (int Index = 0; Index < StackTrace->Count; Index++)
  512. {
  513. UnicodeString Frame = StackTrace->Strings[Index];
  514. // get rid of declarations "flags" that are included in .map
  515. Frame = ReplaceStr(Frame, L"__fastcall ", L"");
  516. Frame = ReplaceStr(Frame, L"__linkproc__ ", L"");
  517. if (DebugAlwaysTrue(!Frame.IsEmpty() && (Frame[1] == L'(')))
  518. {
  519. int Start = Frame.Pos(L"[");
  520. int End = Frame.Pos(L"]");
  521. if (DebugAlwaysTrue((Start > 1) && (End > Start) && (Frame[Start - 1] == L' ')))
  522. {
  523. // remove absolute address
  524. Frame.Delete(Start - 1, End - Start + 2);
  525. }
  526. }
  527. StackTrace->Strings[Index] = Frame;
  528. }
  529. return StackTrace.release();
  530. }
  531. //---------------------------------------------------------------------------
  532. static std::unique_ptr<TCriticalSection> StackTraceCriticalSection(new TCriticalSection());
  533. typedef std::map<DWORD, TStrings *> TStackTraceMap;
  534. static TStackTraceMap StackTraceMap;
  535. //---------------------------------------------------------------------------
  536. bool __fastcall AppendExceptionStackTraceAndForget(TStrings *& MoreMessages)
  537. {
  538. bool Result = false;
  539. TGuard Guard(StackTraceCriticalSection.get());
  540. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  541. if (Iterator != StackTraceMap.end())
  542. {
  543. std::unique_ptr<TStrings> OwnedMoreMessages;
  544. if (MoreMessages == NULL)
  545. {
  546. OwnedMoreMessages.reset(new TStringList());
  547. MoreMessages = OwnedMoreMessages.get();
  548. Result = true;
  549. }
  550. if (!MoreMessages->Text.IsEmpty())
  551. {
  552. MoreMessages->Text = MoreMessages->Text + "\n";
  553. }
  554. MoreMessages->Text = MoreMessages->Text + LoadStr(STACK_TRACE) + "\n";
  555. MoreMessages->AddStrings(Iterator->second);
  556. delete Iterator->second;
  557. StackTraceMap.erase(Iterator);
  558. OwnedMoreMessages.release();
  559. }
  560. return Result;
  561. }
  562. //---------------------------------------------------------------------------
  563. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  564. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  565. const TMessageParams * Params)
  566. {
  567. TStrings * MoreMessages = NULL;
  568. ExtException * EE = dynamic_cast<ExtException *>(E);
  569. if (EE != NULL)
  570. {
  571. MoreMessages = EE->MoreMessages;
  572. }
  573. UnicodeString Message;
  574. // this is always called from within ExceptionMessage check,
  575. // so it should never fail here
  576. DebugCheck(ExceptionMessageFormatted(E, Message));
  577. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  578. std::unique_ptr<TStrings> OwnedMoreMessages;
  579. if (AppendExceptionStackTraceAndForget(MoreMessages))
  580. {
  581. OwnedMoreMessages.reset(MoreMessages);
  582. }
  583. return MoreMessageDialog(
  584. FORMAT(MessageFormat.IsEmpty() ? UnicodeString(L"%s") : MessageFormat, (Message)),
  585. MoreMessages, Type, Answers, HelpKeyword, Params);
  586. }
  587. //---------------------------------------------------------------------------
  588. unsigned int __fastcall FatalExceptionMessageDialog(Exception * E, TQueryType Type,
  589. int SessionReopenTimeout, const UnicodeString MessageFormat, unsigned int Answers,
  590. UnicodeString HelpKeyword, const TMessageParams * Params)
  591. {
  592. DebugAssert(FLAGCLEAR(Answers, qaRetry));
  593. Answers |= qaRetry;
  594. TQueryButtonAlias Aliases[1];
  595. Aliases[0].Button = qaRetry;
  596. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  597. TMessageParams AParams;
  598. if (Params != NULL)
  599. {
  600. AParams = *Params;
  601. }
  602. DebugAssert(AParams.Timeout == 0);
  603. // the condition is de facto excess
  604. if (SessionReopenTimeout > 0)
  605. {
  606. AParams.Timeout = SessionReopenTimeout;
  607. AParams.TimeoutAnswer = qaRetry;
  608. }
  609. DebugAssert(AParams.Aliases == NULL);
  610. AParams.Aliases = Aliases;
  611. AParams.AliasesCount = LENOF(Aliases);
  612. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  613. }
  614. //---------------------------------------------------------------------------
  615. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  616. bool OSException, void * BaseOfStack)
  617. {
  618. if (ExceptObj != NULL)
  619. {
  620. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  621. if ((E != NULL) && IsInternalException(E)) // optimization
  622. {
  623. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  624. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  625. if (DebugAlwaysTrue(StackInfoList != NULL))
  626. {
  627. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  628. DWORD ThreadID = GetCurrentThreadId();
  629. TGuard Guard(StackTraceCriticalSection.get());
  630. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  631. if (Iterator != StackTraceMap.end())
  632. {
  633. Iterator->second->Add(L"");
  634. Iterator->second->AddStrings(StackTrace.get());
  635. }
  636. else
  637. {
  638. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  639. }
  640. // this chains so that JclLastExceptStackList() returns NULL the next time
  641. // for the current thread
  642. delete StackInfoList;
  643. }
  644. }
  645. }
  646. }
  647. //---------------------------------------------------------------------------
  648. void * __fastcall BusyStart()
  649. {
  650. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  651. Screen->Cursor = crHourGlass;
  652. return Token;
  653. }
  654. //---------------------------------------------------------------------------
  655. void __fastcall BusyEnd(void * Token)
  656. {
  657. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  658. }
  659. //---------------------------------------------------------------------------
  660. //---------------------------------------------------------------------------
  661. static DWORD MainThread = 0;
  662. static TDateTime LastGUIUpdate = 0;
  663. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  664. static bool NoGUI = false;
  665. //---------------------------------------------------------------------------
  666. void __fastcall SetNoGUI()
  667. {
  668. NoGUI = true;
  669. }
  670. //---------------------------------------------------------------------------
  671. bool __fastcall ProcessGUI(bool Force)
  672. {
  673. DebugAssert(MainThread != 0);
  674. bool Result = false;
  675. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  676. // As we do not really need to call it in scripting/.NET, just skip it.
  677. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  678. {
  679. TDateTime N = Now();
  680. if (Force ||
  681. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  682. {
  683. LastGUIUpdate = N;
  684. Application->ProcessMessages();
  685. Result = true;
  686. }
  687. }
  688. return Result;
  689. }
  690. //---------------------------------------------------------------------------
  691. void __fastcall CopyParamListButton(TButton * Button)
  692. {
  693. if (!SupportsSplitButton())
  694. {
  695. MenuButton(Button);
  696. }
  697. }
  698. //---------------------------------------------------------------------------
  699. const int cpiDefault = -1;
  700. const int cpiConfigure = -2;
  701. const int cpiCustom = -3;
  702. const int cpiSaveSettings = -4;
  703. const int cpiGenerateCode = -5;
  704. //---------------------------------------------------------------------------
  705. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  706. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  707. int Options, int CopyParamAttrs, bool SaveSettings)
  708. {
  709. Menu->Items->Clear();
  710. TMenuItem * CustomizeItem = NULL;
  711. TMenuItem * Item;
  712. if (FLAGSET(Options, cplCustomize))
  713. {
  714. Item = new TMenuItem(Menu);
  715. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  716. Item->Tag = cpiCustom;
  717. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  718. Item->OnClick = OnClick;
  719. Menu->Items->Add(Item);
  720. CustomizeItem = Item;
  721. }
  722. if (FLAGSET(Options, cplSaveSettings))
  723. {
  724. Item = new TMenuItem(Menu);
  725. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  726. Item->Tag = cpiSaveSettings;
  727. Item->Checked = SaveSettings;
  728. Item->OnClick = OnClick;
  729. Menu->Items->Add(Item);
  730. }
  731. Item = new TMenuItem(Menu);
  732. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  733. Item->Visible = false;
  734. Item->Enabled = false;
  735. Menu->Items->Add(Item);
  736. bool AnyChecked = false;
  737. Item = new TMenuItem(Menu);
  738. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  739. Item->Tag = cpiDefault;
  740. Item->Checked =
  741. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  742. AnyChecked = AnyChecked || Item->Checked;
  743. Item->OnClick = OnClick;
  744. Menu->Items->Add(Item);
  745. TCopyParamType DefaultParam;
  746. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  747. for (int i = 0; i < CopyParamList->Count; i++)
  748. {
  749. UnicodeString Name = CopyParamList->Names[i];
  750. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  751. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  752. // This makes "Binary" preset visible,
  753. // as long as we care about transfer mode
  754. ((AParam == DefaultParam) &&
  755. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  756. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  757. {
  758. Item = new TMenuItem(Menu);
  759. Item->Caption = Name;
  760. Item->Tag = i;
  761. Item->Checked =
  762. (Preset == Name) && (AParam == Param);
  763. AnyChecked = AnyChecked || Item->Checked;
  764. Item->OnClick = OnClick;
  765. Menu->Items->Add(Item);
  766. }
  767. }
  768. if (CustomizeItem != NULL)
  769. {
  770. CustomizeItem->Checked = !AnyChecked;
  771. }
  772. Item = new TMenuItem(Menu);
  773. Item->Caption = L"-";
  774. Menu->Items->Add(Item);
  775. Item = new TMenuItem(Menu);
  776. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  777. Item->Tag = cpiConfigure;
  778. Item->OnClick = OnClick;
  779. Menu->Items->Add(Item);
  780. if (FLAGSET(Options, cplGenerateCode))
  781. {
  782. Item = new TMenuItem(Menu);
  783. Item->Caption = L"-";
  784. Menu->Items->Add(Item);
  785. Item = new TMenuItem(Menu);
  786. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  787. Item->Tag = cpiGenerateCode;
  788. Item->OnClick = OnClick;
  789. Menu->Items->Add(Item);
  790. }
  791. MenuPopup(Menu, Rect, NULL);
  792. }
  793. //---------------------------------------------------------------------------
  794. int __fastcall CopyParamListPopupClick(TObject * Sender,
  795. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  796. bool * SaveSettings)
  797. {
  798. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  799. DebugAssert(Item != NULL);
  800. DebugAssert((Item->Tag >= cpiGenerateCode) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  801. int Result;
  802. if (Item->Tag == cpiConfigure)
  803. {
  804. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  805. DoPreferencesDialog(pmPresets);
  806. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  807. if (Result > 0)
  808. {
  809. // For cast, see a comment below
  810. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  811. }
  812. }
  813. else if (Item->Tag == cpiCustom)
  814. {
  815. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  816. }
  817. else if (Item->Tag == cpiSaveSettings)
  818. {
  819. if (DebugAlwaysTrue(SaveSettings != NULL))
  820. {
  821. *SaveSettings = !*SaveSettings;
  822. }
  823. Result = 0;
  824. }
  825. else if (Item->Tag == cpiGenerateCode)
  826. {
  827. Result = -cplGenerateCode;
  828. }
  829. else
  830. {
  831. Preset = (Item->Tag >= 0) ?
  832. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  833. // The cast strips away the "queue" properties of the TGUICopyParamType
  834. // that are not configurable in presets
  835. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  836. Result = 1;
  837. }
  838. return Result;
  839. }
  840. //---------------------------------------------------------------------------
  841. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  842. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  843. TInteractiveCustomCommand(ChildCustomCommand)
  844. {
  845. FCustomCommandName = StripHotkey(CustomCommandName);
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TWinInteractiveCustomCommand::Prompt(
  849. const UnicodeString & Prompt, UnicodeString & Value)
  850. {
  851. UnicodeString APrompt = Prompt;
  852. if (APrompt.IsEmpty())
  853. {
  854. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  855. }
  856. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"CustomCommandParam"]));
  857. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  858. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History.get()))
  859. {
  860. CustomWinConfiguration->History[L"CustomCommandParam"] = History.get();
  861. }
  862. else
  863. {
  864. Abort();
  865. }
  866. }
  867. //---------------------------------------------------------------------------
  868. void __fastcall TWinInteractiveCustomCommand::Execute(
  869. const UnicodeString & Command, UnicodeString & Value)
  870. {
  871. // inspired by
  872. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  873. HANDLE StdOutOutput;
  874. HANDLE StdOutInput;
  875. HANDLE StdInOutput;
  876. HANDLE StdInInput;
  877. SECURITY_ATTRIBUTES SecurityAttributes;
  878. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  879. SecurityAttributes.lpSecurityDescriptor = NULL;
  880. SecurityAttributes.bInheritHandle = TRUE;
  881. try
  882. {
  883. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  884. {
  885. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  886. }
  887. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  888. {
  889. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  890. }
  891. else
  892. {
  893. STARTUPINFO StartupInfo;
  894. PROCESS_INFORMATION ProcessInformation;
  895. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  896. StartupInfo.cb = sizeof(StartupInfo);
  897. StartupInfo.wShowWindow = SW_HIDE;
  898. StartupInfo.hStdInput = StdInOutput;
  899. StartupInfo.hStdOutput = StdOutInput;
  900. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  901. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  902. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  903. {
  904. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  905. }
  906. else
  907. {
  908. try
  909. {
  910. // wait until the console program terminated
  911. bool Running = true;
  912. while (Running)
  913. {
  914. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  915. {
  916. case WAIT_TIMEOUT:
  917. Application->ProcessMessages();
  918. break;
  919. case WAIT_OBJECT_0:
  920. Running = false;
  921. break;
  922. default:
  923. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  924. }
  925. }
  926. char Buffer[1024];
  927. unsigned long Read;
  928. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  929. (Read > 0))
  930. {
  931. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  932. {
  933. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  934. }
  935. else if (Read > 0)
  936. {
  937. Value += AnsiToString(Buffer, Read);
  938. }
  939. }
  940. // trim trailing cr/lf
  941. Value = TrimRight(Value);
  942. }
  943. __finally
  944. {
  945. CloseHandle(ProcessInformation.hProcess);
  946. CloseHandle(ProcessInformation.hThread);
  947. }
  948. }
  949. }
  950. }
  951. __finally
  952. {
  953. if (StdOutOutput != INVALID_HANDLE_VALUE)
  954. {
  955. CloseHandle(StdOutOutput);
  956. }
  957. if (StdOutInput != INVALID_HANDLE_VALUE)
  958. {
  959. CloseHandle(StdOutInput);
  960. }
  961. if (StdInOutput != INVALID_HANDLE_VALUE)
  962. {
  963. CloseHandle(StdInOutput);
  964. }
  965. if (StdInInput != INVALID_HANDLE_VALUE)
  966. {
  967. CloseHandle(StdInInput);
  968. }
  969. }
  970. }
  971. //---------------------------------------------------------------------------
  972. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  973. {
  974. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  978. {
  979. TControl * Control = dynamic_cast<TControl *>(Sender);
  980. DebugAssert(Control != NULL);
  981. TPoint Point;
  982. if ((MousePos.x == -1) && (MousePos.y == -1))
  983. {
  984. Point = Control->ClientToScreen(TPoint(0, 0));
  985. }
  986. else
  987. {
  988. Point = Control->ClientToScreen(MousePos);
  989. }
  990. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  991. DebugAssert(PopupMenu != NULL);
  992. TRect Rect(Point, Point);
  993. MenuPopup(PopupMenu, Rect, Control);
  994. Handled = true;
  995. }
  996. //---------------------------------------------------------------------------
  997. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  998. {
  999. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1000. DebugAssert(Item != NULL);
  1001. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1002. DebugAssert(PopupMenu != NULL);
  1003. DebugAssert(PopupMenu->PopupComponent != NULL);
  1004. return PopupMenu->PopupComponent;
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. void __fastcall MenuButton(TButton * Button)
  1008. {
  1009. Button->Images = GlyphsModule->ButtonImages;
  1010. Button->ImageIndex = 0;
  1011. Button->DisabledImageIndex = 1;
  1012. Button->ImageAlignment = iaRight;
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. TRect __fastcall CalculatePopupRect(TButton * Button)
  1016. {
  1017. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1018. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1019. TRect Rect(UpPoint, DownPoint);
  1020. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1021. int Offset = UseThemes() ? -1 : 0;
  1022. Rect.Inflate(Offset, Offset);
  1023. return Rect;
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1027. {
  1028. MousePos = Control->ClientToScreen(MousePos);
  1029. TRect Rect(MousePos, MousePos);
  1030. return Rect;
  1031. }
  1032. //---------------------------------------------------------------------------
  1033. void __fastcall FixButtonImage(TButton * Button)
  1034. {
  1035. // with themes enabled, button image is by default drawn too high
  1036. if (UseThemes())
  1037. {
  1038. Button->ImageMargins->Top = 1;
  1039. }
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. void __fastcall CenterButtonImage(TButton * Button)
  1043. {
  1044. // with themes disabled, the text seems to be drawn over the icon,
  1045. // so that the padding spaces hide away most of the icon
  1046. if (UseThemes())
  1047. {
  1048. Button->ImageAlignment = iaCenter;
  1049. int ImageWidth = Button->Images->Width;
  1050. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  1051. Canvas->Control = Button;
  1052. UnicodeString Caption = Button->Caption;
  1053. UnicodeString Padding;
  1054. while (Canvas->TextWidth(Padding) < ImageWidth)
  1055. {
  1056. Padding += L" ";
  1057. }
  1058. if (Button->IsRightToLeft())
  1059. {
  1060. Caption = Caption + Padding;
  1061. }
  1062. else
  1063. {
  1064. Caption = Padding + Caption;
  1065. }
  1066. Button->Caption = Caption;
  1067. int CaptionWidth = Canvas->TextWidth(Caption);
  1068. // The margins seem to extend the area over which the image is centered,
  1069. // so we have to set it to a double of desired padding.
  1070. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1071. // the one below is equivalent, but with reduced rouding.
  1072. // Without the change, the rouding caused the space between icon and caption too
  1073. // small on 200% zoom.
  1074. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1075. // is approximatelly same as half of caption width before padding.
  1076. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1077. }
  1078. else
  1079. {
  1080. // at least do not draw it so near to the edge
  1081. Button->ImageMargins->Left = 1;
  1082. }
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1086. {
  1087. int Result = !S.IsEmpty() && StrToInt(S);
  1088. switch (LocaleFlagOverride)
  1089. {
  1090. default:
  1091. case lfoLanguageIfRecommended:
  1092. if (!Recommended)
  1093. {
  1094. Result = Off;
  1095. }
  1096. break;
  1097. case lfoLanguage:
  1098. // noop = as configured in locale
  1099. break;
  1100. case lfoAlways:
  1101. Result = On;
  1102. break;
  1103. case lfoNever:
  1104. Result = Off;
  1105. break;
  1106. }
  1107. return Result;
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1111. {
  1112. if (GlobalOnMinimize == NULL)
  1113. {
  1114. GlobalOnMinimize = OnMinimize;
  1115. }
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1119. {
  1120. if (GlobalOnMinimize == OnMinimize)
  1121. {
  1122. GlobalOnMinimize = NULL;
  1123. }
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1127. {
  1128. Configuration->Usage->Inc(L"OperationMinimizations");
  1129. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1130. {
  1131. GlobalOnMinimize(Sender);
  1132. }
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1136. {
  1137. // WORKAROUND
  1138. // When main window is hidden (command-line operation),
  1139. // we do not want it to be shown by TApplication.Restore,
  1140. // so we temporarily detach it from an application.
  1141. // Probably not really necessary for minimizing phase,
  1142. // but we do it for consistency anyway.
  1143. TForm * MainForm = Application->MainForm;
  1144. bool RestoreMainForm = false;
  1145. if (DebugAlwaysTrue(MainForm != NULL) &&
  1146. !MainForm->Visible)
  1147. {
  1148. SetAppMainForm(NULL);
  1149. RestoreMainForm = true;
  1150. }
  1151. try
  1152. {
  1153. if (Minimize)
  1154. {
  1155. Application->Minimize();
  1156. }
  1157. else
  1158. {
  1159. Application->Restore();
  1160. }
  1161. }
  1162. __finally
  1163. {
  1164. if (RestoreMainForm)
  1165. {
  1166. SetAppMainForm(MainForm);
  1167. }
  1168. }
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. void __fastcall ApplicationMinimize()
  1172. {
  1173. DoApplicationMinimizeRestore(true);
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. void __fastcall ApplicationRestore()
  1177. {
  1178. DoApplicationMinimizeRestore(false);
  1179. }
  1180. //---------------------------------------------------------------------------
  1181. bool __fastcall IsApplicationMinimized()
  1182. {
  1183. // VCL help recommends handling Application->OnMinimize/OnRestore
  1184. // for tracking state, but OnRestore is actually not called
  1185. // (OnMinimize is), when app is minimized from e.g. Progress window
  1186. bool AppMinimized = IsIconic(Application->Handle);
  1187. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1188. return AppMinimized || MainFormMinimized;
  1189. }
  1190. //---------------------------------------------------------------------------
  1191. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1192. {
  1193. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1194. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1195. bool Result = (Cmd == SC_MINIMIZE);
  1196. if (Result)
  1197. {
  1198. ApplicationMinimize();
  1199. SysCommand.Result = 1;
  1200. }
  1201. return Result;
  1202. }
  1203. //---------------------------------------------------------------------------
  1204. void __fastcall WinInitialize()
  1205. {
  1206. if (JclHookExceptions())
  1207. {
  1208. JclStackTrackingOptions << stAllModules;
  1209. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1210. }
  1211. SetErrorMode(SEM_FAILCRITICALERRORS);
  1212. OnApiPath = ApiPath;
  1213. MainThread = GetCurrentThreadId();
  1214. #pragma warn -8111
  1215. #pragma warn .8111
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. void __fastcall WinFinalize()
  1219. {
  1220. JclRemoveExceptNotifier(DoExceptNotify);
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1224. {
  1225. FVisible = false;
  1226. FOnClick = NULL;
  1227. FOnBalloonClick = NULL;
  1228. FBalloonUserData = NULL;
  1229. FTrayIcon = new NOTIFYICONDATA;
  1230. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1231. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1232. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1233. // LoadIconMetric is available from Windows Vista only
  1234. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1235. if (DebugAlwaysTrue(ComCtl32Dll))
  1236. {
  1237. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1238. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1239. if (LoadIconMetric != NULL)
  1240. {
  1241. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1242. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1243. }
  1244. }
  1245. if (FTrayIcon->hIcon == 0)
  1246. {
  1247. FTrayIcon->hIcon = Application->Icon->Handle;
  1248. }
  1249. FTrayIcon->uID = Id;
  1250. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1251. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1252. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. __fastcall ::TTrayIcon::~TTrayIcon()
  1256. {
  1257. // make sure we hide icon even in case it was shown just to pop up the balloon
  1258. // (in which case Visible == false)
  1259. CancelBalloon();
  1260. Visible = false;
  1261. DeallocateHWnd(FTrayIcon->hWnd);
  1262. delete FTrayIcon;
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1266. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1267. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1268. {
  1269. if (Timeout > 30000)
  1270. {
  1271. // this is probably system limit, do not try more, especially for
  1272. // the timeout-driven hiding of the tray icon (for Win2k)
  1273. Timeout = 30000;
  1274. }
  1275. FTrayIcon->uFlags |= NIF_INFO;
  1276. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1277. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1278. UnicodeString Info = Str;
  1279. // When szInfo is empty, balloon is not shown
  1280. // (or actually it means the balloon should be deleted, if any)
  1281. if (Info.IsEmpty())
  1282. {
  1283. Info = L" ";
  1284. }
  1285. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1286. FTrayIcon->uTimeout = Timeout;
  1287. switch (QueryType)
  1288. {
  1289. case qtError:
  1290. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1291. break;
  1292. case qtInformation:
  1293. case qtConfirmation:
  1294. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1295. break;
  1296. case qtWarning:
  1297. default:
  1298. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1299. break;
  1300. }
  1301. KillTimer(FTrayIcon->hWnd, 1);
  1302. if (Visible)
  1303. {
  1304. Update();
  1305. }
  1306. else
  1307. {
  1308. Notify(NIM_ADD);
  1309. }
  1310. FOnBalloonClick = OnBalloonClick;
  1311. delete FBalloonUserData;
  1312. FBalloonUserData = BalloonUserData;
  1313. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1314. // unless CancelBalloon is called explicitly
  1315. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1316. }
  1317. //---------------------------------------------------------------------------
  1318. void __fastcall ::TTrayIcon::BalloonCancelled()
  1319. {
  1320. FOnBalloonClick = NULL;
  1321. delete FBalloonUserData;
  1322. FBalloonUserData = NULL;
  1323. }
  1324. //---------------------------------------------------------------------------
  1325. void __fastcall ::TTrayIcon::CancelBalloon()
  1326. {
  1327. KillTimer(FTrayIcon->hWnd, 1);
  1328. if (Visible)
  1329. {
  1330. FTrayIcon->uFlags |= NIF_INFO;
  1331. FTrayIcon->szInfo[0] = L'\0';
  1332. Update();
  1333. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1334. }
  1335. else
  1336. {
  1337. Notify(NIM_DELETE);
  1338. }
  1339. BalloonCancelled();
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1343. {
  1344. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1345. if (Result && (Message == NIM_ADD))
  1346. {
  1347. UINT Timeout = FTrayIcon->uTimeout;
  1348. try
  1349. {
  1350. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1351. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1352. }
  1353. __finally
  1354. {
  1355. FTrayIcon->uTimeout = Timeout;
  1356. }
  1357. }
  1358. return Result;
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. void __fastcall ::TTrayIcon::Update()
  1362. {
  1363. if (Visible)
  1364. {
  1365. Notify(NIM_MODIFY);
  1366. }
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1370. {
  1371. if (Visible != value)
  1372. {
  1373. if (value)
  1374. {
  1375. FVisible = Notify(NIM_ADD);
  1376. }
  1377. else
  1378. {
  1379. FVisible = false;
  1380. KillTimer(FTrayIcon->hWnd, 1);
  1381. Notify(NIM_DELETE);
  1382. BalloonCancelled();
  1383. }
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1388. {
  1389. try
  1390. {
  1391. if (Message.Msg == WM_TRAY_ICON)
  1392. {
  1393. DebugAssert(Message.WParam == 0);
  1394. switch (Message.LParam)
  1395. {
  1396. // old shell32
  1397. case WM_LBUTTONUP:
  1398. case WM_RBUTTONUP:
  1399. // new shell32:
  1400. case WM_CONTEXTMENU:
  1401. if (OnClick != NULL)
  1402. {
  1403. OnClick(NULL);
  1404. }
  1405. Message.Result = true;
  1406. break;
  1407. }
  1408. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1409. {
  1410. if (FOnBalloonClick != NULL)
  1411. {
  1412. // prevent the user data from being freed by possible call
  1413. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1414. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1415. FBalloonUserData = NULL;
  1416. FOnBalloonClick(UserData.get());
  1417. }
  1418. else if (OnClick != NULL)
  1419. {
  1420. OnClick(NULL);
  1421. }
  1422. }
  1423. switch (Message.LParam)
  1424. {
  1425. case NIN_BALLOONHIDE:
  1426. case NIN_BALLOONTIMEOUT:
  1427. case NIN_BALLOONUSERCLICK:
  1428. KillTimer(FTrayIcon->hWnd, 1);
  1429. // if icon was shown just to display balloon, hide it with the balloon
  1430. if (!Visible)
  1431. {
  1432. Notify(NIM_DELETE);
  1433. }
  1434. BalloonCancelled();
  1435. break;
  1436. }
  1437. }
  1438. else if (Message.Msg == WM_TIMER)
  1439. {
  1440. // sanity check
  1441. Notify(NIM_DELETE);
  1442. BalloonCancelled();
  1443. }
  1444. else if (Message.Msg == FTaskbarCreatedMsg)
  1445. {
  1446. if (Visible)
  1447. {
  1448. // force recreation
  1449. Visible = false;
  1450. Visible = true;
  1451. }
  1452. }
  1453. else
  1454. {
  1455. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1456. }
  1457. }
  1458. catch(Exception & E)
  1459. {
  1460. Application->HandleException(&E);
  1461. }
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1465. {
  1466. return FTrayIcon->szTip;
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1470. {
  1471. if (Hint != value)
  1472. {
  1473. unsigned int Max = LENOF(FTrayIcon->szTip);
  1474. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1475. Update();
  1476. }
  1477. }
  1478. //---------------------------------------------------------------------------