WinInterface.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  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. UnicodeString __fastcall GetExceptionDebugInfo()
  537. {
  538. UnicodeString Result;
  539. TGuard Guard(StackTraceCriticalSection.get());
  540. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  541. if (Iterator != StackTraceMap.end())
  542. {
  543. TStrings * StackTrace = Iterator->second;
  544. for (int Index = 0; Index < StackTrace->Count; Index++)
  545. {
  546. UnicodeString Frame = StackTrace->Strings[Index];
  547. int P = Frame.Pos(L")");
  548. if (DebugAlwaysTrue(P > 0))
  549. {
  550. UnicodeString Symbol = Frame.SubString(P + 1, Frame.Length() - P).Trim();
  551. if ((Symbol != L"KERNELBASE.dll.RaiseException") &&
  552. (Symbol != L"Jclhookexcept::JclAddExceptNotifier") &&
  553. (Symbol != L"_ReThrowException") &&
  554. (Symbol != L"____ExceptionHandler") &&
  555. (Symbol != L"__ExceptionHandler") &&
  556. (Symbol != L"___doGlobalUnwind") &&
  557. (Symbol != L"_ThrowExceptionLDTC"))
  558. {
  559. AddToList(Result, Symbol, L";");
  560. }
  561. }
  562. }
  563. }
  564. return Result;
  565. }
  566. //---------------------------------------------------------------------------
  567. bool __fastcall AppendExceptionStackTraceAndForget(TStrings *& MoreMessages)
  568. {
  569. bool Result = false;
  570. TGuard Guard(StackTraceCriticalSection.get());
  571. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  572. if (Iterator != StackTraceMap.end())
  573. {
  574. std::unique_ptr<TStrings> OwnedMoreMessages;
  575. if (MoreMessages == NULL)
  576. {
  577. OwnedMoreMessages.reset(new TStringList());
  578. MoreMessages = OwnedMoreMessages.get();
  579. Result = true;
  580. }
  581. if (!MoreMessages->Text.IsEmpty())
  582. {
  583. MoreMessages->Text = MoreMessages->Text + "\n";
  584. }
  585. MoreMessages->Text = MoreMessages->Text + LoadStr(STACK_TRACE) + "\n";
  586. MoreMessages->AddStrings(Iterator->second);
  587. delete Iterator->second;
  588. StackTraceMap.erase(Iterator);
  589. OwnedMoreMessages.release();
  590. }
  591. return Result;
  592. }
  593. //---------------------------------------------------------------------------
  594. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  595. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  596. const TMessageParams * Params)
  597. {
  598. TStrings * MoreMessages = NULL;
  599. ExtException * EE = dynamic_cast<ExtException *>(E);
  600. if (EE != NULL)
  601. {
  602. MoreMessages = EE->MoreMessages;
  603. }
  604. UnicodeString Message;
  605. // this is always called from within ExceptionMessage check,
  606. // so it should never fail here
  607. DebugCheck(ExceptionMessageFormatted(E, Message));
  608. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  609. std::unique_ptr<TStrings> OwnedMoreMessages;
  610. if (AppendExceptionStackTraceAndForget(MoreMessages))
  611. {
  612. OwnedMoreMessages.reset(MoreMessages);
  613. }
  614. return MoreMessageDialog(
  615. FORMAT(MessageFormat.IsEmpty() ? UnicodeString(L"%s") : MessageFormat, (Message)),
  616. MoreMessages, Type, Answers, HelpKeyword, Params);
  617. }
  618. //---------------------------------------------------------------------------
  619. unsigned int __fastcall FatalExceptionMessageDialog(Exception * E, TQueryType Type,
  620. int SessionReopenTimeout, const UnicodeString MessageFormat, unsigned int Answers,
  621. UnicodeString HelpKeyword, const TMessageParams * Params)
  622. {
  623. DebugAssert(FLAGCLEAR(Answers, qaRetry));
  624. Answers |= qaRetry;
  625. TQueryButtonAlias Aliases[1];
  626. Aliases[0].Button = qaRetry;
  627. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  628. TMessageParams AParams;
  629. if (Params != NULL)
  630. {
  631. AParams = *Params;
  632. }
  633. DebugAssert(AParams.Timeout == 0);
  634. // the condition is de facto excess
  635. if (SessionReopenTimeout > 0)
  636. {
  637. AParams.Timeout = SessionReopenTimeout;
  638. AParams.TimeoutAnswer = qaRetry;
  639. }
  640. DebugAssert(AParams.Aliases == NULL);
  641. AParams.Aliases = Aliases;
  642. AParams.AliasesCount = LENOF(Aliases);
  643. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  644. }
  645. //---------------------------------------------------------------------------
  646. //---------------------------------------------------------------------------
  647. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  648. bool OSException, void * BaseOfStack)
  649. {
  650. if (ExceptObj != NULL)
  651. {
  652. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  653. if ((E != NULL) && IsInternalException(E))
  654. {
  655. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  656. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  657. if (DebugAlwaysTrue(StackInfoList != NULL))
  658. {
  659. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  660. DWORD ThreadID = GetCurrentThreadId();
  661. TGuard Guard(StackTraceCriticalSection.get());
  662. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  663. if (Iterator != StackTraceMap.end())
  664. {
  665. Iterator->second->Add(L"");
  666. Iterator->second->AddStrings(StackTrace.get());
  667. }
  668. else
  669. {
  670. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  671. }
  672. // this chains so that JclLastExceptStackList() returns NULL the next time
  673. // for the current thread
  674. delete StackInfoList;
  675. }
  676. }
  677. }
  678. }
  679. //---------------------------------------------------------------------------
  680. void * __fastcall BusyStart()
  681. {
  682. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  683. Screen->Cursor = crHourGlass;
  684. return Token;
  685. }
  686. //---------------------------------------------------------------------------
  687. void __fastcall BusyEnd(void * Token)
  688. {
  689. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  690. }
  691. //---------------------------------------------------------------------------
  692. //---------------------------------------------------------------------------
  693. static DWORD MainThread = 0;
  694. static TDateTime LastGUIUpdate = 0;
  695. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  696. static bool NoGUI = false;
  697. //---------------------------------------------------------------------------
  698. void __fastcall SetNoGUI()
  699. {
  700. NoGUI = true;
  701. }
  702. //---------------------------------------------------------------------------
  703. bool __fastcall ProcessGUI(bool Force)
  704. {
  705. DebugAssert(MainThread != 0);
  706. bool Result = false;
  707. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  708. // As we do not really need to call it in scripting/.NET, just skip it.
  709. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  710. {
  711. TDateTime N = Now();
  712. if (Force ||
  713. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  714. {
  715. LastGUIUpdate = N;
  716. Application->ProcessMessages();
  717. Result = true;
  718. }
  719. }
  720. return Result;
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall CopyParamListButton(TButton * Button)
  724. {
  725. if (!SupportsSplitButton())
  726. {
  727. MenuButton(Button);
  728. }
  729. }
  730. //---------------------------------------------------------------------------
  731. const int cpiDefault = -1;
  732. const int cpiConfigure = -2;
  733. const int cpiCustom = -3;
  734. const int cpiSaveSettings = -4;
  735. const int cpiGenerateCode = -5;
  736. //---------------------------------------------------------------------------
  737. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  738. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  739. int Options, int CopyParamAttrs, bool SaveSettings)
  740. {
  741. Menu->Items->Clear();
  742. TMenuItem * CustomizeItem = NULL;
  743. TMenuItem * Item;
  744. if (FLAGSET(Options, cplCustomize))
  745. {
  746. Item = new TMenuItem(Menu);
  747. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  748. Item->Tag = cpiCustom;
  749. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  750. Item->OnClick = OnClick;
  751. Menu->Items->Add(Item);
  752. CustomizeItem = Item;
  753. }
  754. if (FLAGSET(Options, cplSaveSettings))
  755. {
  756. Item = new TMenuItem(Menu);
  757. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  758. Item->Tag = cpiSaveSettings;
  759. Item->Checked = SaveSettings;
  760. Item->OnClick = OnClick;
  761. Menu->Items->Add(Item);
  762. }
  763. Item = new TMenuItem(Menu);
  764. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  765. Item->Visible = false;
  766. Item->Enabled = false;
  767. Menu->Items->Add(Item);
  768. bool AnyChecked = false;
  769. Item = new TMenuItem(Menu);
  770. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  771. Item->Tag = cpiDefault;
  772. Item->Checked =
  773. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  774. AnyChecked = AnyChecked || Item->Checked;
  775. Item->OnClick = OnClick;
  776. Menu->Items->Add(Item);
  777. TCopyParamType DefaultParam;
  778. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  779. for (int i = 0; i < CopyParamList->Count; i++)
  780. {
  781. UnicodeString Name = CopyParamList->Names[i];
  782. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  783. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  784. // This makes "Binary" preset visible,
  785. // as long as we care about transfer mode
  786. ((AParam == DefaultParam) &&
  787. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  788. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  789. {
  790. Item = new TMenuItem(Menu);
  791. Item->Caption = Name;
  792. Item->Tag = i;
  793. Item->Checked =
  794. (Preset == Name) && (AParam == Param);
  795. AnyChecked = AnyChecked || Item->Checked;
  796. Item->OnClick = OnClick;
  797. Menu->Items->Add(Item);
  798. }
  799. }
  800. if (CustomizeItem != NULL)
  801. {
  802. CustomizeItem->Checked = !AnyChecked;
  803. }
  804. Item = new TMenuItem(Menu);
  805. Item->Caption = L"-";
  806. Menu->Items->Add(Item);
  807. Item = new TMenuItem(Menu);
  808. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  809. Item->Tag = cpiConfigure;
  810. Item->OnClick = OnClick;
  811. Menu->Items->Add(Item);
  812. if (FLAGSET(Options, cplGenerateCode))
  813. {
  814. Item = new TMenuItem(Menu);
  815. Item->Caption = L"-";
  816. Menu->Items->Add(Item);
  817. Item = new TMenuItem(Menu);
  818. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  819. Item->Tag = cpiGenerateCode;
  820. Item->OnClick = OnClick;
  821. Menu->Items->Add(Item);
  822. }
  823. MenuPopup(Menu, Rect, NULL);
  824. }
  825. //---------------------------------------------------------------------------
  826. int __fastcall CopyParamListPopupClick(TObject * Sender,
  827. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  828. bool * SaveSettings)
  829. {
  830. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  831. DebugAssert(Item != NULL);
  832. DebugAssert((Item->Tag >= cpiGenerateCode) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  833. int Result;
  834. if (Item->Tag == cpiConfigure)
  835. {
  836. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  837. DoPreferencesDialog(pmPresets);
  838. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  839. if (Result > 0)
  840. {
  841. // For cast, see a comment below
  842. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  843. }
  844. }
  845. else if (Item->Tag == cpiCustom)
  846. {
  847. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  848. }
  849. else if (Item->Tag == cpiSaveSettings)
  850. {
  851. if (DebugAlwaysTrue(SaveSettings != NULL))
  852. {
  853. *SaveSettings = !*SaveSettings;
  854. }
  855. Result = 0;
  856. }
  857. else if (Item->Tag == cpiGenerateCode)
  858. {
  859. Result = -cplGenerateCode;
  860. }
  861. else
  862. {
  863. Preset = (Item->Tag >= 0) ?
  864. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  865. // The cast strips away the "queue" properties of the TGUICopyParamType
  866. // that are not configurable in presets
  867. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  868. Result = 1;
  869. }
  870. return Result;
  871. }
  872. //---------------------------------------------------------------------------
  873. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  874. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  875. TInteractiveCustomCommand(ChildCustomCommand)
  876. {
  877. FCustomCommandName = StripHotkey(CustomCommandName);
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TWinInteractiveCustomCommand::Prompt(
  881. const UnicodeString & Prompt, UnicodeString & Value)
  882. {
  883. UnicodeString APrompt = Prompt;
  884. if (APrompt.IsEmpty())
  885. {
  886. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  887. }
  888. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"CustomCommandParam"]));
  889. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  890. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History.get()))
  891. {
  892. CustomWinConfiguration->History[L"CustomCommandParam"] = History.get();
  893. }
  894. else
  895. {
  896. Abort();
  897. }
  898. }
  899. //---------------------------------------------------------------------------
  900. void __fastcall TWinInteractiveCustomCommand::Execute(
  901. const UnicodeString & Command, UnicodeString & Value)
  902. {
  903. // inspired by
  904. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  905. HANDLE StdOutOutput;
  906. HANDLE StdOutInput;
  907. HANDLE StdInOutput;
  908. HANDLE StdInInput;
  909. SECURITY_ATTRIBUTES SecurityAttributes;
  910. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  911. SecurityAttributes.lpSecurityDescriptor = NULL;
  912. SecurityAttributes.bInheritHandle = TRUE;
  913. try
  914. {
  915. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  916. {
  917. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  918. }
  919. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  920. {
  921. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  922. }
  923. else
  924. {
  925. STARTUPINFO StartupInfo;
  926. PROCESS_INFORMATION ProcessInformation;
  927. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  928. StartupInfo.cb = sizeof(StartupInfo);
  929. StartupInfo.wShowWindow = SW_HIDE;
  930. StartupInfo.hStdInput = StdInOutput;
  931. StartupInfo.hStdOutput = StdOutInput;
  932. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  933. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  934. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  935. {
  936. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  937. }
  938. else
  939. {
  940. try
  941. {
  942. // wait until the console program terminated
  943. bool Running = true;
  944. while (Running)
  945. {
  946. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  947. {
  948. case WAIT_TIMEOUT:
  949. Application->ProcessMessages();
  950. break;
  951. case WAIT_OBJECT_0:
  952. Running = false;
  953. break;
  954. default:
  955. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  956. }
  957. }
  958. char Buffer[1024];
  959. unsigned long Read;
  960. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  961. (Read > 0))
  962. {
  963. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  964. {
  965. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  966. }
  967. else if (Read > 0)
  968. {
  969. Value += AnsiToString(Buffer, Read);
  970. }
  971. }
  972. // trim trailing cr/lf
  973. Value = TrimRight(Value);
  974. }
  975. __finally
  976. {
  977. CloseHandle(ProcessInformation.hProcess);
  978. CloseHandle(ProcessInformation.hThread);
  979. }
  980. }
  981. }
  982. }
  983. __finally
  984. {
  985. if (StdOutOutput != INVALID_HANDLE_VALUE)
  986. {
  987. CloseHandle(StdOutOutput);
  988. }
  989. if (StdOutInput != INVALID_HANDLE_VALUE)
  990. {
  991. CloseHandle(StdOutInput);
  992. }
  993. if (StdInOutput != INVALID_HANDLE_VALUE)
  994. {
  995. CloseHandle(StdInOutput);
  996. }
  997. if (StdInInput != INVALID_HANDLE_VALUE)
  998. {
  999. CloseHandle(StdInInput);
  1000. }
  1001. }
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  1005. {
  1006. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  1010. {
  1011. TControl * Control = dynamic_cast<TControl *>(Sender);
  1012. DebugAssert(Control != NULL);
  1013. TPoint Point;
  1014. if ((MousePos.x == -1) && (MousePos.y == -1))
  1015. {
  1016. Point = Control->ClientToScreen(TPoint(0, 0));
  1017. }
  1018. else
  1019. {
  1020. Point = Control->ClientToScreen(MousePos);
  1021. }
  1022. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  1023. DebugAssert(PopupMenu != NULL);
  1024. TRect Rect(Point, Point);
  1025. MenuPopup(PopupMenu, Rect, Control);
  1026. Handled = true;
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  1030. {
  1031. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1032. DebugAssert(Item != NULL);
  1033. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1034. DebugAssert(PopupMenu != NULL);
  1035. DebugAssert(PopupMenu->PopupComponent != NULL);
  1036. return PopupMenu->PopupComponent;
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. void __fastcall MenuButton(TButton * Button)
  1040. {
  1041. Button->Images = GlyphsModule->ButtonImages;
  1042. Button->ImageIndex = 0;
  1043. Button->DisabledImageIndex = 1;
  1044. Button->ImageAlignment = iaRight;
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. TRect __fastcall CalculatePopupRect(TButton * Button)
  1048. {
  1049. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1050. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1051. TRect Rect(UpPoint, DownPoint);
  1052. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1053. int Offset = UseThemes() ? -1 : 0;
  1054. Rect.Inflate(Offset, Offset);
  1055. return Rect;
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1059. {
  1060. MousePos = Control->ClientToScreen(MousePos);
  1061. TRect Rect(MousePos, MousePos);
  1062. return Rect;
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. void __fastcall FixButtonImage(TButton * Button)
  1066. {
  1067. // with themes enabled, button image is by default drawn too high
  1068. if (UseThemes())
  1069. {
  1070. Button->ImageMargins->Top = 1;
  1071. }
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. void __fastcall CenterButtonImage(TButton * Button)
  1075. {
  1076. // with themes disabled, the text seems to be drawn over the icon,
  1077. // so that the padding spaces hide away most of the icon
  1078. if (UseThemes())
  1079. {
  1080. Button->ImageAlignment = iaCenter;
  1081. int ImageWidth = Button->Images->Width;
  1082. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  1083. Canvas->Control = Button;
  1084. UnicodeString Caption = Button->Caption;
  1085. UnicodeString Padding;
  1086. while (Canvas->TextWidth(Padding) < ImageWidth)
  1087. {
  1088. Padding += L" ";
  1089. }
  1090. if (Button->IsRightToLeft())
  1091. {
  1092. Caption = Caption + Padding;
  1093. }
  1094. else
  1095. {
  1096. Caption = Padding + Caption;
  1097. }
  1098. Button->Caption = Caption;
  1099. int CaptionWidth = Canvas->TextWidth(Caption);
  1100. // The margins seem to extend the area over which the image is centered,
  1101. // so we have to set it to a double of desired padding.
  1102. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1103. // the one below is equivalent, but with reduced rouding.
  1104. // Without the change, the rouding caused the space between icon and caption too
  1105. // small on 200% zoom.
  1106. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1107. // is approximatelly same as half of caption width before padding.
  1108. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1109. }
  1110. else
  1111. {
  1112. // at least do not draw it so near to the edge
  1113. Button->ImageMargins->Left = 1;
  1114. }
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1118. {
  1119. int Result = !S.IsEmpty() && StrToInt(S);
  1120. switch (LocaleFlagOverride)
  1121. {
  1122. default:
  1123. case lfoLanguageIfRecommended:
  1124. if (!Recommended)
  1125. {
  1126. Result = Off;
  1127. }
  1128. break;
  1129. case lfoLanguage:
  1130. // noop = as configured in locale
  1131. break;
  1132. case lfoAlways:
  1133. Result = On;
  1134. break;
  1135. case lfoNever:
  1136. Result = Off;
  1137. break;
  1138. }
  1139. return Result;
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1143. {
  1144. if (GlobalOnMinimize == NULL)
  1145. {
  1146. GlobalOnMinimize = OnMinimize;
  1147. }
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1151. {
  1152. if (GlobalOnMinimize == OnMinimize)
  1153. {
  1154. GlobalOnMinimize = NULL;
  1155. }
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1159. {
  1160. Configuration->Usage->Inc(L"OperationMinimizations");
  1161. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1162. {
  1163. GlobalOnMinimize(Sender);
  1164. }
  1165. }
  1166. //---------------------------------------------------------------------------
  1167. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1168. {
  1169. // WORKAROUND
  1170. // When main window is hidden (command-line operation),
  1171. // we do not want it to be shown by TApplication.Restore,
  1172. // so we temporarily detach it from an application.
  1173. // Probably not really necessary for minimizing phase,
  1174. // but we do it for consistency anyway.
  1175. TForm * MainForm = Application->MainForm;
  1176. bool RestoreMainForm = false;
  1177. if (DebugAlwaysTrue(MainForm != NULL) &&
  1178. !MainForm->Visible)
  1179. {
  1180. SetAppMainForm(NULL);
  1181. RestoreMainForm = true;
  1182. }
  1183. try
  1184. {
  1185. if (Minimize)
  1186. {
  1187. Application->Minimize();
  1188. }
  1189. else
  1190. {
  1191. Application->Restore();
  1192. }
  1193. }
  1194. __finally
  1195. {
  1196. if (RestoreMainForm)
  1197. {
  1198. SetAppMainForm(MainForm);
  1199. }
  1200. }
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. void __fastcall ApplicationMinimize()
  1204. {
  1205. DoApplicationMinimizeRestore(true);
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. void __fastcall ApplicationRestore()
  1209. {
  1210. DoApplicationMinimizeRestore(false);
  1211. }
  1212. //---------------------------------------------------------------------------
  1213. bool __fastcall IsApplicationMinimized()
  1214. {
  1215. // VCL help recommends handling Application->OnMinimize/OnRestore
  1216. // for tracking state, but OnRestore is actually not called
  1217. // (OnMinimize is), when app is minimized from e.g. Progress window
  1218. bool AppMinimized = IsIconic(Application->Handle);
  1219. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1220. return AppMinimized || MainFormMinimized;
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1224. {
  1225. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1226. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1227. bool Result = (Cmd == SC_MINIMIZE);
  1228. if (Result)
  1229. {
  1230. ApplicationMinimize();
  1231. SysCommand.Result = 1;
  1232. }
  1233. return Result;
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. void __fastcall WinInitialize()
  1237. {
  1238. if (JclHookExceptions())
  1239. {
  1240. JclStackTrackingOptions << stAllModules;
  1241. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1242. }
  1243. SetErrorMode(SEM_FAILCRITICALERRORS);
  1244. OnApiPath = ApiPath;
  1245. MainThread = GetCurrentThreadId();
  1246. #pragma warn -8111
  1247. #pragma warn .8111
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. void __fastcall WinFinalize()
  1251. {
  1252. JclRemoveExceptNotifier(DoExceptNotify);
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1256. {
  1257. FVisible = false;
  1258. FOnClick = NULL;
  1259. FOnBalloonClick = NULL;
  1260. FBalloonUserData = NULL;
  1261. FTrayIcon = new NOTIFYICONDATA;
  1262. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1263. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1264. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1265. // LoadIconMetric is available from Windows Vista only
  1266. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1267. if (DebugAlwaysTrue(ComCtl32Dll))
  1268. {
  1269. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1270. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1271. if (LoadIconMetric != NULL)
  1272. {
  1273. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1274. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1275. }
  1276. }
  1277. if (FTrayIcon->hIcon == 0)
  1278. {
  1279. FTrayIcon->hIcon = Application->Icon->Handle;
  1280. }
  1281. FTrayIcon->uID = Id;
  1282. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1283. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1284. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. __fastcall ::TTrayIcon::~TTrayIcon()
  1288. {
  1289. // make sure we hide icon even in case it was shown just to pop up the balloon
  1290. // (in which case Visible == false)
  1291. CancelBalloon();
  1292. Visible = false;
  1293. DeallocateHWnd(FTrayIcon->hWnd);
  1294. delete FTrayIcon;
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1298. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1299. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1300. {
  1301. if (Timeout > 30000)
  1302. {
  1303. // this is probably system limit, do not try more, especially for
  1304. // the timeout-driven hiding of the tray icon (for Win2k)
  1305. Timeout = 30000;
  1306. }
  1307. FTrayIcon->uFlags |= NIF_INFO;
  1308. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1309. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1310. UnicodeString Info = Str;
  1311. // When szInfo is empty, balloon is not shown
  1312. // (or actually it means the balloon should be deleted, if any)
  1313. if (Info.IsEmpty())
  1314. {
  1315. Info = L" ";
  1316. }
  1317. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1318. FTrayIcon->uTimeout = Timeout;
  1319. switch (QueryType)
  1320. {
  1321. case qtError:
  1322. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1323. break;
  1324. case qtInformation:
  1325. case qtConfirmation:
  1326. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1327. break;
  1328. case qtWarning:
  1329. default:
  1330. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1331. break;
  1332. }
  1333. KillTimer(FTrayIcon->hWnd, 1);
  1334. if (Visible)
  1335. {
  1336. Update();
  1337. }
  1338. else
  1339. {
  1340. Notify(NIM_ADD);
  1341. }
  1342. FOnBalloonClick = OnBalloonClick;
  1343. delete FBalloonUserData;
  1344. FBalloonUserData = BalloonUserData;
  1345. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1346. // unless CancelBalloon is called explicitly
  1347. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1348. }
  1349. //---------------------------------------------------------------------------
  1350. void __fastcall ::TTrayIcon::BalloonCancelled()
  1351. {
  1352. FOnBalloonClick = NULL;
  1353. delete FBalloonUserData;
  1354. FBalloonUserData = NULL;
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. void __fastcall ::TTrayIcon::CancelBalloon()
  1358. {
  1359. KillTimer(FTrayIcon->hWnd, 1);
  1360. if (Visible)
  1361. {
  1362. FTrayIcon->uFlags |= NIF_INFO;
  1363. FTrayIcon->szInfo[0] = L'\0';
  1364. Update();
  1365. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1366. }
  1367. else
  1368. {
  1369. Notify(NIM_DELETE);
  1370. }
  1371. BalloonCancelled();
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1375. {
  1376. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1377. if (Result && (Message == NIM_ADD))
  1378. {
  1379. UINT Timeout = FTrayIcon->uTimeout;
  1380. try
  1381. {
  1382. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1383. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1384. }
  1385. __finally
  1386. {
  1387. FTrayIcon->uTimeout = Timeout;
  1388. }
  1389. }
  1390. return Result;
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. void __fastcall ::TTrayIcon::Update()
  1394. {
  1395. if (Visible)
  1396. {
  1397. Notify(NIM_MODIFY);
  1398. }
  1399. }
  1400. //---------------------------------------------------------------------------
  1401. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1402. {
  1403. if (Visible != value)
  1404. {
  1405. if (value)
  1406. {
  1407. FVisible = Notify(NIM_ADD);
  1408. }
  1409. else
  1410. {
  1411. FVisible = false;
  1412. KillTimer(FTrayIcon->hWnd, 1);
  1413. Notify(NIM_DELETE);
  1414. BalloonCancelled();
  1415. }
  1416. }
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1420. {
  1421. try
  1422. {
  1423. if (Message.Msg == WM_TRAY_ICON)
  1424. {
  1425. DebugAssert(Message.WParam == 0);
  1426. switch (Message.LParam)
  1427. {
  1428. // old shell32
  1429. case WM_LBUTTONUP:
  1430. case WM_RBUTTONUP:
  1431. // new shell32:
  1432. case WM_CONTEXTMENU:
  1433. if (OnClick != NULL)
  1434. {
  1435. OnClick(NULL);
  1436. }
  1437. Message.Result = true;
  1438. break;
  1439. }
  1440. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1441. {
  1442. if (FOnBalloonClick != NULL)
  1443. {
  1444. // prevent the user data from being freed by possible call
  1445. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1446. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1447. FBalloonUserData = NULL;
  1448. FOnBalloonClick(UserData.get());
  1449. }
  1450. else if (OnClick != NULL)
  1451. {
  1452. OnClick(NULL);
  1453. }
  1454. }
  1455. switch (Message.LParam)
  1456. {
  1457. case NIN_BALLOONHIDE:
  1458. case NIN_BALLOONTIMEOUT:
  1459. case NIN_BALLOONUSERCLICK:
  1460. KillTimer(FTrayIcon->hWnd, 1);
  1461. // if icon was shown just to display balloon, hide it with the balloon
  1462. if (!Visible)
  1463. {
  1464. Notify(NIM_DELETE);
  1465. }
  1466. BalloonCancelled();
  1467. break;
  1468. }
  1469. }
  1470. else if (Message.Msg == WM_TIMER)
  1471. {
  1472. // sanity check
  1473. Notify(NIM_DELETE);
  1474. BalloonCancelled();
  1475. }
  1476. else if (Message.Msg == FTaskbarCreatedMsg)
  1477. {
  1478. if (Visible)
  1479. {
  1480. // force recreation
  1481. Visible = false;
  1482. Visible = true;
  1483. }
  1484. }
  1485. else
  1486. {
  1487. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1488. }
  1489. }
  1490. catch(Exception & E)
  1491. {
  1492. Application->HandleException(&E);
  1493. }
  1494. }
  1495. //---------------------------------------------------------------------------
  1496. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1497. {
  1498. return FTrayIcon->szTip;
  1499. }
  1500. //---------------------------------------------------------------------------
  1501. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1502. {
  1503. if (Hint != value)
  1504. {
  1505. unsigned int Max = LENOF(FTrayIcon->szTip);
  1506. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1507. Update();
  1508. }
  1509. }
  1510. //---------------------------------------------------------------------------