WinInterface.cpp 49 KB

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