1
0

WinInterface.cpp 45 KB

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