WinInterface.cpp 42 KB

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