WinInterface.cpp 45 KB

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