WinInterface.cpp 47 KB

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