WinInterface.cpp 57 KB

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