WinInterface.cpp 49 KB

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