WinInterface.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlwapi.h>
  5. #include <Common.h>
  6. #include <Exceptions.h>
  7. #include <CoreMain.h>
  8. #include <TextsCore.h>
  9. #include <TextsWin.h>
  10. #include <HelpWin.h>
  11. #include <HelpCore.h>
  12. #include <Interface.h>
  13. #include <VCLCommon.h>
  14. #include <Glyphs.h>
  15. #include <PasTools.hpp>
  16. #include "WinInterface.h"
  17. #include "CustomWinConfiguration.h"
  18. #include "GUITools.h"
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. #define WM_TRAY_ICON (WM_WINSCP_USER + 5)
  23. //---------------------------------------------------------------------
  24. TNotifyEvent GlobalOnMinimize = NULL;
  25. //---------------------------------------------------------------------
  26. void __fastcall FormHelp(TForm * Form)
  27. {
  28. InvokeHelp(Form->ActiveControl != NULL ? Form->ActiveControl : Form);
  29. }
  30. //---------------------------------------------------------------------------
  31. TMessageParams::TMessageParams(unsigned int AParams)
  32. {
  33. Reset();
  34. Params = AParams;
  35. }
  36. //---------------------------------------------------------------------------
  37. TMessageParams::TMessageParams(const TQueryParams * AParams)
  38. {
  39. Reset();
  40. if (AParams != NULL)
  41. {
  42. Aliases = AParams->Aliases;
  43. AliasesCount = AParams->AliasesCount;
  44. Timer = AParams->Timer;
  45. TimerEvent = AParams->TimerEvent;
  46. TimerMessage = AParams->TimerMessage;
  47. TimerAnswers = AParams->TimerAnswers;
  48. Timeout = AParams->Timeout;
  49. TimeoutAnswer = AParams->TimeoutAnswer;
  50. if (FLAGSET(AParams->Params, qpNeverAskAgainCheck))
  51. {
  52. Params |= mpNeverAskAgainCheck;
  53. }
  54. if (FLAGSET(AParams->Params, qpAllowContinueOnError))
  55. {
  56. Params |= mpAllowContinueOnError;
  57. }
  58. }
  59. }
  60. //---------------------------------------------------------------------------
  61. inline void TMessageParams::Reset()
  62. {
  63. Params = 0;
  64. Aliases = NULL;
  65. AliasesCount = 0;
  66. Timer = 0;
  67. TimerEvent = NULL;
  68. TimerMessage = L"";
  69. TimerAnswers = 0;
  70. Timeout = 0;
  71. TimeoutAnswer = 0;
  72. NeverAskAgainTitle = L"";
  73. NeverAskAgainAnswer = 0;
  74. NeverAskAgainCheckedInitially = false;
  75. AllowHelp = true;
  76. ImageName = L"";
  77. }
  78. //---------------------------------------------------------------------------
  79. static bool __fastcall IsPositiveAnswer(unsigned int Answer)
  80. {
  81. return (Answer == qaYes) || (Answer == qaOK) || (Answer == qaYesToAll);
  82. }
  83. //---------------------------------------------------------------------------
  84. static void __fastcall NeverAskAgainCheckClick(void * /*Data*/, TObject * Sender)
  85. {
  86. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(Sender);
  87. assert(CheckBox != NULL);
  88. TForm * Dialog = dynamic_cast<TForm *>(CheckBox->Owner);
  89. assert(Dialog != NULL);
  90. unsigned int PositiveAnswer = 0;
  91. if (CheckBox->Checked)
  92. {
  93. if (CheckBox->Tag > 0)
  94. {
  95. PositiveAnswer = CheckBox->Tag;
  96. }
  97. else
  98. {
  99. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  100. {
  101. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  102. if (Button != NULL)
  103. {
  104. if (IsPositiveAnswer(Button->ModalResult))
  105. {
  106. PositiveAnswer = Button->ModalResult;
  107. break;
  108. }
  109. }
  110. }
  111. }
  112. assert(PositiveAnswer != 0);
  113. }
  114. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  115. {
  116. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  117. if (Button != NULL)
  118. {
  119. if ((Button->ModalResult != 0) && (Button->ModalResult != static_cast<int>(qaCancel)))
  120. {
  121. Button->Enabled = !CheckBox->Checked || (Button->ModalResult == static_cast<int>(PositiveAnswer));
  122. }
  123. if (Button->DropDownMenu != NULL)
  124. {
  125. for (int iii = 0; iii < Button->DropDownMenu->Items->Count; iii++)
  126. {
  127. TMenuItem * Item = Button->DropDownMenu->Items->Items[iii];
  128. Item->Enabled = Item->Default || !CheckBox->Checked;
  129. }
  130. }
  131. }
  132. }
  133. }
  134. //---------------------------------------------------------------------------
  135. static TCheckBox * __fastcall FindNeverAskAgainCheck(TForm * Dialog)
  136. {
  137. return NOT_NULL(dynamic_cast<TCheckBox *>(Dialog->FindComponent(L"NeverAskAgainCheck")));
  138. }
  139. //---------------------------------------------------------------------------
  140. TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg,
  141. TStrings * MoreMessages, TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword,
  142. const TMessageParams * Params, TButton *& TimeoutButton)
  143. {
  144. TMsgDlgType DlgType;
  145. switch (Type) {
  146. case qtConfirmation: DlgType = mtConfirmation; break;
  147. case qtInformation: DlgType = mtInformation; break;
  148. case qtError: DlgType = mtError; break;
  149. case qtWarning: DlgType = mtWarning; break;
  150. default: assert(false);
  151. }
  152. unsigned int TimeoutAnswer = (Params != NULL) ? Params->TimeoutAnswer : 0;
  153. unsigned int ActualAnswers = Answers;
  154. if ((Params == NULL) || Params->AllowHelp)
  155. {
  156. Answers = Answers | qaHelp;
  157. }
  158. if (HelpKeyword == HELP_INTERNAL_ERROR)
  159. {
  160. Answers = Answers | qaReport;
  161. }
  162. if ((MoreMessages != NULL) && (MoreMessages->Count == 0))
  163. {
  164. MoreMessages = NULL;
  165. }
  166. UnicodeString ImageName;
  167. if (Params != NULL)
  168. {
  169. ImageName = Params->ImageName;
  170. }
  171. const TQueryButtonAlias * Aliases = (Params != NULL) ? Params->Aliases : NULL;
  172. unsigned int AliasesCount = (Params != NULL) ? Params->AliasesCount : 0;
  173. UnicodeString NeverAskAgainCaption;
  174. bool HasNeverAskAgain = (Params != NULL) && FLAGSET(Params->Params, mpNeverAskAgainCheck);
  175. if (HasNeverAskAgain)
  176. {
  177. NeverAskAgainCaption =
  178. !Params->NeverAskAgainTitle.IsEmpty() ?
  179. (UnicodeString)Params->NeverAskAgainTitle :
  180. // qaOK | qaIgnore is used, when custom "non-answer" button is required
  181. LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ?
  182. NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN);
  183. }
  184. TForm * Dialog = CreateMoreMessageDialog(Msg, MoreMessages, DlgType, Answers,
  185. Aliases, AliasesCount, TimeoutAnswer, &TimeoutButton, ImageName, NeverAskAgainCaption);
  186. try
  187. {
  188. if (HasNeverAskAgain && ALWAYS_TRUE(Params != NULL))
  189. {
  190. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  191. NeverAskAgainCheck->Checked = Params->NeverAskAgainCheckedInitially;
  192. if (Params->NeverAskAgainAnswer > 0)
  193. {
  194. NeverAskAgainCheck->Tag = Params->NeverAskAgainAnswer;
  195. }
  196. TNotifyEvent OnClick;
  197. ((TMethod*)&OnClick)->Code = NeverAskAgainCheckClick;
  198. NeverAskAgainCheck->OnClick = OnClick;
  199. }
  200. Dialog->HelpKeyword = HelpKeyword;
  201. if (FLAGSET(Answers, qaHelp))
  202. {
  203. Dialog->BorderIcons = Dialog->BorderIcons << biHelp;
  204. }
  205. ResetSystemSettings(Dialog);
  206. }
  207. catch(...)
  208. {
  209. delete Dialog;
  210. throw;
  211. }
  212. return Dialog;
  213. }
  214. //---------------------------------------------------------------------------
  215. unsigned int __fastcall ExecuteMessageDialog(TForm * Dialog, unsigned int Answers, const TMessageParams * Params)
  216. {
  217. FlashOnBackground();
  218. unsigned int Answer = Dialog->ShowModal();
  219. // mrCancel is returned always when X button is pressed, despite
  220. // no Cancel button was on the dialog. Find valid "cancel" answer.
  221. // mrNone is retuned when Windows session is closing (log off)
  222. if ((Answer == mrCancel) || (Answer == mrNone))
  223. {
  224. Answer = CancelAnswer(Answers);
  225. }
  226. if ((Params != NULL) && (Params->Params & mpNeverAskAgainCheck))
  227. {
  228. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  229. if (NeverAskAgainCheck->Checked)
  230. {
  231. bool PositiveAnswer =
  232. (Params->NeverAskAgainAnswer > 0) ?
  233. (Answer == Params->NeverAskAgainAnswer) :
  234. IsPositiveAnswer(Answer);
  235. if (PositiveAnswer)
  236. {
  237. Answer = qaNeverAskAgain;
  238. }
  239. }
  240. }
  241. return Answer;
  242. }
  243. //---------------------------------------------------------------------------
  244. class TMessageTimer : public TTimer
  245. {
  246. public:
  247. TQueryParamsTimerEvent Event;
  248. TForm * Dialog;
  249. __fastcall TMessageTimer(TComponent * AOwner);
  250. protected:
  251. void __fastcall DoTimer(TObject * Sender);
  252. };
  253. //---------------------------------------------------------------------------
  254. __fastcall TMessageTimer::TMessageTimer(TComponent * AOwner) : TTimer(AOwner)
  255. {
  256. Event = NULL;
  257. OnTimer = DoTimer;
  258. Dialog = NULL;
  259. }
  260. //---------------------------------------------------------------------------
  261. void __fastcall TMessageTimer::DoTimer(TObject * /*Sender*/)
  262. {
  263. if (Event != NULL)
  264. {
  265. unsigned int Result = 0;
  266. Event(Result);
  267. if (Result != 0)
  268. {
  269. Dialog->ModalResult = Result;
  270. }
  271. }
  272. }
  273. //---------------------------------------------------------------------------
  274. class TMessageTimeout : public TTimer
  275. {
  276. public:
  277. __fastcall TMessageTimeout(TComponent * AOwner, unsigned int Timeout,
  278. TButton * Button);
  279. void __fastcall Reset();
  280. void __fastcall Cancel();
  281. protected:
  282. unsigned int FOrigTimeout;
  283. unsigned int FTimeout;
  284. TButton * FButton;
  285. UnicodeString FOrigCaption;
  286. void __fastcall DoTimer(TObject * Sender);
  287. void __fastcall UpdateButton();
  288. };
  289. //---------------------------------------------------------------------------
  290. __fastcall TMessageTimeout::TMessageTimeout(TComponent * AOwner,
  291. unsigned int Timeout, TButton * Button) :
  292. TTimer(AOwner), FOrigTimeout(Timeout), FTimeout(Timeout), FButton(Button)
  293. {
  294. OnTimer = DoTimer;
  295. Interval = MSecsPerSec;
  296. FOrigCaption = FButton->Caption;
  297. UpdateButton();
  298. }
  299. //---------------------------------------------------------------------------
  300. void __fastcall TMessageTimeout::Reset()
  301. {
  302. FTimeout = FOrigTimeout;
  303. UpdateButton();
  304. }
  305. //---------------------------------------------------------------------------
  306. void __fastcall TMessageTimeout::Cancel()
  307. {
  308. Enabled = false;
  309. UpdateButton();
  310. }
  311. //---------------------------------------------------------------------------
  312. void __fastcall TMessageTimeout::UpdateButton()
  313. {
  314. assert(FButton != NULL);
  315. FButton->Caption =
  316. !Enabled ? FOrigCaption : FMTLOAD(TIMEOUT_BUTTON, (FOrigCaption, int(FTimeout / MSecsPerSec)));
  317. }
  318. //---------------------------------------------------------------------------
  319. void __fastcall TMessageTimeout::DoTimer(TObject * /*Sender*/)
  320. {
  321. if (FTimeout <= MSecsPerSec)
  322. {
  323. assert(FButton != NULL);
  324. TForm * Dialog = dynamic_cast<TForm *>(FButton->Parent);
  325. assert(Dialog != NULL);
  326. Dialog->ModalResult = FButton->ModalResult;
  327. }
  328. else
  329. {
  330. FTimeout -= MSecsPerSec;
  331. UpdateButton();
  332. }
  333. }
  334. //---------------------------------------------------------------------
  335. class TPublicControl : public TControl
  336. {
  337. friend void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled);
  338. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  339. };
  340. //---------------------------------------------------------------------
  341. class TPublicWinControl : public TWinControl
  342. {
  343. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  344. };
  345. //---------------------------------------------------------------------------
  346. static void __fastcall MessageDialogMouseMove(void * Data, TObject * /*Sender*/,
  347. TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  348. {
  349. assert(Data != NULL);
  350. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  351. Timeout->Reset();
  352. }
  353. //---------------------------------------------------------------------------
  354. static void __fastcall MessageDialogMouseDown(void * Data, TObject * /*Sender*/,
  355. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  356. {
  357. assert(Data != NULL);
  358. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  359. Timeout->Cancel();
  360. }
  361. //---------------------------------------------------------------------------
  362. static void __fastcall MessageDialogKeyDownUp(void * Data, TObject * /*Sender*/,
  363. Word & /*Key*/, TShiftState /*Shift*/)
  364. {
  365. assert(Data != NULL);
  366. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  367. Timeout->Cancel();
  368. }
  369. //---------------------------------------------------------------------------
  370. void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout)
  371. {
  372. TPublicControl * PublicControl = reinterpret_cast<TPublicControl *>(Control);
  373. assert(PublicControl->OnMouseMove == NULL);
  374. PublicControl->OnMouseMove = MakeMethod<TMouseMoveEvent>(Timeout, MessageDialogMouseMove);
  375. assert(PublicControl->OnMouseDown == NULL);
  376. PublicControl->OnMouseDown = MakeMethod<TMouseEvent>(Timeout, MessageDialogMouseDown);
  377. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  378. if (WinControl != NULL)
  379. {
  380. TPublicWinControl * PublicWinControl = reinterpret_cast<TPublicWinControl *>(Control);
  381. assert(PublicWinControl->OnKeyDown == NULL);
  382. PublicWinControl->OnKeyDown = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  383. assert(PublicWinControl->OnKeyUp == NULL);
  384. PublicWinControl->OnKeyUp = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  385. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  386. {
  387. SetTimeoutEvents(WinControl->Controls[Index], Timeout);
  388. }
  389. }
  390. }
  391. //---------------------------------------------------------------------------
  392. unsigned int __fastcall MoreMessageDialog(const UnicodeString Message, TStrings * MoreMessages,
  393. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  394. {
  395. unsigned int Result;
  396. TForm * Dialog = NULL;
  397. TMessageTimer * Timer = NULL;
  398. TMessageTimeout * Timeout = NULL;
  399. try
  400. {
  401. UnicodeString AMessage = Message;
  402. if ((Params != NULL) && (Params->Timer > 0))
  403. {
  404. Timer = new TMessageTimer(Application);
  405. Timer->Interval = Params->Timer;
  406. Timer->Event = Params->TimerEvent;
  407. if (Params->TimerAnswers > 0)
  408. {
  409. Answers = Params->TimerAnswers;
  410. }
  411. if (!Params->TimerMessage.IsEmpty())
  412. {
  413. AMessage = Params->TimerMessage;
  414. }
  415. }
  416. TButton * TimeoutButton = NULL;
  417. Dialog = CreateMessageDialogEx(AMessage, MoreMessages, Type, Answers,
  418. HelpKeyword, Params, TimeoutButton);
  419. if (Timer != NULL)
  420. {
  421. Timer->Dialog = Dialog;
  422. }
  423. if (Params != NULL)
  424. {
  425. if (Params->Timeout > 0)
  426. {
  427. Timeout = new TMessageTimeout(Application, Params->Timeout, TimeoutButton);
  428. SetTimeoutEvents(Dialog, Timeout);
  429. }
  430. }
  431. Result = ExecuteMessageDialog(Dialog, Answers, Params);
  432. }
  433. __finally
  434. {
  435. delete Dialog;
  436. delete Timer;
  437. delete Timeout;
  438. }
  439. return Result;
  440. }
  441. //---------------------------------------------------------------------------
  442. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  443. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  444. {
  445. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  446. }
  447. //---------------------------------------------------------------------------
  448. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  449. {
  450. unsigned int Result;
  451. TStrings * More = NULL;
  452. try
  453. {
  454. if (!MoreMessages.IsEmpty())
  455. {
  456. More = new TStringList();
  457. More->Text = MoreMessages;
  458. }
  459. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  460. }
  461. __finally
  462. {
  463. delete More;
  464. }
  465. return Result;
  466. }
  467. //---------------------------------------------------------------------------
  468. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  469. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  470. const TMessageParams * Params)
  471. {
  472. TStrings * MoreMessages = NULL;
  473. ExtException * EE = dynamic_cast<ExtException *>(E);
  474. if (EE != NULL)
  475. {
  476. MoreMessages = EE->MoreMessages;
  477. }
  478. UnicodeString Message;
  479. // this is always called from within ExceptionMessage check,
  480. // so it should never fail here
  481. CHECK(ExceptionMessageFormatted(E, Message));
  482. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  483. return MoreMessageDialog(
  484. FORMAT(MessageFormat.IsEmpty() ? UnicodeString(L"%s") : MessageFormat, (Message)),
  485. MoreMessages, Type, Answers, HelpKeyword, Params);
  486. }
  487. //---------------------------------------------------------------------------
  488. unsigned int __fastcall FatalExceptionMessageDialog(Exception * E, TQueryType Type,
  489. int SessionReopenTimeout, const UnicodeString MessageFormat, unsigned int Answers,
  490. UnicodeString HelpKeyword, const TMessageParams * Params)
  491. {
  492. assert(FLAGCLEAR(Answers, qaRetry));
  493. Answers |= qaRetry;
  494. TQueryButtonAlias Aliases[1];
  495. Aliases[0].Button = qaRetry;
  496. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  497. TMessageParams AParams;
  498. if (Params != NULL)
  499. {
  500. AParams = *Params;
  501. }
  502. assert(AParams.Timeout == 0);
  503. // the condition is de facto excess
  504. if (SessionReopenTimeout > 0)
  505. {
  506. AParams.Timeout = SessionReopenTimeout;
  507. AParams.TimeoutAnswer = qaRetry;
  508. }
  509. assert(AParams.Aliases == NULL);
  510. AParams.Aliases = Aliases;
  511. AParams.AliasesCount = LENOF(Aliases);
  512. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  513. }
  514. //---------------------------------------------------------------------------
  515. void __fastcall Busy(bool Start)
  516. {
  517. static int Busy = 0;
  518. static TCursor PrevCursor;
  519. if (Start)
  520. {
  521. if (!Busy)
  522. {
  523. PrevCursor = Screen->Cursor;
  524. Screen->Cursor = crHourGlass;
  525. }
  526. Busy++;
  527. assert(Busy < 10);
  528. }
  529. else
  530. {
  531. assert(Busy > 0);
  532. Busy--;
  533. if (!Busy)
  534. {
  535. Screen->Cursor = PrevCursor;
  536. }
  537. }
  538. }
  539. //---------------------------------------------------------------------------
  540. void __fastcall CopyParamListButton(TButton * Button)
  541. {
  542. if (!SupportsSplitButton())
  543. {
  544. MenuButton(Button);
  545. }
  546. }
  547. //---------------------------------------------------------------------------
  548. const int cpiDefault = -1;
  549. const int cpiConfigure = -2;
  550. const int cpiCustom = -3;
  551. const int cpiSaveSettings = -4;
  552. //---------------------------------------------------------------------------
  553. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  554. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  555. int Options, int CopyParamAttrs, bool SaveSettings)
  556. {
  557. Menu->Items->Clear();
  558. TMenuItem * CustomizeItem = NULL;
  559. TMenuItem * Item;
  560. if (FLAGSET(Options, cplCustomize))
  561. {
  562. Item = new TMenuItem(Menu);
  563. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  564. Item->Tag = cpiCustom;
  565. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  566. Item->OnClick = OnClick;
  567. Menu->Items->Add(Item);
  568. CustomizeItem = Item;
  569. }
  570. if (FLAGSET(Options, cplSaveSettings))
  571. {
  572. Item = new TMenuItem(Menu);
  573. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  574. Item->Tag = cpiSaveSettings;
  575. Item->Checked = SaveSettings;
  576. Item->OnClick = OnClick;
  577. Menu->Items->Add(Item);
  578. }
  579. Item = new TMenuItem(Menu);
  580. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  581. Item->Visible = false;
  582. Item->Enabled = false;
  583. Menu->Items->Add(Item);
  584. bool AnyChecked = false;
  585. Item = new TMenuItem(Menu);
  586. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  587. Item->Tag = cpiDefault;
  588. Item->Checked =
  589. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  590. AnyChecked = AnyChecked || Item->Checked;
  591. Item->OnClick = OnClick;
  592. Menu->Items->Add(Item);
  593. TCopyParamType DefaultParam;
  594. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  595. for (int i = 0; i < CopyParamList->Count; i++)
  596. {
  597. UnicodeString Name = CopyParamList->Names[i];
  598. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  599. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  600. // This makes "Binary" preset visible,
  601. // as long as we care about transfer mode
  602. ((AParam == DefaultParam) &&
  603. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  604. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  605. {
  606. Item = new TMenuItem(Menu);
  607. Item->Caption = Name;
  608. Item->Tag = i;
  609. Item->Checked =
  610. (Preset == Name) && (AParam == Param);
  611. AnyChecked = AnyChecked || Item->Checked;
  612. Item->OnClick = OnClick;
  613. Menu->Items->Add(Item);
  614. }
  615. }
  616. if (CustomizeItem != NULL)
  617. {
  618. CustomizeItem->Checked = !AnyChecked;
  619. }
  620. Item = new TMenuItem(Menu);
  621. Item->Caption = L"-";
  622. Menu->Items->Add(Item);
  623. Item = new TMenuItem(Menu);
  624. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  625. Item->Tag = cpiConfigure;
  626. Item->OnClick = OnClick;
  627. Menu->Items->Add(Item);
  628. MenuPopup(Menu, Rect, NULL);
  629. }
  630. //---------------------------------------------------------------------------
  631. bool __fastcall CopyParamListPopupClick(TObject * Sender,
  632. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  633. bool * SaveSettings)
  634. {
  635. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  636. assert(Item != NULL);
  637. assert((Item->Tag >= cpiSaveSettings) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  638. bool Result;
  639. if (Item->Tag == cpiConfigure)
  640. {
  641. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  642. DoPreferencesDialog(pmPresets);
  643. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]);
  644. if (Result)
  645. {
  646. Param = GUIConfiguration->CopyParamPreset[Preset];
  647. }
  648. }
  649. else if (Item->Tag == cpiCustom)
  650. {
  651. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs);
  652. }
  653. else if (Item->Tag == cpiSaveSettings)
  654. {
  655. if (ALWAYS_TRUE(SaveSettings != NULL))
  656. {
  657. *SaveSettings = !*SaveSettings;
  658. }
  659. Result = false;
  660. }
  661. else
  662. {
  663. Preset = (Item->Tag >= 0) ?
  664. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  665. Param = GUIConfiguration->CopyParamPreset[Preset];
  666. Result = true;
  667. }
  668. return Result;
  669. }
  670. //---------------------------------------------------------------------------
  671. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  672. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  673. TInteractiveCustomCommand(ChildCustomCommand)
  674. {
  675. FCustomCommandName = StripHotkey(CustomCommandName);
  676. }
  677. //---------------------------------------------------------------------------
  678. void __fastcall TWinInteractiveCustomCommand::Prompt(
  679. const UnicodeString & Prompt, UnicodeString & Value)
  680. {
  681. UnicodeString APrompt = Prompt;
  682. if (APrompt.IsEmpty())
  683. {
  684. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  685. }
  686. TStrings * History = CustomWinConfiguration->History[L"CustomCommandParam"];
  687. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  688. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History))
  689. {
  690. CustomWinConfiguration->History[L"CustomCommandParam"] = History;
  691. }
  692. else
  693. {
  694. Abort();
  695. }
  696. }
  697. //---------------------------------------------------------------------------
  698. void __fastcall TWinInteractiveCustomCommand::Execute(
  699. const UnicodeString & Command, UnicodeString & Value)
  700. {
  701. // inspired by
  702. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  703. HANDLE StdOutOutput;
  704. HANDLE StdOutInput;
  705. HANDLE StdInOutput;
  706. HANDLE StdInInput;
  707. SECURITY_ATTRIBUTES SecurityAttributes;
  708. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  709. SecurityAttributes.lpSecurityDescriptor = NULL;
  710. SecurityAttributes.bInheritHandle = TRUE;
  711. try
  712. {
  713. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  714. {
  715. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  716. }
  717. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  718. {
  719. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  720. }
  721. else
  722. {
  723. STARTUPINFO StartupInfo;
  724. PROCESS_INFORMATION ProcessInformation;
  725. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  726. StartupInfo.cb = sizeof(StartupInfo);
  727. StartupInfo.wShowWindow = SW_HIDE;
  728. StartupInfo.hStdInput = StdInOutput;
  729. StartupInfo.hStdOutput = StdOutInput;
  730. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  731. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  732. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  733. {
  734. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  735. }
  736. else
  737. {
  738. try
  739. {
  740. // wait until the console program terminated
  741. bool Running = true;
  742. while (Running)
  743. {
  744. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  745. {
  746. case WAIT_TIMEOUT:
  747. Application->ProcessMessages();
  748. break;
  749. case WAIT_OBJECT_0:
  750. Running = false;
  751. break;
  752. default:
  753. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  754. }
  755. }
  756. char Buffer[1024];
  757. unsigned long Read;
  758. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  759. (Read > 0))
  760. {
  761. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  762. {
  763. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  764. }
  765. else if (Read > 0)
  766. {
  767. Value += UnicodeString(AnsiString(Buffer, Read));
  768. }
  769. }
  770. // trim trailing cr/lf
  771. Value = TrimRight(Value);
  772. }
  773. __finally
  774. {
  775. CloseHandle(ProcessInformation.hProcess);
  776. CloseHandle(ProcessInformation.hThread);
  777. }
  778. }
  779. }
  780. }
  781. __finally
  782. {
  783. if (StdOutOutput != INVALID_HANDLE_VALUE)
  784. {
  785. CloseHandle(StdOutOutput);
  786. }
  787. if (StdOutInput != INVALID_HANDLE_VALUE)
  788. {
  789. CloseHandle(StdOutInput);
  790. }
  791. if (StdInOutput != INVALID_HANDLE_VALUE)
  792. {
  793. CloseHandle(StdInOutput);
  794. }
  795. if (StdInInput != INVALID_HANDLE_VALUE)
  796. {
  797. CloseHandle(StdInInput);
  798. }
  799. }
  800. }
  801. //---------------------------------------------------------------------------
  802. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  803. {
  804. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  808. {
  809. TControl * Control = dynamic_cast<TControl *>(Sender);
  810. assert(Control != NULL);
  811. TPoint Point;
  812. if ((MousePos.x == -1) && (MousePos.y == -1))
  813. {
  814. Point = Control->ClientToScreen(TPoint(0, 0));
  815. }
  816. else
  817. {
  818. Point = Control->ClientToScreen(MousePos);
  819. }
  820. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  821. assert(PopupMenu != NULL);
  822. TRect Rect(Point, Point);
  823. MenuPopup(PopupMenu, Rect, Control);
  824. Handled = true;
  825. }
  826. //---------------------------------------------------------------------------
  827. void __fastcall MenuButton(TButton * Button)
  828. {
  829. Button->Images = GlyphsModule->ButtonImages;
  830. Button->ImageIndex = 0;
  831. Button->DisabledImageIndex = 1;
  832. Button->ImageAlignment = iaRight;
  833. }
  834. //---------------------------------------------------------------------------
  835. TRect __fastcall CalculatePopupRect(TButton * Button)
  836. {
  837. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  838. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  839. TRect Rect(UpPoint, DownPoint);
  840. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  841. int Offset = UseThemes() ? -1 : 0;
  842. Rect.Inflate(Offset, Offset);
  843. return Rect;
  844. }
  845. //---------------------------------------------------------------------------
  846. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  847. {
  848. MousePos = Control->ClientToScreen(MousePos);
  849. TRect Rect(MousePos, MousePos);
  850. return Rect;
  851. }
  852. //---------------------------------------------------------------------------
  853. void __fastcall FixButtonImage(TButton * Button)
  854. {
  855. // this themes enabled, button image is by default drawn too high
  856. if (UseThemes())
  857. {
  858. Button->ImageMargins->Top = 1;
  859. }
  860. }
  861. //---------------------------------------------------------------------------
  862. void __fastcall CenterButtonImage(TButton * Button)
  863. {
  864. // with themes disabled, the text seems to be drawn over the icon,
  865. // so that the padding spaces hide away most of the icon
  866. if (UseThemes())
  867. {
  868. Button->ImageAlignment = iaCenter;
  869. int ImageWidthWithPadding = Button->Images->Width;
  870. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  871. Canvas->Control = Button;
  872. UnicodeString Caption = Button->Caption;
  873. Caption = TrimLeft(Caption);
  874. UnicodeString Padding;
  875. while (Canvas->TextWidth(Padding) < ImageWidthWithPadding)
  876. {
  877. Padding += L" ";
  878. }
  879. Caption = Padding + Caption;
  880. Button->Caption = Caption;
  881. int CaptionWidth = Canvas->TextWidth(Caption);
  882. // Image is bit to the left, than what it would be,
  883. // if it were to be centered together with the caption.
  884. // Windows elevation buttons have it the same
  885. // (althought they have smaller padding between image and the caption)
  886. Button->ImageMargins->Left = -(CaptionWidth / 2) - ScaleByTextHeight(Button, 8);
  887. }
  888. else
  889. {
  890. // at least do not draw it so near to the edge
  891. Button->ImageMargins->Left = 1;
  892. }
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  896. {
  897. if (GlobalOnMinimize == NULL)
  898. {
  899. GlobalOnMinimize = OnMinimize;
  900. }
  901. }
  902. //---------------------------------------------------------------------------
  903. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  904. {
  905. if (GlobalOnMinimize == OnMinimize)
  906. {
  907. GlobalOnMinimize = NULL;
  908. }
  909. }
  910. //---------------------------------------------------------------------------
  911. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  912. {
  913. if (ALWAYS_TRUE(GlobalOnMinimize != NULL))
  914. {
  915. GlobalOnMinimize(Sender);
  916. }
  917. }
  918. //---------------------------------------------------------------------------
  919. bool __fastcall IsApplicationMinimized()
  920. {
  921. // VCL help recommends handling Application->OnMinimize/OnRestore
  922. // for tracking state, but OnRestore is actually not called
  923. // (OnMinimize is), when app is minimized from e.g. Progress window
  924. bool AppMinimized = IsIconic(Application->Handle);
  925. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  926. return AppMinimized || MainFormMinimized;
  927. }
  928. //---------------------------------------------------------------------------
  929. UnicodeString __fastcall TranslateDateFormat(UnicodeString FormatStr)
  930. {
  931. UnicodeString Result;
  932. CALTYPE CalendarType = StrToIntDef(GetLocaleStr(GetDefaultLCID(), LOCALE_ICALENDARTYPE, L"1"), 1);
  933. if ((CalendarType != CAL_JAPAN) && (CalendarType != CAL_TAIWAN) && (CalendarType != CAL_KOREA))
  934. {
  935. bool RemoveEra =
  936. (SysLocale.PriLangID == LANG_JAPANESE) ||
  937. (SysLocale.PriLangID == LANG_CHINESE) ||
  938. (SysLocale.PriLangID == LANG_KOREAN);
  939. if (RemoveEra)
  940. {
  941. int I = 1;
  942. while (I <= FormatStr.Length())
  943. {
  944. if ((FormatStr[I] != L'g') && (FormatStr[I] != L'G'))
  945. {
  946. Result += FormatStr[I];
  947. }
  948. I++;
  949. }
  950. }
  951. else
  952. {
  953. Result = FormatStr;
  954. }
  955. }
  956. else
  957. {
  958. int I = 1;
  959. while (I <= FormatStr.Length())
  960. {
  961. if (FormatStr.IsLeadSurrogate(I))
  962. {
  963. int L = CharLength(FormatStr, I);
  964. Result += FormatStr.SubString(I, L);
  965. I += L;
  966. }
  967. else
  968. {
  969. if (StrLIComp(FormatStr.c_str() + I - 1, L"gg", 2) == 0)
  970. {
  971. Result += L"ggg";
  972. I++;
  973. }
  974. else if (StrLIComp(FormatStr.c_str() + I - 1, L"yyyy", 4) == 0)
  975. {
  976. Result += L"eeee";
  977. I += 4 - 1;
  978. }
  979. else if (StrLIComp(FormatStr.c_str() + I - 1, L"yy", 2) == 0)
  980. {
  981. Result += L"ee";
  982. I += 2 - 1;
  983. }
  984. else if ((FormatStr[I] == L'y') || (FormatStr[I] == L'Y'))
  985. {
  986. Result += L"e";
  987. }
  988. else
  989. {
  990. Result += FormatStr[I];
  991. }
  992. I++;
  993. }
  994. }
  995. }
  996. return Result;
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall GetFormatSettingsFix()
  1000. {
  1001. // todo InitSysLocale
  1002. // todo GetMonthDayNames
  1003. // todo GetEraNamesAndYearOffsets
  1004. LCID DefaultLCID = GetDefaultLCID();
  1005. FormatSettings = TFormatSettings::Create(DefaultLCID);
  1006. #pragma warn -8111
  1007. CurrencyString = GetLocaleStr(DefaultLCID, LOCALE_SCURRENCY, L"");
  1008. CurrencyFormat = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRENCY, L"0"), 0);
  1009. NegCurrFormat = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_INEGCURR, L"0"), 0);
  1010. ThousandSeparator = GetLocaleChar(DefaultLCID, LOCALE_STHOUSAND, L',');
  1011. DecimalSeparator = GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, L'.');
  1012. CurrencyDecimals = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRDIGITS, L"0"), 0);
  1013. DateSeparator = GetLocaleChar(DefaultLCID, LOCALE_SDATE, L'/');
  1014. ShortDateFormat = TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SSHORTDATE, L"m/d/yy"));
  1015. LongDateFormat = TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SLONGDATE, L"mmmm d, yyyy"));
  1016. TimeSeparator = GetLocaleChar(DefaultLCID, LOCALE_STIME, L':');
  1017. TimeAMString = GetLocaleStr(DefaultLCID, LOCALE_S1159, L"am");
  1018. TimePMString = GetLocaleStr(DefaultLCID, LOCALE_S2359, L"pm");
  1019. UnicodeString HourFormat;
  1020. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITLZERO, L"0"), 0) == 0)
  1021. {
  1022. HourFormat = L"h";
  1023. }
  1024. else
  1025. {
  1026. HourFormat = L"hh";
  1027. }
  1028. UnicodeString TimePrefix, TimePostfix;
  1029. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIME, L"0"), 0) == 0)
  1030. {
  1031. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIMEMARKPOSN, L"0"), 0) == 0)
  1032. {
  1033. TimePostfix = L" AMPM";
  1034. }
  1035. else
  1036. {
  1037. TimePrefix = L"AMPM ";
  1038. }
  1039. }
  1040. ShortTimeFormat = TimePrefix + HourFormat + L":mm" + TimePostfix;
  1041. LongTimeFormat = TimePrefix + HourFormat + L":mm:ss" + TimePostfix;
  1042. ListSeparator = GetLocaleChar(DefaultLCID, LOCALE_SLIST, L',');
  1043. #pragma warn .8111
  1044. }
  1045. //---------------------------------------------------------------------------
  1046. void __fastcall WinInitialize()
  1047. {
  1048. SetErrorMode(SEM_FAILCRITICALERRORS);
  1049. // HACK
  1050. if (::IsWin7())
  1051. {
  1052. GetFormatSettingsFix();
  1053. }
  1054. #pragma warn -8111
  1055. #pragma warn .8111
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. struct TNotifyIconData5
  1059. {
  1060. DWORD cbSize;
  1061. HWND hWnd;
  1062. UINT uID;
  1063. UINT uFlags;
  1064. UINT uCallbackMessage;
  1065. HICON hIcon;
  1066. TCHAR szTip[128];
  1067. DWORD dwState;
  1068. DWORD dwStateMask;
  1069. TCHAR szInfo[256];
  1070. union {
  1071. UINT uTimeout;
  1072. UINT uVersion;
  1073. } DUMMYUNIONNAME;
  1074. TCHAR szInfoTitle[64];
  1075. DWORD dwInfoFlags;
  1076. };
  1077. //---------------------------------------------------------------------------
  1078. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1079. {
  1080. FVisible = false;
  1081. FOnClick = NULL;
  1082. FOnBalloonClick = NULL;
  1083. FBalloonUserData = NULL;
  1084. FTrayIcon = new TNotifyIconData5;
  1085. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1086. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1087. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1088. FTrayIcon->hIcon = Application->Icon->Handle;
  1089. FTrayIcon->uID = Id;
  1090. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1091. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1092. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. __fastcall ::TTrayIcon::~TTrayIcon()
  1096. {
  1097. // make sure we hide icon even in case it was shown just to pop up the balloon
  1098. // (in which case Visible == false)
  1099. CancelBalloon();
  1100. Visible = false;
  1101. DeallocateHWnd(FTrayIcon->hWnd);
  1102. delete FTrayIcon;
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1106. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1107. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1108. {
  1109. if (Timeout > 30000)
  1110. {
  1111. // this is probably system limit, do not try more, especially for
  1112. // the timeout-driven hiding of the tray icon (for Win2k)
  1113. Timeout = 30000;
  1114. }
  1115. FTrayIcon->uFlags |= NIF_INFO;
  1116. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1117. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1118. StrPLCopy(FTrayIcon->szInfo, Str, LENOF(FTrayIcon->szInfo) - 1);
  1119. FTrayIcon->uTimeout = Timeout;
  1120. switch (QueryType)
  1121. {
  1122. case qtError:
  1123. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1124. break;
  1125. case qtInformation:
  1126. case qtConfirmation:
  1127. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1128. break;
  1129. case qtWarning:
  1130. default:
  1131. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1132. break;
  1133. }
  1134. KillTimer(FTrayIcon->hWnd, 1);
  1135. if (Visible)
  1136. {
  1137. Update();
  1138. }
  1139. else
  1140. {
  1141. Notify(NIM_ADD);
  1142. }
  1143. FOnBalloonClick = OnBalloonClick;
  1144. delete FBalloonUserData;
  1145. FBalloonUserData = BalloonUserData;
  1146. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1147. // unless CancelBalloon is called explicitly
  1148. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. void __fastcall ::TTrayIcon::BalloonCancelled()
  1152. {
  1153. FOnBalloonClick = NULL;
  1154. delete FBalloonUserData;
  1155. FBalloonUserData = NULL;
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. void __fastcall ::TTrayIcon::CancelBalloon()
  1159. {
  1160. KillTimer(FTrayIcon->hWnd, 1);
  1161. if (Visible)
  1162. {
  1163. FTrayIcon->uFlags |= NIF_INFO;
  1164. FTrayIcon->szInfo[0] = L'\0';
  1165. Update();
  1166. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1167. }
  1168. else
  1169. {
  1170. Notify(NIM_DELETE);
  1171. }
  1172. BalloonCancelled();
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1176. {
  1177. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1178. if (Result && (Message == NIM_ADD))
  1179. {
  1180. UINT Timeout = FTrayIcon->uTimeout;
  1181. try
  1182. {
  1183. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1184. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1185. }
  1186. __finally
  1187. {
  1188. FTrayIcon->uTimeout = Timeout;
  1189. }
  1190. }
  1191. return Result;
  1192. }
  1193. //---------------------------------------------------------------------------
  1194. void __fastcall ::TTrayIcon::Update()
  1195. {
  1196. if (Visible)
  1197. {
  1198. Notify(NIM_MODIFY);
  1199. }
  1200. }
  1201. //---------------------------------------------------------------------------
  1202. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1203. {
  1204. if (Visible != value)
  1205. {
  1206. if (value)
  1207. {
  1208. FVisible = Notify(NIM_ADD);
  1209. }
  1210. else
  1211. {
  1212. FVisible = false;
  1213. KillTimer(FTrayIcon->hWnd, 1);
  1214. Notify(NIM_DELETE);
  1215. BalloonCancelled();
  1216. }
  1217. }
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1221. {
  1222. try
  1223. {
  1224. if (Message.Msg == WM_TRAY_ICON)
  1225. {
  1226. assert(Message.WParam == 0);
  1227. switch (Message.LParam)
  1228. {
  1229. // old shell32
  1230. case WM_LBUTTONUP:
  1231. case WM_RBUTTONUP:
  1232. // new shell32:
  1233. case WM_CONTEXTMENU:
  1234. if (OnClick != NULL)
  1235. {
  1236. OnClick(NULL);
  1237. }
  1238. Message.Result = true;
  1239. break;
  1240. }
  1241. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1242. {
  1243. if (FOnBalloonClick != NULL)
  1244. {
  1245. // prevent the user data from being freed by possible call
  1246. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1247. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1248. FBalloonUserData = NULL;
  1249. FOnBalloonClick(UserData.get());
  1250. }
  1251. else if (OnClick != NULL)
  1252. {
  1253. OnClick(NULL);
  1254. }
  1255. }
  1256. switch (Message.LParam)
  1257. {
  1258. case NIN_BALLOONHIDE:
  1259. case NIN_BALLOONTIMEOUT:
  1260. case NIN_BALLOONUSERCLICK:
  1261. KillTimer(FTrayIcon->hWnd, 1);
  1262. // if icon was shown just to display balloon, hide it with the balloon
  1263. if (!Visible)
  1264. {
  1265. Notify(NIM_DELETE);
  1266. }
  1267. BalloonCancelled();
  1268. break;
  1269. }
  1270. }
  1271. else if (Message.Msg == WM_TIMER)
  1272. {
  1273. // sanity check
  1274. Notify(NIM_DELETE);
  1275. BalloonCancelled();
  1276. }
  1277. else if (Message.Msg == FTaskbarCreatedMsg)
  1278. {
  1279. if (Visible)
  1280. {
  1281. // force recreation
  1282. Visible = false;
  1283. Visible = true;
  1284. }
  1285. }
  1286. else
  1287. {
  1288. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1289. }
  1290. }
  1291. catch(Exception & E)
  1292. {
  1293. Application->HandleException(&E);
  1294. }
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1298. {
  1299. return FTrayIcon->szTip;
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1303. {
  1304. if (Hint != value)
  1305. {
  1306. unsigned int Max = LENOF(FTrayIcon->szTip);
  1307. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1308. Update();
  1309. }
  1310. }
  1311. //---------------------------------------------------------------------------