WinInterface.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  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. //---------------------------------------------------------------------------
  616. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  617. bool OSException, void * BaseOfStack)
  618. {
  619. if (ExceptObj != NULL)
  620. {
  621. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  622. if ((E != NULL) && IsInternalException(E)) // optimization
  623. {
  624. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  625. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  626. if (DebugAlwaysTrue(StackInfoList != NULL))
  627. {
  628. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  629. DWORD ThreadID = GetCurrentThreadId();
  630. TGuard Guard(StackTraceCriticalSection.get());
  631. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  632. if (Iterator != StackTraceMap.end())
  633. {
  634. Iterator->second->Add(L"");
  635. Iterator->second->AddStrings(StackTrace.get());
  636. }
  637. else
  638. {
  639. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  640. }
  641. // this chains so that JclLastExceptStackList() returns NULL the next time
  642. // for the current thread
  643. delete StackInfoList;
  644. }
  645. }
  646. }
  647. }
  648. //---------------------------------------------------------------------------
  649. void * __fastcall BusyStart()
  650. {
  651. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  652. Screen->Cursor = crHourGlass;
  653. return Token;
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall BusyEnd(void * Token)
  657. {
  658. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  659. }
  660. //---------------------------------------------------------------------------
  661. //---------------------------------------------------------------------------
  662. static DWORD MainThread = 0;
  663. static TDateTime LastGUIUpdate = 0;
  664. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  665. static bool NoGUI = false;
  666. //---------------------------------------------------------------------------
  667. void __fastcall SetNoGUI()
  668. {
  669. NoGUI = true;
  670. }
  671. //---------------------------------------------------------------------------
  672. bool __fastcall ProcessGUI(bool Force)
  673. {
  674. DebugAssert(MainThread != 0);
  675. bool Result = false;
  676. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  677. // As we do not really need to call it in scripting/.NET, just skip it.
  678. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  679. {
  680. TDateTime N = Now();
  681. if (Force ||
  682. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  683. {
  684. LastGUIUpdate = N;
  685. Application->ProcessMessages();
  686. Result = true;
  687. }
  688. }
  689. return Result;
  690. }
  691. //---------------------------------------------------------------------------
  692. void __fastcall CopyParamListButton(TButton * Button)
  693. {
  694. if (!SupportsSplitButton())
  695. {
  696. MenuButton(Button);
  697. }
  698. }
  699. //---------------------------------------------------------------------------
  700. const int cpiDefault = -1;
  701. const int cpiConfigure = -2;
  702. const int cpiCustom = -3;
  703. const int cpiSaveSettings = -4;
  704. const int cpiGenerateCode = -5;
  705. //---------------------------------------------------------------------------
  706. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  707. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  708. int Options, int CopyParamAttrs, bool SaveSettings)
  709. {
  710. Menu->Items->Clear();
  711. TMenuItem * CustomizeItem = NULL;
  712. TMenuItem * Item;
  713. if (FLAGSET(Options, cplCustomize))
  714. {
  715. Item = new TMenuItem(Menu);
  716. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  717. Item->Tag = cpiCustom;
  718. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  719. Item->OnClick = OnClick;
  720. Menu->Items->Add(Item);
  721. CustomizeItem = Item;
  722. }
  723. if (FLAGSET(Options, cplSaveSettings))
  724. {
  725. Item = new TMenuItem(Menu);
  726. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  727. Item->Tag = cpiSaveSettings;
  728. Item->Checked = SaveSettings;
  729. Item->OnClick = OnClick;
  730. Menu->Items->Add(Item);
  731. }
  732. Item = new TMenuItem(Menu);
  733. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  734. Item->Visible = false;
  735. Item->Enabled = false;
  736. Menu->Items->Add(Item);
  737. bool AnyChecked = false;
  738. Item = new TMenuItem(Menu);
  739. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  740. Item->Tag = cpiDefault;
  741. Item->Checked =
  742. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  743. AnyChecked = AnyChecked || Item->Checked;
  744. Item->OnClick = OnClick;
  745. Menu->Items->Add(Item);
  746. TCopyParamType DefaultParam;
  747. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  748. for (int i = 0; i < CopyParamList->Count; i++)
  749. {
  750. UnicodeString Name = CopyParamList->Names[i];
  751. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  752. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  753. // This makes "Binary" preset visible,
  754. // as long as we care about transfer mode
  755. ((AParam == DefaultParam) &&
  756. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  757. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  758. {
  759. Item = new TMenuItem(Menu);
  760. Item->Caption = Name;
  761. Item->Tag = i;
  762. Item->Checked =
  763. (Preset == Name) && (AParam == Param);
  764. AnyChecked = AnyChecked || Item->Checked;
  765. Item->OnClick = OnClick;
  766. Menu->Items->Add(Item);
  767. }
  768. }
  769. if (CustomizeItem != NULL)
  770. {
  771. CustomizeItem->Checked = !AnyChecked;
  772. }
  773. Item = new TMenuItem(Menu);
  774. Item->Caption = L"-";
  775. Menu->Items->Add(Item);
  776. Item = new TMenuItem(Menu);
  777. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  778. Item->Tag = cpiConfigure;
  779. Item->OnClick = OnClick;
  780. Menu->Items->Add(Item);
  781. if (FLAGSET(Options, cplGenerateCode))
  782. {
  783. Item = new TMenuItem(Menu);
  784. Item->Caption = L"-";
  785. Menu->Items->Add(Item);
  786. Item = new TMenuItem(Menu);
  787. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  788. Item->Tag = cpiGenerateCode;
  789. Item->OnClick = OnClick;
  790. Menu->Items->Add(Item);
  791. }
  792. MenuPopup(Menu, Rect, NULL);
  793. }
  794. //---------------------------------------------------------------------------
  795. int __fastcall CopyParamListPopupClick(TObject * Sender,
  796. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  797. bool * SaveSettings)
  798. {
  799. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  800. DebugAssert(Item != NULL);
  801. DebugAssert((Item->Tag >= cpiGenerateCode) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  802. int Result;
  803. if (Item->Tag == cpiConfigure)
  804. {
  805. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  806. DoPreferencesDialog(pmPresets);
  807. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  808. if (Result > 0)
  809. {
  810. // For cast, see a comment below
  811. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  812. }
  813. }
  814. else if (Item->Tag == cpiCustom)
  815. {
  816. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  817. }
  818. else if (Item->Tag == cpiSaveSettings)
  819. {
  820. if (DebugAlwaysTrue(SaveSettings != NULL))
  821. {
  822. *SaveSettings = !*SaveSettings;
  823. }
  824. Result = 0;
  825. }
  826. else if (Item->Tag == cpiGenerateCode)
  827. {
  828. Result = -cplGenerateCode;
  829. }
  830. else
  831. {
  832. Preset = (Item->Tag >= 0) ?
  833. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  834. // The cast strips away the "queue" properties of the TGUICopyParamType
  835. // that are not configurable in presets
  836. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  837. Result = 1;
  838. }
  839. return Result;
  840. }
  841. //---------------------------------------------------------------------------
  842. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  843. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  844. TInteractiveCustomCommand(ChildCustomCommand)
  845. {
  846. FCustomCommandName = StripHotkey(CustomCommandName);
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TWinInteractiveCustomCommand::Prompt(
  850. const UnicodeString & Prompt, UnicodeString & Value)
  851. {
  852. UnicodeString APrompt = Prompt;
  853. if (APrompt.IsEmpty())
  854. {
  855. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  856. }
  857. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"CustomCommandParam"]));
  858. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  859. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History.get()))
  860. {
  861. CustomWinConfiguration->History[L"CustomCommandParam"] = History.get();
  862. }
  863. else
  864. {
  865. Abort();
  866. }
  867. }
  868. //---------------------------------------------------------------------------
  869. void __fastcall TWinInteractiveCustomCommand::Execute(
  870. const UnicodeString & Command, UnicodeString & Value)
  871. {
  872. // inspired by
  873. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  874. HANDLE StdOutOutput;
  875. HANDLE StdOutInput;
  876. HANDLE StdInOutput;
  877. HANDLE StdInInput;
  878. SECURITY_ATTRIBUTES SecurityAttributes;
  879. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  880. SecurityAttributes.lpSecurityDescriptor = NULL;
  881. SecurityAttributes.bInheritHandle = TRUE;
  882. try
  883. {
  884. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  885. {
  886. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  887. }
  888. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  889. {
  890. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  891. }
  892. else
  893. {
  894. STARTUPINFO StartupInfo;
  895. PROCESS_INFORMATION ProcessInformation;
  896. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  897. StartupInfo.cb = sizeof(StartupInfo);
  898. StartupInfo.wShowWindow = SW_HIDE;
  899. StartupInfo.hStdInput = StdInOutput;
  900. StartupInfo.hStdOutput = StdOutInput;
  901. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  902. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  903. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  904. {
  905. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  906. }
  907. else
  908. {
  909. try
  910. {
  911. // wait until the console program terminated
  912. bool Running = true;
  913. while (Running)
  914. {
  915. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  916. {
  917. case WAIT_TIMEOUT:
  918. Application->ProcessMessages();
  919. break;
  920. case WAIT_OBJECT_0:
  921. Running = false;
  922. break;
  923. default:
  924. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  925. }
  926. }
  927. char Buffer[1024];
  928. unsigned long Read;
  929. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  930. (Read > 0))
  931. {
  932. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  933. {
  934. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  935. }
  936. else if (Read > 0)
  937. {
  938. Value += AnsiToString(Buffer, Read);
  939. }
  940. }
  941. // trim trailing cr/lf
  942. Value = TrimRight(Value);
  943. }
  944. __finally
  945. {
  946. CloseHandle(ProcessInformation.hProcess);
  947. CloseHandle(ProcessInformation.hThread);
  948. }
  949. }
  950. }
  951. }
  952. __finally
  953. {
  954. if (StdOutOutput != INVALID_HANDLE_VALUE)
  955. {
  956. CloseHandle(StdOutOutput);
  957. }
  958. if (StdOutInput != INVALID_HANDLE_VALUE)
  959. {
  960. CloseHandle(StdOutInput);
  961. }
  962. if (StdInOutput != INVALID_HANDLE_VALUE)
  963. {
  964. CloseHandle(StdInOutput);
  965. }
  966. if (StdInInput != INVALID_HANDLE_VALUE)
  967. {
  968. CloseHandle(StdInInput);
  969. }
  970. }
  971. }
  972. //---------------------------------------------------------------------------
  973. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  974. {
  975. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  976. }
  977. //---------------------------------------------------------------------------
  978. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  979. {
  980. TControl * Control = dynamic_cast<TControl *>(Sender);
  981. DebugAssert(Control != NULL);
  982. TPoint Point;
  983. if ((MousePos.x == -1) && (MousePos.y == -1))
  984. {
  985. Point = Control->ClientToScreen(TPoint(0, 0));
  986. }
  987. else
  988. {
  989. Point = Control->ClientToScreen(MousePos);
  990. }
  991. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  992. DebugAssert(PopupMenu != NULL);
  993. TRect Rect(Point, Point);
  994. MenuPopup(PopupMenu, Rect, Control);
  995. Handled = true;
  996. }
  997. //---------------------------------------------------------------------------
  998. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  999. {
  1000. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1001. DebugAssert(Item != NULL);
  1002. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1003. DebugAssert(PopupMenu != NULL);
  1004. DebugAssert(PopupMenu->PopupComponent != NULL);
  1005. return PopupMenu->PopupComponent;
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall MenuButton(TButton * Button)
  1009. {
  1010. Button->Images = GlyphsModule->ButtonImages;
  1011. Button->ImageIndex = 0;
  1012. Button->DisabledImageIndex = 1;
  1013. Button->ImageAlignment = iaRight;
  1014. }
  1015. //---------------------------------------------------------------------------
  1016. TRect __fastcall CalculatePopupRect(TButton * Button)
  1017. {
  1018. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1019. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1020. TRect Rect(UpPoint, DownPoint);
  1021. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1022. int Offset = UseThemes() ? -1 : 0;
  1023. Rect.Inflate(Offset, Offset);
  1024. return Rect;
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1028. {
  1029. MousePos = Control->ClientToScreen(MousePos);
  1030. TRect Rect(MousePos, MousePos);
  1031. return Rect;
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall FixButtonImage(TButton * Button)
  1035. {
  1036. // with themes enabled, button image is by default drawn too high
  1037. if (UseThemes())
  1038. {
  1039. Button->ImageMargins->Top = 1;
  1040. }
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall CenterButtonImage(TButton * Button)
  1044. {
  1045. // with themes disabled, the text seems to be drawn over the icon,
  1046. // so that the padding spaces hide away most of the icon
  1047. if (UseThemes())
  1048. {
  1049. Button->ImageAlignment = iaCenter;
  1050. int ImageWidth = Button->Images->Width;
  1051. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  1052. Canvas->Control = Button;
  1053. UnicodeString Caption = Button->Caption;
  1054. UnicodeString Padding;
  1055. while (Canvas->TextWidth(Padding) < ImageWidth)
  1056. {
  1057. Padding += L" ";
  1058. }
  1059. if (Button->IsRightToLeft())
  1060. {
  1061. Caption = Caption + Padding;
  1062. }
  1063. else
  1064. {
  1065. Caption = Padding + Caption;
  1066. }
  1067. Button->Caption = Caption;
  1068. int CaptionWidth = Canvas->TextWidth(Caption);
  1069. // The margins seem to extend the area over which the image is centered,
  1070. // so we have to set it to a double of desired padding.
  1071. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1072. // the one below is equivalent, but with reduced rouding.
  1073. // Without the change, the rouding caused the space between icon and caption too
  1074. // small on 200% zoom.
  1075. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1076. // is approximatelly same as half of caption width before padding.
  1077. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1078. }
  1079. else
  1080. {
  1081. // at least do not draw it so near to the edge
  1082. Button->ImageMargins->Left = 1;
  1083. }
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1087. {
  1088. int Result = !S.IsEmpty() && StrToInt(S);
  1089. switch (LocaleFlagOverride)
  1090. {
  1091. default:
  1092. case lfoLanguageIfRecommended:
  1093. if (!Recommended)
  1094. {
  1095. Result = Off;
  1096. }
  1097. break;
  1098. case lfoLanguage:
  1099. // noop = as configured in locale
  1100. break;
  1101. case lfoAlways:
  1102. Result = On;
  1103. break;
  1104. case lfoNever:
  1105. Result = Off;
  1106. break;
  1107. }
  1108. return Result;
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1112. {
  1113. if (GlobalOnMinimize == NULL)
  1114. {
  1115. GlobalOnMinimize = OnMinimize;
  1116. }
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1120. {
  1121. if (GlobalOnMinimize == OnMinimize)
  1122. {
  1123. GlobalOnMinimize = NULL;
  1124. }
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1128. {
  1129. Configuration->Usage->Inc(L"OperationMinimizations");
  1130. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1131. {
  1132. GlobalOnMinimize(Sender);
  1133. }
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1137. {
  1138. // WORKAROUND
  1139. // When main window is hidden (command-line operation),
  1140. // we do not want it to be shown by TApplication.Restore,
  1141. // so we temporarily detach it from an application.
  1142. // Probably not really necessary for minimizing phase,
  1143. // but we do it for consistency anyway.
  1144. TForm * MainForm = Application->MainForm;
  1145. bool RestoreMainForm = false;
  1146. if (DebugAlwaysTrue(MainForm != NULL) &&
  1147. !MainForm->Visible)
  1148. {
  1149. SetAppMainForm(NULL);
  1150. RestoreMainForm = true;
  1151. }
  1152. try
  1153. {
  1154. if (Minimize)
  1155. {
  1156. Application->Minimize();
  1157. }
  1158. else
  1159. {
  1160. Application->Restore();
  1161. }
  1162. }
  1163. __finally
  1164. {
  1165. if (RestoreMainForm)
  1166. {
  1167. SetAppMainForm(MainForm);
  1168. }
  1169. }
  1170. }
  1171. //---------------------------------------------------------------------------
  1172. void __fastcall ApplicationMinimize()
  1173. {
  1174. DoApplicationMinimizeRestore(true);
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. void __fastcall ApplicationRestore()
  1178. {
  1179. DoApplicationMinimizeRestore(false);
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. bool __fastcall IsApplicationMinimized()
  1183. {
  1184. // VCL help recommends handling Application->OnMinimize/OnRestore
  1185. // for tracking state, but OnRestore is actually not called
  1186. // (OnMinimize is), when app is minimized from e.g. Progress window
  1187. bool AppMinimized = IsIconic(Application->Handle);
  1188. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1189. return AppMinimized || MainFormMinimized;
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1193. {
  1194. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1195. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1196. bool Result = (Cmd == SC_MINIMIZE);
  1197. if (Result)
  1198. {
  1199. ApplicationMinimize();
  1200. SysCommand.Result = 1;
  1201. }
  1202. return Result;
  1203. }
  1204. //---------------------------------------------------------------------------
  1205. void __fastcall WinInitialize()
  1206. {
  1207. if (JclHookExceptions())
  1208. {
  1209. JclStackTrackingOptions << stAllModules;
  1210. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1211. }
  1212. SetErrorMode(SEM_FAILCRITICALERRORS);
  1213. OnApiPath = ApiPath;
  1214. MainThread = GetCurrentThreadId();
  1215. #pragma warn -8111
  1216. #pragma warn .8111
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. void __fastcall WinFinalize()
  1220. {
  1221. JclRemoveExceptNotifier(DoExceptNotify);
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1225. {
  1226. FVisible = false;
  1227. FOnClick = NULL;
  1228. FOnBalloonClick = NULL;
  1229. FBalloonUserData = NULL;
  1230. FTrayIcon = new NOTIFYICONDATA;
  1231. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1232. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1233. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1234. // LoadIconMetric is available from Windows Vista only
  1235. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1236. if (DebugAlwaysTrue(ComCtl32Dll))
  1237. {
  1238. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1239. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1240. if (LoadIconMetric != NULL)
  1241. {
  1242. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1243. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1244. }
  1245. }
  1246. if (FTrayIcon->hIcon == 0)
  1247. {
  1248. FTrayIcon->hIcon = Application->Icon->Handle;
  1249. }
  1250. FTrayIcon->uID = Id;
  1251. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1252. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1253. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. __fastcall ::TTrayIcon::~TTrayIcon()
  1257. {
  1258. // make sure we hide icon even in case it was shown just to pop up the balloon
  1259. // (in which case Visible == false)
  1260. CancelBalloon();
  1261. Visible = false;
  1262. DeallocateHWnd(FTrayIcon->hWnd);
  1263. delete FTrayIcon;
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1267. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1268. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1269. {
  1270. if (Timeout > 30000)
  1271. {
  1272. // this is probably system limit, do not try more, especially for
  1273. // the timeout-driven hiding of the tray icon (for Win2k)
  1274. Timeout = 30000;
  1275. }
  1276. FTrayIcon->uFlags |= NIF_INFO;
  1277. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1278. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1279. UnicodeString Info = Str;
  1280. // When szInfo is empty, balloon is not shown
  1281. // (or actually it means the balloon should be deleted, if any)
  1282. if (Info.IsEmpty())
  1283. {
  1284. Info = L" ";
  1285. }
  1286. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1287. FTrayIcon->uTimeout = Timeout;
  1288. switch (QueryType)
  1289. {
  1290. case qtError:
  1291. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1292. break;
  1293. case qtInformation:
  1294. case qtConfirmation:
  1295. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1296. break;
  1297. case qtWarning:
  1298. default:
  1299. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1300. break;
  1301. }
  1302. KillTimer(FTrayIcon->hWnd, 1);
  1303. if (Visible)
  1304. {
  1305. Update();
  1306. }
  1307. else
  1308. {
  1309. Notify(NIM_ADD);
  1310. }
  1311. FOnBalloonClick = OnBalloonClick;
  1312. delete FBalloonUserData;
  1313. FBalloonUserData = BalloonUserData;
  1314. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1315. // unless CancelBalloon is called explicitly
  1316. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void __fastcall ::TTrayIcon::BalloonCancelled()
  1320. {
  1321. FOnBalloonClick = NULL;
  1322. delete FBalloonUserData;
  1323. FBalloonUserData = NULL;
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. void __fastcall ::TTrayIcon::CancelBalloon()
  1327. {
  1328. KillTimer(FTrayIcon->hWnd, 1);
  1329. if (Visible)
  1330. {
  1331. FTrayIcon->uFlags |= NIF_INFO;
  1332. FTrayIcon->szInfo[0] = L'\0';
  1333. Update();
  1334. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1335. }
  1336. else
  1337. {
  1338. Notify(NIM_DELETE);
  1339. }
  1340. BalloonCancelled();
  1341. }
  1342. //---------------------------------------------------------------------------
  1343. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1344. {
  1345. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1346. if (Result && (Message == NIM_ADD))
  1347. {
  1348. UINT Timeout = FTrayIcon->uTimeout;
  1349. try
  1350. {
  1351. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1352. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1353. }
  1354. __finally
  1355. {
  1356. FTrayIcon->uTimeout = Timeout;
  1357. }
  1358. }
  1359. return Result;
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. void __fastcall ::TTrayIcon::Update()
  1363. {
  1364. if (Visible)
  1365. {
  1366. Notify(NIM_MODIFY);
  1367. }
  1368. }
  1369. //---------------------------------------------------------------------------
  1370. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1371. {
  1372. if (Visible != value)
  1373. {
  1374. if (value)
  1375. {
  1376. FVisible = Notify(NIM_ADD);
  1377. }
  1378. else
  1379. {
  1380. FVisible = false;
  1381. KillTimer(FTrayIcon->hWnd, 1);
  1382. Notify(NIM_DELETE);
  1383. BalloonCancelled();
  1384. }
  1385. }
  1386. }
  1387. //---------------------------------------------------------------------------
  1388. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1389. {
  1390. try
  1391. {
  1392. if (Message.Msg == WM_TRAY_ICON)
  1393. {
  1394. DebugAssert(Message.WParam == 0);
  1395. switch (Message.LParam)
  1396. {
  1397. // old shell32
  1398. case WM_LBUTTONUP:
  1399. case WM_RBUTTONUP:
  1400. // new shell32:
  1401. case WM_CONTEXTMENU:
  1402. if (OnClick != NULL)
  1403. {
  1404. OnClick(NULL);
  1405. }
  1406. Message.Result = true;
  1407. break;
  1408. }
  1409. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1410. {
  1411. if (FOnBalloonClick != NULL)
  1412. {
  1413. // prevent the user data from being freed by possible call
  1414. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1415. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1416. FBalloonUserData = NULL;
  1417. FOnBalloonClick(UserData.get());
  1418. }
  1419. else if (OnClick != NULL)
  1420. {
  1421. OnClick(NULL);
  1422. }
  1423. }
  1424. switch (Message.LParam)
  1425. {
  1426. case NIN_BALLOONHIDE:
  1427. case NIN_BALLOONTIMEOUT:
  1428. case NIN_BALLOONUSERCLICK:
  1429. KillTimer(FTrayIcon->hWnd, 1);
  1430. // if icon was shown just to display balloon, hide it with the balloon
  1431. if (!Visible)
  1432. {
  1433. Notify(NIM_DELETE);
  1434. }
  1435. BalloonCancelled();
  1436. break;
  1437. }
  1438. }
  1439. else if (Message.Msg == WM_TIMER)
  1440. {
  1441. // sanity check
  1442. Notify(NIM_DELETE);
  1443. BalloonCancelled();
  1444. }
  1445. else if (Message.Msg == FTaskbarCreatedMsg)
  1446. {
  1447. if (Visible)
  1448. {
  1449. // force recreation
  1450. Visible = false;
  1451. Visible = true;
  1452. }
  1453. }
  1454. else
  1455. {
  1456. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1457. }
  1458. }
  1459. catch(Exception & E)
  1460. {
  1461. Application->HandleException(&E);
  1462. }
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1466. {
  1467. return FTrayIcon->szTip;
  1468. }
  1469. //---------------------------------------------------------------------------
  1470. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1471. {
  1472. if (Hint != value)
  1473. {
  1474. unsigned int Max = LENOF(FTrayIcon->szTip);
  1475. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1476. Update();
  1477. }
  1478. }
  1479. //---------------------------------------------------------------------------