WinInterface.cpp 44 KB

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