WinInterface.cpp 46 KB

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