WinInterface.cpp 48 KB

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