WinInterface.cpp 58 KB

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