WinInterface.cpp 57 KB

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