WinInterface.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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 <DateUtils.hpp>
  17. #include "WinInterface.h"
  18. #include "GUITools.h"
  19. #include "JclDebug.hpp"
  20. #include "JclHookExcept.hpp"
  21. #include <StrUtils.hpp>
  22. #include <WinApi.h>
  23. //---------------------------------------------------------------------------
  24. #pragma package(smart_init)
  25. //---------------------------------------------------------------------------
  26. #define WM_TRAY_ICON (WM_WINSCP_USER + 5)
  27. //---------------------------------------------------------------------
  28. TNotifyEvent GlobalOnMinimize = NULL;
  29. //---------------------------------------------------------------------
  30. const IID IID_IListView_Win7 = {0xE5B16AF2, 0x3990, 0x4681, {0xA6, 0x09, 0x1F, 0x06, 0x0C, 0xD1, 0x42, 0x69}};
  31. //---------------------------------------------------------------------
  32. void __fastcall FormHelp(TCustomForm * Form)
  33. {
  34. InvokeHelp(Form->ActiveControl != NULL ? Form->ActiveControl : Form);
  35. }
  36. //---------------------------------------------------------------------------
  37. TMessageParams::TMessageParams(unsigned int AParams)
  38. {
  39. Reset();
  40. Params = AParams;
  41. }
  42. //---------------------------------------------------------------------------
  43. TMessageParams::TMessageParams(const TQueryParams * AParams)
  44. {
  45. Reset();
  46. if (AParams != NULL)
  47. {
  48. Aliases = AParams->Aliases;
  49. AliasesCount = AParams->AliasesCount;
  50. Timer = AParams->Timer;
  51. TimerEvent = AParams->TimerEvent;
  52. TimerMessage = AParams->TimerMessage;
  53. TimerAnswers = AParams->TimerAnswers;
  54. TimerQueryType = AParams->TimerQueryType;
  55. Timeout = AParams->Timeout;
  56. TimeoutAnswer = AParams->TimeoutAnswer;
  57. if (FLAGSET(AParams->Params, qpNeverAskAgainCheck))
  58. {
  59. Params |= mpNeverAskAgainCheck;
  60. }
  61. if (FLAGSET(AParams->Params, qpAllowContinueOnError))
  62. {
  63. Params |= mpAllowContinueOnError;
  64. }
  65. }
  66. }
  67. //---------------------------------------------------------------------------
  68. inline void TMessageParams::Reset()
  69. {
  70. Params = 0;
  71. Aliases = NULL;
  72. AliasesCount = 0;
  73. Timer = 0;
  74. TimerEvent = NULL;
  75. TimerMessage = L"";
  76. TimerAnswers = 0;
  77. TimerQueryType = static_cast<TQueryType>(-1);
  78. Timeout = 0;
  79. TimeoutAnswer = 0;
  80. NeverAskAgainTitle = L"";
  81. NeverAskAgainAnswer = 0;
  82. NeverAskAgainCheckedInitially = false;
  83. AllowHelp = true;
  84. ImageName = L"";
  85. MoreMessagesUrl = L"";
  86. MoreMessagesSize = TSize();
  87. CustomCaption = L"";
  88. }
  89. //---------------------------------------------------------------------------
  90. static bool __fastcall IsPositiveAnswer(unsigned int Answer)
  91. {
  92. return (Answer == qaYes) || (Answer == qaOK) || (Answer == qaYesToAll);
  93. }
  94. //---------------------------------------------------------------------------
  95. static void __fastcall NeverAskAgainCheckClick(void * /*Data*/, TObject * Sender)
  96. {
  97. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(Sender);
  98. DebugAssert(CheckBox != NULL);
  99. TForm * Dialog = dynamic_cast<TForm *>(CheckBox->Owner);
  100. DebugAssert(Dialog != NULL);
  101. unsigned int PositiveAnswer = 0;
  102. if (CheckBox->Checked)
  103. {
  104. if (CheckBox->Tag > 0)
  105. {
  106. PositiveAnswer = CheckBox->Tag;
  107. }
  108. else
  109. {
  110. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  111. {
  112. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  113. if (Button != NULL)
  114. {
  115. if (IsPositiveAnswer(Button->ModalResult))
  116. {
  117. PositiveAnswer = Button->ModalResult;
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. DebugAssert(PositiveAnswer != 0);
  124. }
  125. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  126. {
  127. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  128. if (Button != NULL)
  129. {
  130. if ((Button->ModalResult != 0) && (Button->ModalResult != static_cast<int>(qaCancel)))
  131. {
  132. Button->Enabled = !CheckBox->Checked || (Button->ModalResult == static_cast<int>(PositiveAnswer));
  133. }
  134. if (Button->DropDownMenu != NULL)
  135. {
  136. for (int iii = 0; iii < Button->DropDownMenu->Items->Count; iii++)
  137. {
  138. TMenuItem * Item = Button->DropDownMenu->Items->Items[iii];
  139. Item->Enabled = Item->Default || !CheckBox->Checked;
  140. }
  141. }
  142. }
  143. }
  144. }
  145. //---------------------------------------------------------------------------
  146. static TCheckBox * __fastcall FindNeverAskAgainCheck(TForm * Dialog)
  147. {
  148. return DebugNotNull(dynamic_cast<TCheckBox *>(Dialog->FindComponent(L"NeverAskAgainCheck")));
  149. }
  150. //---------------------------------------------------------------------------
  151. TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg,
  152. TStrings * MoreMessages, TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword,
  153. const TMessageParams * Params, TButton *& TimeoutButton)
  154. {
  155. TMsgDlgType DlgType;
  156. switch (Type) {
  157. case qtConfirmation: DlgType = mtConfirmation; break;
  158. case qtInformation: DlgType = mtInformation; break;
  159. case qtError: DlgType = mtError; break;
  160. case qtWarning: DlgType = mtWarning; break;
  161. default: DebugFail();
  162. }
  163. unsigned int TimeoutAnswer = (Params != NULL) ? Params->TimeoutAnswer : 0;
  164. unsigned int ActualAnswers = Answers;
  165. if ((Params == NULL) || Params->AllowHelp)
  166. {
  167. Answers = Answers | qaHelp;
  168. }
  169. if (IsInternalErrorHelpKeyword(HelpKeyword))
  170. {
  171. Answers = Answers | qaReport;
  172. }
  173. if ((MoreMessages != NULL) && (MoreMessages->Count == 0))
  174. {
  175. MoreMessages = NULL;
  176. }
  177. UnicodeString ImageName;
  178. UnicodeString MoreMessagesUrl;
  179. TSize MoreMessagesSize;
  180. UnicodeString CustomCaption;
  181. if (Params != NULL)
  182. {
  183. ImageName = Params->ImageName;
  184. MoreMessagesUrl = Params->MoreMessagesUrl;
  185. MoreMessagesSize = Params->MoreMessagesSize;
  186. CustomCaption = Params->CustomCaption;
  187. }
  188. const TQueryButtonAlias * Aliases = (Params != NULL) ? Params->Aliases : NULL;
  189. unsigned int AliasesCount = (Params != NULL) ? Params->AliasesCount : 0;
  190. UnicodeString NeverAskAgainCaption;
  191. bool HasNeverAskAgain = (Params != NULL) && FLAGSET(Params->Params, mpNeverAskAgainCheck);
  192. if (HasNeverAskAgain)
  193. {
  194. NeverAskAgainCaption =
  195. !Params->NeverAskAgainTitle.IsEmpty() ?
  196. (UnicodeString)Params->NeverAskAgainTitle :
  197. // qaOK | qaIgnore is used, when custom "non-answer" button is required
  198. LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ?
  199. NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN);
  200. }
  201. TForm * Dialog = CreateMoreMessageDialog(Msg, MoreMessages, DlgType, Answers,
  202. Aliases, AliasesCount, TimeoutAnswer, &TimeoutButton, ImageName, NeverAskAgainCaption,
  203. MoreMessagesUrl, MoreMessagesSize, CustomCaption);
  204. try
  205. {
  206. if (HasNeverAskAgain && DebugAlwaysTrue(Params != NULL))
  207. {
  208. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  209. NeverAskAgainCheck->Checked = Params->NeverAskAgainCheckedInitially;
  210. if (Params->NeverAskAgainAnswer > 0)
  211. {
  212. NeverAskAgainCheck->Tag = Params->NeverAskAgainAnswer;
  213. }
  214. TNotifyEvent OnClick;
  215. ((TMethod*)&OnClick)->Code = NeverAskAgainCheckClick;
  216. NeverAskAgainCheck->OnClick = OnClick;
  217. }
  218. Dialog->HelpKeyword = HelpKeyword;
  219. if (FLAGSET(Answers, qaHelp))
  220. {
  221. Dialog->BorderIcons = Dialog->BorderIcons << biHelp;
  222. }
  223. ResetSystemSettings(Dialog);
  224. }
  225. catch(...)
  226. {
  227. delete Dialog;
  228. throw;
  229. }
  230. return Dialog;
  231. }
  232. //---------------------------------------------------------------------------
  233. unsigned int __fastcall ExecuteMessageDialog(TForm * Dialog, unsigned int Answers, const TMessageParams * Params)
  234. {
  235. FlashOnBackground();
  236. unsigned int Answer = Dialog->ShowModal();
  237. // mrCancel is returned always when X button is pressed, despite
  238. // no Cancel button was on the dialog. Find valid "cancel" answer.
  239. // mrNone is retuned when Windows session is closing (log off)
  240. if ((Answer == mrCancel) || (Answer == mrNone))
  241. {
  242. Answer = CancelAnswer(Answers);
  243. }
  244. if ((Params != NULL) && (Params->Params & mpNeverAskAgainCheck))
  245. {
  246. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  247. if (NeverAskAgainCheck->Checked)
  248. {
  249. bool PositiveAnswer =
  250. (Params->NeverAskAgainAnswer > 0) ?
  251. (Answer == Params->NeverAskAgainAnswer) :
  252. IsPositiveAnswer(Answer);
  253. if (PositiveAnswer)
  254. {
  255. Answer = qaNeverAskAgain;
  256. }
  257. }
  258. }
  259. return Answer;
  260. }
  261. //---------------------------------------------------------------------------
  262. class TMessageTimer : public TTimer
  263. {
  264. public:
  265. TQueryParamsTimerEvent Event;
  266. TForm * Dialog;
  267. __fastcall TMessageTimer(TComponent * AOwner);
  268. protected:
  269. void __fastcall DoTimer(TObject * Sender);
  270. };
  271. //---------------------------------------------------------------------------
  272. __fastcall TMessageTimer::TMessageTimer(TComponent * AOwner) : TTimer(AOwner)
  273. {
  274. Event = NULL;
  275. OnTimer = DoTimer;
  276. Dialog = NULL;
  277. }
  278. //---------------------------------------------------------------------------
  279. void __fastcall TMessageTimer::DoTimer(TObject * /*Sender*/)
  280. {
  281. if (Event != NULL)
  282. {
  283. unsigned int Result = 0;
  284. Event(Result);
  285. if (Result != 0)
  286. {
  287. Dialog->ModalResult = Result;
  288. }
  289. }
  290. }
  291. //---------------------------------------------------------------------------
  292. class TMessageTimeout : public TTimer
  293. {
  294. public:
  295. __fastcall TMessageTimeout(TComponent * AOwner, unsigned int Timeout,
  296. TButton * Button);
  297. void __fastcall MouseMove();
  298. void __fastcall Cancel();
  299. protected:
  300. unsigned int FOrigTimeout;
  301. unsigned int FTimeout;
  302. TButton * FButton;
  303. UnicodeString FOrigCaption;
  304. TPoint FOrigCursorPos;
  305. void __fastcall DoTimer(TObject * Sender);
  306. void __fastcall UpdateButton();
  307. };
  308. //---------------------------------------------------------------------------
  309. __fastcall TMessageTimeout::TMessageTimeout(TComponent * AOwner,
  310. unsigned int Timeout, TButton * Button) :
  311. TTimer(AOwner), FOrigTimeout(Timeout), FTimeout(Timeout), FButton(Button)
  312. {
  313. OnTimer = DoTimer;
  314. Interval = MSecsPerSec;
  315. FOrigCaption = FButton->Caption;
  316. FOrigCursorPos = Mouse->CursorPos;
  317. UpdateButton();
  318. }
  319. //---------------------------------------------------------------------------
  320. void __fastcall TMessageTimeout::MouseMove()
  321. {
  322. TPoint CursorPos = Mouse->CursorPos;
  323. int Delta = std::max(std::abs(FOrigCursorPos.X - CursorPos.X), std::abs(FOrigCursorPos.Y - CursorPos.Y));
  324. int Threshold = 8;
  325. if (DebugAlwaysTrue(FButton != NULL))
  326. {
  327. Threshold = ScaleByTextHeight(FButton, Threshold);
  328. }
  329. if (Delta > Threshold)
  330. {
  331. FOrigCursorPos = CursorPos;
  332. const unsigned int SuspendTime = 30 * MSecsPerSec;
  333. FTimeout = std::max(FOrigTimeout, SuspendTime);
  334. UpdateButton();
  335. }
  336. }
  337. //---------------------------------------------------------------------------
  338. void __fastcall TMessageTimeout::Cancel()
  339. {
  340. Enabled = false;
  341. UpdateButton();
  342. }
  343. //---------------------------------------------------------------------------
  344. void __fastcall TMessageTimeout::UpdateButton()
  345. {
  346. DebugAssert(FButton != NULL);
  347. FButton->Caption =
  348. !Enabled ? FOrigCaption : FMTLOAD(TIMEOUT_BUTTON, (FOrigCaption, int(FTimeout / MSecsPerSec)));
  349. }
  350. //---------------------------------------------------------------------------
  351. void __fastcall TMessageTimeout::DoTimer(TObject * /*Sender*/)
  352. {
  353. if (FTimeout <= Interval)
  354. {
  355. DebugAssert(FButton != NULL);
  356. TForm * Dialog = dynamic_cast<TForm *>(FButton->Parent);
  357. DebugAssert(Dialog != NULL);
  358. Dialog->ModalResult = FButton->ModalResult;
  359. }
  360. else
  361. {
  362. FTimeout -= Interval;
  363. UpdateButton();
  364. }
  365. }
  366. //---------------------------------------------------------------------
  367. class TPublicControl : public TControl
  368. {
  369. friend void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled);
  370. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  371. };
  372. //---------------------------------------------------------------------
  373. class TPublicWinControl : public TWinControl
  374. {
  375. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  376. };
  377. //---------------------------------------------------------------------------
  378. static void __fastcall MessageDialogMouseMove(void * Data, TObject * /*Sender*/,
  379. TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  380. {
  381. DebugAssert(Data != NULL);
  382. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  383. Timeout->MouseMove();
  384. }
  385. //---------------------------------------------------------------------------
  386. static void __fastcall MessageDialogMouseDown(void * Data, TObject * /*Sender*/,
  387. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  388. {
  389. DebugAssert(Data != NULL);
  390. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  391. Timeout->Cancel();
  392. }
  393. //---------------------------------------------------------------------------
  394. static void __fastcall MessageDialogKeyDownUp(void * Data, TObject * /*Sender*/,
  395. Word & /*Key*/, TShiftState /*Shift*/)
  396. {
  397. DebugAssert(Data != NULL);
  398. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  399. Timeout->Cancel();
  400. }
  401. //---------------------------------------------------------------------------
  402. void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout)
  403. {
  404. TPublicControl * PublicControl = reinterpret_cast<TPublicControl *>(Control);
  405. DebugAssert(PublicControl->OnMouseMove == NULL);
  406. PublicControl->OnMouseMove = MakeMethod<TMouseMoveEvent>(Timeout, MessageDialogMouseMove);
  407. DebugAssert(PublicControl->OnMouseDown == NULL);
  408. PublicControl->OnMouseDown = MakeMethod<TMouseEvent>(Timeout, MessageDialogMouseDown);
  409. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  410. if (WinControl != NULL)
  411. {
  412. TPublicWinControl * PublicWinControl = reinterpret_cast<TPublicWinControl *>(Control);
  413. DebugAssert(PublicWinControl->OnKeyDown == NULL);
  414. PublicWinControl->OnKeyDown = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  415. DebugAssert(PublicWinControl->OnKeyUp == NULL);
  416. PublicWinControl->OnKeyUp = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  417. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  418. {
  419. SetTimeoutEvents(WinControl->Controls[Index], Timeout);
  420. }
  421. }
  422. }
  423. //---------------------------------------------------------------------------
  424. // Merge with CreateMessageDialogEx
  425. TForm * __fastcall CreateMoreMessageDialogEx(const UnicodeString Message, TStrings * MoreMessages,
  426. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  427. {
  428. std::unique_ptr<TForm> Dialog;
  429. UnicodeString AMessage = Message;
  430. TMessageTimer * Timer = NULL;
  431. if ((Params != NULL) && (Params->Timer > 0))
  432. {
  433. Timer = new TMessageTimer(Application);
  434. Timer->Interval = Params->Timer;
  435. Timer->Event = Params->TimerEvent;
  436. if (Params->TimerAnswers > 0)
  437. {
  438. Answers = Params->TimerAnswers;
  439. }
  440. if (Params->TimerQueryType >= 0)
  441. {
  442. Type = Params->TimerQueryType;
  443. }
  444. if (!Params->TimerMessage.IsEmpty())
  445. {
  446. AMessage = Params->TimerMessage;
  447. }
  448. Timer->Name = L"MessageTimer";
  449. }
  450. TButton * TimeoutButton = NULL;
  451. Dialog.reset(
  452. CreateMessageDialogEx(
  453. AMessage, MoreMessages, Type, Answers, HelpKeyword, Params, TimeoutButton));
  454. if (Timer != NULL)
  455. {
  456. Timer->Dialog = Dialog.get();
  457. Dialog->InsertComponent(Timer);
  458. }
  459. if (Params != NULL)
  460. {
  461. if (Params->Timeout > 0)
  462. {
  463. TMessageTimeout * Timeout = new TMessageTimeout(Application, Params->Timeout, TimeoutButton);
  464. SetTimeoutEvents(Dialog.get(), Timeout);
  465. Timeout->Name = L"MessageTimeout";
  466. Dialog->InsertComponent(Timeout);
  467. }
  468. }
  469. return Dialog.release();
  470. }
  471. //---------------------------------------------------------------------------
  472. unsigned int __fastcall MoreMessageDialog(const UnicodeString Message, TStrings * MoreMessages,
  473. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  474. {
  475. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, MoreMessages, Type, Answers, HelpKeyword, Params));
  476. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, Params);
  477. return Result;
  478. }
  479. //---------------------------------------------------------------------------
  480. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  481. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  482. {
  483. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  484. }
  485. //---------------------------------------------------------------------------
  486. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  487. {
  488. unsigned int Result;
  489. TStrings * More = NULL;
  490. try
  491. {
  492. if (!MoreMessages.IsEmpty())
  493. {
  494. More = TextToStringList(MoreMessages);
  495. }
  496. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  497. }
  498. __finally
  499. {
  500. delete More;
  501. }
  502. return Result;
  503. }
  504. //---------------------------------------------------------------------------
  505. static TStrings * __fastcall StackInfoListToStrings(
  506. TJclStackInfoList * StackInfoList)
  507. {
  508. std::unique_ptr<TStrings> StackTrace(new TStringList());
  509. StackInfoList->AddToStrings(StackTrace.get(), true, false, true, true);
  510. for (int Index = 0; Index < StackTrace->Count; Index++)
  511. {
  512. UnicodeString Frame = StackTrace->Strings[Index];
  513. // get rid of declarations "flags" that are included in .map
  514. Frame = ReplaceStr(Frame, L"__fastcall ", L"");
  515. Frame = ReplaceStr(Frame, L"__linkproc__ ", L"");
  516. if (DebugAlwaysTrue(!Frame.IsEmpty() && (Frame[1] == L'(')))
  517. {
  518. int Start = Frame.Pos(L"[");
  519. int End = Frame.Pos(L"]");
  520. if (DebugAlwaysTrue((Start > 1) && (End > Start) && (Frame[Start - 1] == L' ')))
  521. {
  522. // remove absolute address
  523. Frame.Delete(Start - 1, End - Start + 2);
  524. }
  525. }
  526. StackTrace->Strings[Index] = Frame;
  527. }
  528. return StackTrace.release();
  529. }
  530. //---------------------------------------------------------------------------
  531. static std::unique_ptr<TCriticalSection> StackTraceCriticalSection(new TCriticalSection());
  532. typedef std::map<DWORD, TStrings *> TStackTraceMap;
  533. static TStackTraceMap StackTraceMap;
  534. //---------------------------------------------------------------------------
  535. bool __fastcall AppendExceptionStackTraceAndForget(TStrings *& MoreMessages)
  536. {
  537. bool Result = false;
  538. TGuard Guard(StackTraceCriticalSection.get());
  539. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  540. if (Iterator != StackTraceMap.end())
  541. {
  542. std::unique_ptr<TStrings> OwnedMoreMessages;
  543. if (MoreMessages == NULL)
  544. {
  545. OwnedMoreMessages.reset(new TStringList());
  546. MoreMessages = OwnedMoreMessages.get();
  547. Result = true;
  548. }
  549. if (!MoreMessages->Text.IsEmpty())
  550. {
  551. MoreMessages->Text = MoreMessages->Text + "\n";
  552. }
  553. MoreMessages->Text = MoreMessages->Text + LoadStr(STACK_TRACE) + "\n";
  554. MoreMessages->AddStrings(Iterator->second);
  555. delete Iterator->second;
  556. StackTraceMap.erase(Iterator);
  557. OwnedMoreMessages.release();
  558. }
  559. return Result;
  560. }
  561. //---------------------------------------------------------------------------
  562. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  563. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  564. const TMessageParams * Params)
  565. {
  566. TStrings * MoreMessages = NULL;
  567. ExtException * EE = dynamic_cast<ExtException *>(E);
  568. if (EE != NULL)
  569. {
  570. MoreMessages = EE->MoreMessages;
  571. }
  572. UnicodeString Message;
  573. // this is always called from within ExceptionMessage check,
  574. // so it should never fail here
  575. DebugCheck(ExceptionMessageFormatted(E, Message));
  576. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  577. std::unique_ptr<TStrings> OwnedMoreMessages;
  578. if (AppendExceptionStackTraceAndForget(MoreMessages))
  579. {
  580. OwnedMoreMessages.reset(MoreMessages);
  581. }
  582. return MoreMessageDialog(
  583. FORMAT(MessageFormat.IsEmpty() ? UnicodeString(L"%s") : MessageFormat, (Message)),
  584. MoreMessages, Type, Answers, HelpKeyword, Params);
  585. }
  586. //---------------------------------------------------------------------------
  587. unsigned int __fastcall FatalExceptionMessageDialog(Exception * E, TQueryType Type,
  588. int SessionReopenTimeout, const UnicodeString MessageFormat, unsigned int Answers,
  589. UnicodeString HelpKeyword, const TMessageParams * Params)
  590. {
  591. DebugAssert(FLAGCLEAR(Answers, qaRetry));
  592. Answers |= qaRetry;
  593. TQueryButtonAlias Aliases[1];
  594. Aliases[0].Button = qaRetry;
  595. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  596. TMessageParams AParams;
  597. if (Params != NULL)
  598. {
  599. AParams = *Params;
  600. }
  601. DebugAssert(AParams.Timeout == 0);
  602. // the condition is de facto excess
  603. if (SessionReopenTimeout > 0)
  604. {
  605. AParams.Timeout = SessionReopenTimeout;
  606. AParams.TimeoutAnswer = qaRetry;
  607. }
  608. DebugAssert(AParams.Aliases == NULL);
  609. AParams.Aliases = Aliases;
  610. AParams.AliasesCount = LENOF(Aliases);
  611. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  612. }
  613. //---------------------------------------------------------------------------
  614. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  615. bool OSException, void * BaseOfStack)
  616. {
  617. if (ExceptObj != NULL)
  618. {
  619. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  620. if ((E != NULL) && IsInternalException(E)) // optimization
  621. {
  622. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  623. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  624. if (DebugAlwaysTrue(StackInfoList != NULL))
  625. {
  626. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  627. DWORD ThreadID = GetCurrentThreadId();
  628. TGuard Guard(StackTraceCriticalSection.get());
  629. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  630. if (Iterator != StackTraceMap.end())
  631. {
  632. Iterator->second->Add(L"");
  633. Iterator->second->AddStrings(StackTrace.get());
  634. }
  635. else
  636. {
  637. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  638. }
  639. // this chains so that JclLastExceptStackList() returns NULL the next time
  640. // for the current thread
  641. delete StackInfoList;
  642. }
  643. }
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. void * __fastcall BusyStart()
  648. {
  649. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  650. Screen->Cursor = crHourGlass;
  651. return Token;
  652. }
  653. //---------------------------------------------------------------------------
  654. void __fastcall BusyEnd(void * Token)
  655. {
  656. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  657. }
  658. //---------------------------------------------------------------------------
  659. //---------------------------------------------------------------------------
  660. static DWORD MainThread = 0;
  661. static TDateTime LastGUIUpdate = 0;
  662. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  663. static bool NoGUI = false;
  664. //---------------------------------------------------------------------------
  665. void __fastcall SetNoGUI()
  666. {
  667. NoGUI = true;
  668. }
  669. //---------------------------------------------------------------------------
  670. bool __fastcall ProcessGUI(bool Force)
  671. {
  672. DebugAssert(MainThread != 0);
  673. bool Result = false;
  674. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  675. // As we do not really need to call it in scripting/.NET, just skip it.
  676. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  677. {
  678. TDateTime N = Now();
  679. if (Force ||
  680. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  681. {
  682. LastGUIUpdate = N;
  683. Application->ProcessMessages();
  684. Result = true;
  685. }
  686. }
  687. return Result;
  688. }
  689. //---------------------------------------------------------------------------
  690. void __fastcall CopyParamListButton(TButton * Button)
  691. {
  692. if (!SupportsSplitButton())
  693. {
  694. MenuButton(Button);
  695. }
  696. }
  697. //---------------------------------------------------------------------------
  698. const int cpiDefault = -1;
  699. const int cpiConfigure = -2;
  700. const int cpiCustom = -3;
  701. const int cpiSaveSettings = -4;
  702. const int cpiGenerateCode = -5;
  703. //---------------------------------------------------------------------------
  704. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  705. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  706. int Options, int CopyParamAttrs, bool SaveSettings)
  707. {
  708. Menu->Items->Clear();
  709. TMenuItem * CustomizeItem = NULL;
  710. TMenuItem * Item;
  711. if (FLAGSET(Options, cplCustomize))
  712. {
  713. Item = new TMenuItem(Menu);
  714. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  715. Item->Tag = cpiCustom;
  716. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  717. Item->OnClick = OnClick;
  718. Menu->Items->Add(Item);
  719. CustomizeItem = Item;
  720. }
  721. if (FLAGSET(Options, cplSaveSettings))
  722. {
  723. Item = new TMenuItem(Menu);
  724. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  725. Item->Tag = cpiSaveSettings;
  726. Item->Checked = SaveSettings;
  727. Item->OnClick = OnClick;
  728. Menu->Items->Add(Item);
  729. }
  730. Item = new TMenuItem(Menu);
  731. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  732. Item->Visible = false;
  733. Item->Enabled = false;
  734. Menu->Items->Add(Item);
  735. bool AnyChecked = false;
  736. Item = new TMenuItem(Menu);
  737. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  738. Item->Tag = cpiDefault;
  739. Item->Checked =
  740. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  741. AnyChecked = AnyChecked || Item->Checked;
  742. Item->OnClick = OnClick;
  743. Menu->Items->Add(Item);
  744. TCopyParamType DefaultParam;
  745. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  746. for (int i = 0; i < CopyParamList->Count; i++)
  747. {
  748. UnicodeString Name = CopyParamList->Names[i];
  749. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  750. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  751. // This makes "Binary" preset visible,
  752. // as long as we care about transfer mode
  753. ((AParam == DefaultParam) &&
  754. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  755. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  756. {
  757. Item = new TMenuItem(Menu);
  758. Item->Caption = Name;
  759. Item->Tag = i;
  760. Item->Checked =
  761. (Preset == Name) && (AParam == Param);
  762. AnyChecked = AnyChecked || Item->Checked;
  763. Item->OnClick = OnClick;
  764. Menu->Items->Add(Item);
  765. }
  766. }
  767. if (CustomizeItem != NULL)
  768. {
  769. CustomizeItem->Checked = !AnyChecked;
  770. }
  771. Item = new TMenuItem(Menu);
  772. Item->Caption = L"-";
  773. Menu->Items->Add(Item);
  774. Item = new TMenuItem(Menu);
  775. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  776. Item->Tag = cpiConfigure;
  777. Item->OnClick = OnClick;
  778. Menu->Items->Add(Item);
  779. if (FLAGSET(Options, cplGenerateCode))
  780. {
  781. Item = new TMenuItem(Menu);
  782. Item->Caption = L"-";
  783. Menu->Items->Add(Item);
  784. Item = new TMenuItem(Menu);
  785. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  786. Item->Tag = cpiGenerateCode;
  787. Item->OnClick = OnClick;
  788. Menu->Items->Add(Item);
  789. }
  790. MenuPopup(Menu, Rect, NULL);
  791. }
  792. //---------------------------------------------------------------------------
  793. int __fastcall CopyParamListPopupClick(TObject * Sender,
  794. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  795. bool * SaveSettings)
  796. {
  797. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  798. DebugAssert(Item != NULL);
  799. DebugAssert((Item->Tag >= cpiGenerateCode) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  800. int Result;
  801. if (Item->Tag == cpiConfigure)
  802. {
  803. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  804. DoPreferencesDialog(pmPresets);
  805. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  806. if (Result > 0)
  807. {
  808. // For cast, see a comment below
  809. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  810. }
  811. }
  812. else if (Item->Tag == cpiCustom)
  813. {
  814. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  815. }
  816. else if (Item->Tag == cpiSaveSettings)
  817. {
  818. if (DebugAlwaysTrue(SaveSettings != NULL))
  819. {
  820. *SaveSettings = !*SaveSettings;
  821. }
  822. Result = 0;
  823. }
  824. else if (Item->Tag == cpiGenerateCode)
  825. {
  826. Result = -cplGenerateCode;
  827. }
  828. else
  829. {
  830. Preset = (Item->Tag >= 0) ?
  831. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  832. // The cast strips away the "queue" properties of the TGUICopyParamType
  833. // that are not configurable in presets
  834. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  835. Result = 1;
  836. }
  837. return Result;
  838. }
  839. //---------------------------------------------------------------------------
  840. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  841. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  842. TInteractiveCustomCommand(ChildCustomCommand)
  843. {
  844. FCustomCommandName = StripHotkey(CustomCommandName);
  845. }
  846. //---------------------------------------------------------------------------
  847. void __fastcall TWinInteractiveCustomCommand::Prompt(
  848. const UnicodeString & Prompt, UnicodeString & Value)
  849. {
  850. UnicodeString APrompt = Prompt;
  851. if (APrompt.IsEmpty())
  852. {
  853. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  854. }
  855. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"CustomCommandParam"]));
  856. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  857. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History.get()))
  858. {
  859. CustomWinConfiguration->History[L"CustomCommandParam"] = History.get();
  860. }
  861. else
  862. {
  863. Abort();
  864. }
  865. }
  866. //---------------------------------------------------------------------------
  867. void __fastcall TWinInteractiveCustomCommand::Execute(
  868. const UnicodeString & Command, UnicodeString & Value)
  869. {
  870. // inspired by
  871. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  872. HANDLE StdOutOutput;
  873. HANDLE StdOutInput;
  874. HANDLE StdInOutput;
  875. HANDLE StdInInput;
  876. SECURITY_ATTRIBUTES SecurityAttributes;
  877. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  878. SecurityAttributes.lpSecurityDescriptor = NULL;
  879. SecurityAttributes.bInheritHandle = TRUE;
  880. try
  881. {
  882. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  883. {
  884. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  885. }
  886. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  887. {
  888. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  889. }
  890. else
  891. {
  892. STARTUPINFO StartupInfo;
  893. PROCESS_INFORMATION ProcessInformation;
  894. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  895. StartupInfo.cb = sizeof(StartupInfo);
  896. StartupInfo.wShowWindow = SW_HIDE;
  897. StartupInfo.hStdInput = StdInOutput;
  898. StartupInfo.hStdOutput = StdOutInput;
  899. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  900. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  901. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  902. {
  903. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  904. }
  905. else
  906. {
  907. try
  908. {
  909. // wait until the console program terminated
  910. bool Running = true;
  911. while (Running)
  912. {
  913. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  914. {
  915. case WAIT_TIMEOUT:
  916. Application->ProcessMessages();
  917. break;
  918. case WAIT_OBJECT_0:
  919. Running = false;
  920. break;
  921. default:
  922. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  923. }
  924. }
  925. char Buffer[1024];
  926. unsigned long Read;
  927. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  928. (Read > 0))
  929. {
  930. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  931. {
  932. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  933. }
  934. else if (Read > 0)
  935. {
  936. Value += AnsiToString(Buffer, Read);
  937. }
  938. }
  939. // trim trailing cr/lf
  940. Value = TrimRight(Value);
  941. }
  942. __finally
  943. {
  944. CloseHandle(ProcessInformation.hProcess);
  945. CloseHandle(ProcessInformation.hThread);
  946. }
  947. }
  948. }
  949. }
  950. __finally
  951. {
  952. if (StdOutOutput != INVALID_HANDLE_VALUE)
  953. {
  954. CloseHandle(StdOutOutput);
  955. }
  956. if (StdOutInput != INVALID_HANDLE_VALUE)
  957. {
  958. CloseHandle(StdOutInput);
  959. }
  960. if (StdInOutput != INVALID_HANDLE_VALUE)
  961. {
  962. CloseHandle(StdInOutput);
  963. }
  964. if (StdInInput != INVALID_HANDLE_VALUE)
  965. {
  966. CloseHandle(StdInInput);
  967. }
  968. }
  969. }
  970. //---------------------------------------------------------------------------
  971. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  972. {
  973. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  977. {
  978. TControl * Control = dynamic_cast<TControl *>(Sender);
  979. DebugAssert(Control != NULL);
  980. TPoint Point;
  981. if ((MousePos.x == -1) && (MousePos.y == -1))
  982. {
  983. Point = Control->ClientToScreen(TPoint(0, 0));
  984. }
  985. else
  986. {
  987. Point = Control->ClientToScreen(MousePos);
  988. }
  989. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  990. DebugAssert(PopupMenu != NULL);
  991. TRect Rect(Point, Point);
  992. MenuPopup(PopupMenu, Rect, Control);
  993. Handled = true;
  994. }
  995. //---------------------------------------------------------------------------
  996. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  997. {
  998. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  999. DebugAssert(Item != NULL);
  1000. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1001. DebugAssert(PopupMenu != NULL);
  1002. DebugAssert(PopupMenu->PopupComponent != NULL);
  1003. return PopupMenu->PopupComponent;
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall MenuButton(TButton * Button)
  1007. {
  1008. Button->Images = GlyphsModule->ButtonImages;
  1009. Button->ImageIndex = 0;
  1010. Button->DisabledImageIndex = 1;
  1011. Button->ImageAlignment = iaRight;
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. TRect __fastcall CalculatePopupRect(TButton * Button)
  1015. {
  1016. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1017. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1018. TRect Rect(UpPoint, DownPoint);
  1019. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1020. int Offset = UseThemes() ? -1 : 0;
  1021. Rect.Inflate(Offset, Offset);
  1022. return Rect;
  1023. }
  1024. //---------------------------------------------------------------------------
  1025. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1026. {
  1027. MousePos = Control->ClientToScreen(MousePos);
  1028. TRect Rect(MousePos, MousePos);
  1029. return Rect;
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. void __fastcall FixButtonImage(TButton * Button)
  1033. {
  1034. // with themes enabled, button image is by default drawn too high
  1035. if (UseThemes())
  1036. {
  1037. Button->ImageMargins->Top = 1;
  1038. }
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall CenterButtonImage(TButton * Button)
  1042. {
  1043. // with themes disabled, the text seems to be drawn over the icon,
  1044. // so that the padding spaces hide away most of the icon
  1045. if (UseThemes())
  1046. {
  1047. Button->ImageAlignment = iaCenter;
  1048. int ImageWidth = Button->Images->Width;
  1049. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  1050. Canvas->Control = Button;
  1051. UnicodeString Caption = Button->Caption;
  1052. UnicodeString Padding;
  1053. while (Canvas->TextWidth(Padding) < ImageWidth)
  1054. {
  1055. Padding += L" ";
  1056. }
  1057. if (Button->IsRightToLeft())
  1058. {
  1059. Caption = Caption + Padding;
  1060. }
  1061. else
  1062. {
  1063. Caption = Padding + Caption;
  1064. }
  1065. Button->Caption = Caption;
  1066. int CaptionWidth = Canvas->TextWidth(Caption);
  1067. // The margins seem to extend the area over which the image is centered,
  1068. // so we have to set it to a double of desired padding.
  1069. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1070. // the one below is equivalent, but with reduced rouding.
  1071. // Without the change, the rouding caused the space between icon and caption too
  1072. // small on 200% zoom.
  1073. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1074. // is approximatelly same as half of caption width before padding.
  1075. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1076. }
  1077. else
  1078. {
  1079. // at least do not draw it so near to the edge
  1080. Button->ImageMargins->Left = 1;
  1081. }
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1085. {
  1086. int Result = !S.IsEmpty() && StrToInt(S);
  1087. switch (LocaleFlagOverride)
  1088. {
  1089. default:
  1090. case lfoLanguageIfRecommended:
  1091. if (!Recommended)
  1092. {
  1093. Result = Off;
  1094. }
  1095. break;
  1096. case lfoLanguage:
  1097. // noop = as configured in locale
  1098. break;
  1099. case lfoAlways:
  1100. Result = On;
  1101. break;
  1102. case lfoNever:
  1103. Result = Off;
  1104. break;
  1105. }
  1106. return Result;
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1110. {
  1111. if (GlobalOnMinimize == NULL)
  1112. {
  1113. GlobalOnMinimize = OnMinimize;
  1114. }
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1118. {
  1119. if (GlobalOnMinimize == OnMinimize)
  1120. {
  1121. GlobalOnMinimize = NULL;
  1122. }
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1126. {
  1127. Configuration->Usage->Inc(L"OperationMinimizations");
  1128. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1129. {
  1130. GlobalOnMinimize(Sender);
  1131. }
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1135. {
  1136. // WORKAROUND
  1137. // When main window is hidden (command-line operation),
  1138. // we do not want it to be shown by TApplication.Restore,
  1139. // so we temporarily detach it from an application.
  1140. // Probably not really necessary for minimizing phase,
  1141. // but we do it for consistency anyway.
  1142. TForm * MainForm = Application->MainForm;
  1143. bool RestoreMainForm = false;
  1144. if (DebugAlwaysTrue(MainForm != NULL) &&
  1145. !MainForm->Visible)
  1146. {
  1147. SetAppMainForm(NULL);
  1148. RestoreMainForm = true;
  1149. }
  1150. try
  1151. {
  1152. if (Minimize)
  1153. {
  1154. Application->Minimize();
  1155. }
  1156. else
  1157. {
  1158. Application->Restore();
  1159. }
  1160. }
  1161. __finally
  1162. {
  1163. if (RestoreMainForm)
  1164. {
  1165. SetAppMainForm(MainForm);
  1166. }
  1167. }
  1168. }
  1169. //---------------------------------------------------------------------------
  1170. void __fastcall ApplicationMinimize()
  1171. {
  1172. DoApplicationMinimizeRestore(true);
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. void __fastcall ApplicationRestore()
  1176. {
  1177. DoApplicationMinimizeRestore(false);
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. bool __fastcall IsApplicationMinimized()
  1181. {
  1182. // VCL help recommends handling Application->OnMinimize/OnRestore
  1183. // for tracking state, but OnRestore is actually not called
  1184. // (OnMinimize is), when app is minimized from e.g. Progress window
  1185. bool AppMinimized = IsIconic(Application->Handle);
  1186. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1187. return AppMinimized || MainFormMinimized;
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1191. {
  1192. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1193. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1194. bool Result = (Cmd == SC_MINIMIZE);
  1195. if (Result)
  1196. {
  1197. ApplicationMinimize();
  1198. SysCommand.Result = 1;
  1199. }
  1200. return Result;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. void __fastcall WinInitialize()
  1204. {
  1205. if (JclHookExceptions())
  1206. {
  1207. JclStackTrackingOptions << stAllModules;
  1208. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1209. }
  1210. SetErrorMode(SEM_FAILCRITICALERRORS);
  1211. OnApiPath = ApiPath;
  1212. MainThread = GetCurrentThreadId();
  1213. #pragma warn -8111
  1214. #pragma warn .8111
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. void __fastcall WinFinalize()
  1218. {
  1219. JclRemoveExceptNotifier(DoExceptNotify);
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1223. {
  1224. FVisible = false;
  1225. FOnClick = NULL;
  1226. FOnBalloonClick = NULL;
  1227. FBalloonUserData = NULL;
  1228. FTrayIcon = new NOTIFYICONDATA;
  1229. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1230. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1231. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1232. // LoadIconMetric is available from Windows Vista only
  1233. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1234. if (DebugAlwaysTrue(ComCtl32Dll))
  1235. {
  1236. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1237. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1238. if (LoadIconMetric != NULL)
  1239. {
  1240. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1241. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1242. }
  1243. }
  1244. if (FTrayIcon->hIcon == 0)
  1245. {
  1246. FTrayIcon->hIcon = Application->Icon->Handle;
  1247. }
  1248. FTrayIcon->uID = Id;
  1249. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1250. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1251. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. __fastcall ::TTrayIcon::~TTrayIcon()
  1255. {
  1256. // make sure we hide icon even in case it was shown just to pop up the balloon
  1257. // (in which case Visible == false)
  1258. CancelBalloon();
  1259. Visible = false;
  1260. DeallocateHWnd(FTrayIcon->hWnd);
  1261. delete FTrayIcon;
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1265. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1266. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1267. {
  1268. if (Timeout > 30000)
  1269. {
  1270. // this is probably system limit, do not try more, especially for
  1271. // the timeout-driven hiding of the tray icon (for Win2k)
  1272. Timeout = 30000;
  1273. }
  1274. FTrayIcon->uFlags |= NIF_INFO;
  1275. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1276. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1277. UnicodeString Info = Str;
  1278. // When szInfo is empty, balloon is not shown
  1279. // (or actually it means the balloon should be deleted, if any)
  1280. if (Info.IsEmpty())
  1281. {
  1282. Info = L" ";
  1283. }
  1284. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1285. FTrayIcon->uTimeout = Timeout;
  1286. switch (QueryType)
  1287. {
  1288. case qtError:
  1289. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1290. break;
  1291. case qtInformation:
  1292. case qtConfirmation:
  1293. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1294. break;
  1295. case qtWarning:
  1296. default:
  1297. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1298. break;
  1299. }
  1300. KillTimer(FTrayIcon->hWnd, 1);
  1301. if (Visible)
  1302. {
  1303. Update();
  1304. }
  1305. else
  1306. {
  1307. Notify(NIM_ADD);
  1308. }
  1309. FOnBalloonClick = OnBalloonClick;
  1310. delete FBalloonUserData;
  1311. FBalloonUserData = BalloonUserData;
  1312. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1313. // unless CancelBalloon is called explicitly
  1314. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1315. }
  1316. //---------------------------------------------------------------------------
  1317. void __fastcall ::TTrayIcon::BalloonCancelled()
  1318. {
  1319. FOnBalloonClick = NULL;
  1320. delete FBalloonUserData;
  1321. FBalloonUserData = NULL;
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. void __fastcall ::TTrayIcon::CancelBalloon()
  1325. {
  1326. KillTimer(FTrayIcon->hWnd, 1);
  1327. if (Visible)
  1328. {
  1329. FTrayIcon->uFlags |= NIF_INFO;
  1330. FTrayIcon->szInfo[0] = L'\0';
  1331. Update();
  1332. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1333. }
  1334. else
  1335. {
  1336. Notify(NIM_DELETE);
  1337. }
  1338. BalloonCancelled();
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1342. {
  1343. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1344. if (Result && (Message == NIM_ADD))
  1345. {
  1346. UINT Timeout = FTrayIcon->uTimeout;
  1347. try
  1348. {
  1349. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1350. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1351. }
  1352. __finally
  1353. {
  1354. FTrayIcon->uTimeout = Timeout;
  1355. }
  1356. }
  1357. return Result;
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall ::TTrayIcon::Update()
  1361. {
  1362. if (Visible)
  1363. {
  1364. Notify(NIM_MODIFY);
  1365. }
  1366. }
  1367. //---------------------------------------------------------------------------
  1368. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1369. {
  1370. if (Visible != value)
  1371. {
  1372. if (value)
  1373. {
  1374. FVisible = Notify(NIM_ADD);
  1375. }
  1376. else
  1377. {
  1378. FVisible = false;
  1379. KillTimer(FTrayIcon->hWnd, 1);
  1380. Notify(NIM_DELETE);
  1381. BalloonCancelled();
  1382. }
  1383. }
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1387. {
  1388. try
  1389. {
  1390. if (Message.Msg == WM_TRAY_ICON)
  1391. {
  1392. DebugAssert(Message.WParam == 0);
  1393. switch (Message.LParam)
  1394. {
  1395. // old shell32
  1396. case WM_LBUTTONUP:
  1397. case WM_RBUTTONUP:
  1398. // new shell32:
  1399. case WM_CONTEXTMENU:
  1400. if (OnClick != NULL)
  1401. {
  1402. OnClick(NULL);
  1403. }
  1404. Message.Result = true;
  1405. break;
  1406. }
  1407. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1408. {
  1409. if (FOnBalloonClick != NULL)
  1410. {
  1411. // prevent the user data from being freed by possible call
  1412. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1413. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1414. FBalloonUserData = NULL;
  1415. FOnBalloonClick(UserData.get());
  1416. }
  1417. else if (OnClick != NULL)
  1418. {
  1419. OnClick(NULL);
  1420. }
  1421. }
  1422. switch (Message.LParam)
  1423. {
  1424. case NIN_BALLOONHIDE:
  1425. case NIN_BALLOONTIMEOUT:
  1426. case NIN_BALLOONUSERCLICK:
  1427. KillTimer(FTrayIcon->hWnd, 1);
  1428. // if icon was shown just to display balloon, hide it with the balloon
  1429. if (!Visible)
  1430. {
  1431. Notify(NIM_DELETE);
  1432. }
  1433. BalloonCancelled();
  1434. break;
  1435. }
  1436. }
  1437. else if (Message.Msg == WM_TIMER)
  1438. {
  1439. // sanity check
  1440. Notify(NIM_DELETE);
  1441. BalloonCancelled();
  1442. }
  1443. else if (Message.Msg == FTaskbarCreatedMsg)
  1444. {
  1445. if (Visible)
  1446. {
  1447. // force recreation
  1448. Visible = false;
  1449. Visible = true;
  1450. }
  1451. }
  1452. else
  1453. {
  1454. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1455. }
  1456. }
  1457. catch(Exception & E)
  1458. {
  1459. Application->HandleException(&E);
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1464. {
  1465. return FTrayIcon->szTip;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1469. {
  1470. if (Hint != value)
  1471. {
  1472. unsigned int Max = LENOF(FTrayIcon->szTip);
  1473. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1474. Update();
  1475. }
  1476. }
  1477. //---------------------------------------------------------------------------