WinInterface.cpp 57 KB

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