WinInterface.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlwapi.h>
  5. #include <Common.h>
  6. #include <Queue.h>
  7. #include <Exceptions.h>
  8. #include <CoreMain.h>
  9. #include <TextsCore.h>
  10. #include <TextsWin.h>
  11. #include <HelpWin.h>
  12. #include <HelpCore.h>
  13. #include <Interface.h>
  14. #include <VCLCommon.h>
  15. #include <Glyphs.h>
  16. #include <PasTools.hpp>
  17. #include <DateUtils.hpp>
  18. #include <Custom.h>
  19. #include <HistoryComboBox.hpp>
  20. #include "WinInterface.h"
  21. #include "GUITools.h"
  22. #include "JclDebug.hpp"
  23. #include "JclHookExcept.hpp"
  24. #include <System.IOUtils.hpp>
  25. #include <StrUtils.hpp>
  26. #include <WinApi.h>
  27. #include "Tools.h"
  28. #include <Vcl.AppEvnts.hpp>
  29. //---------------------------------------------------------------------------
  30. #pragma package(smart_init)
  31. //---------------------------------------------------------------------------
  32. #define WM_TRAY_ICON (WM_WINSCP_USER + 5)
  33. //---------------------------------------------------------------------
  34. TNotifyEvent GlobalOnMinimize = NULL;
  35. //---------------------------------------------------------------------
  36. const IID IID_IListView_Win7 = {0xE5B16AF2, 0x3990, 0x4681, {0xA6, 0x09, 0x1F, 0x06, 0x0C, 0xD1, 0x42, 0x69}};
  37. //---------------------------------------------------------------------
  38. void __fastcall FormHelp(TCustomForm * Form)
  39. {
  40. InvokeHelp(Form->ActiveControl != NULL ? Form->ActiveControl : Form);
  41. }
  42. //---------------------------------------------------------------------------
  43. TMessageParams::TMessageParams(unsigned int AParams)
  44. {
  45. Reset();
  46. Params = AParams;
  47. }
  48. //---------------------------------------------------------------------------
  49. TMessageParams::TMessageParams(const TQueryParams * AParams)
  50. {
  51. Reset();
  52. if (AParams != NULL)
  53. {
  54. Aliases = AParams->Aliases;
  55. AliasesCount = AParams->AliasesCount;
  56. Timer = AParams->Timer;
  57. TimerEvent = AParams->TimerEvent;
  58. TimerMessage = AParams->TimerMessage;
  59. TimerAnswers = AParams->TimerAnswers;
  60. TimerQueryType = AParams->TimerQueryType;
  61. Timeout = AParams->Timeout;
  62. TimeoutAnswer = AParams->TimeoutAnswer;
  63. TimeoutResponse = AParams->TimeoutResponse;
  64. if (FLAGSET(AParams->Params, qpNeverAskAgainCheck))
  65. {
  66. Params |= mpNeverAskAgainCheck;
  67. }
  68. if (FLAGSET(AParams->Params, qpAllowContinueOnError))
  69. {
  70. Params |= mpAllowContinueOnError;
  71. }
  72. }
  73. }
  74. //---------------------------------------------------------------------------
  75. inline void TMessageParams::Reset()
  76. {
  77. Params = 0;
  78. Aliases = NULL;
  79. AliasesCount = 0;
  80. Timer = 0;
  81. TimerEvent = NULL;
  82. TimerMessage = L"";
  83. TimerAnswers = 0;
  84. TimerQueryType = static_cast<TQueryType>(-1);
  85. Timeout = 0;
  86. TimeoutAnswer = 0;
  87. TimeoutResponse = 0;
  88. NeverAskAgainTitle = L"";
  89. NeverAskAgainAnswer = 0;
  90. NeverAskAgainCheckedInitially = false;
  91. AllowHelp = true;
  92. ImageName = L"";
  93. MoreMessagesUrl = L"";
  94. MoreMessagesSize = TSize();
  95. CustomCaption = L"";
  96. }
  97. //---------------------------------------------------------------------------
  98. static bool __fastcall IsPositiveAnswer(unsigned int Answer)
  99. {
  100. return (Answer == qaYes) || (Answer == qaOK) || (Answer == qaYesToAll);
  101. }
  102. //---------------------------------------------------------------------------
  103. static void __fastcall NeverAskAgainCheckClick(void * /*Data*/, TObject * Sender)
  104. {
  105. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(Sender);
  106. DebugAssert(CheckBox != NULL);
  107. TForm * Dialog = dynamic_cast<TForm *>(CheckBox->Owner);
  108. DebugAssert(Dialog != NULL);
  109. unsigned int PositiveAnswer = 0;
  110. if (CheckBox->Checked)
  111. {
  112. if (CheckBox->Tag > 0)
  113. {
  114. PositiveAnswer = CheckBox->Tag;
  115. }
  116. else
  117. {
  118. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  119. {
  120. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  121. if (Button != NULL)
  122. {
  123. if (IsPositiveAnswer(Button->ModalResult))
  124. {
  125. PositiveAnswer = Button->ModalResult;
  126. break;
  127. }
  128. }
  129. }
  130. }
  131. DebugAssert(PositiveAnswer != 0);
  132. }
  133. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  134. {
  135. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  136. if (Button != NULL)
  137. {
  138. if ((Button->ModalResult != 0) && (Button->ModalResult != static_cast<int>(qaCancel)))
  139. {
  140. Button->Enabled = !CheckBox->Checked || (Button->ModalResult == static_cast<int>(PositiveAnswer));
  141. }
  142. if (Button->DropDownMenu != NULL)
  143. {
  144. for (int iii = 0; iii < Button->DropDownMenu->Items->Count; iii++)
  145. {
  146. TMenuItem * Item = Button->DropDownMenu->Items->Items[iii];
  147. Item->Enabled = Item->Default || !CheckBox->Checked;
  148. }
  149. }
  150. }
  151. }
  152. }
  153. //---------------------------------------------------------------------------
  154. static TCheckBox * __fastcall FindNeverAskAgainCheck(TForm * Dialog)
  155. {
  156. return DebugNotNull(dynamic_cast<TCheckBox *>(Dialog->FindComponent(L"NeverAskAgainCheck")));
  157. }
  158. //---------------------------------------------------------------------------
  159. TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg,
  160. TStrings * MoreMessages, TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword,
  161. const TMessageParams * Params, TButton *& TimeoutButton)
  162. {
  163. TMsgDlgType DlgType;
  164. switch (Type) {
  165. case qtConfirmation: DlgType = mtConfirmation; break;
  166. case qtInformation: DlgType = mtInformation; break;
  167. case qtError: DlgType = mtError; break;
  168. case qtWarning: DlgType = mtWarning; break;
  169. default: DebugFail();
  170. }
  171. unsigned int TimeoutAnswer = (Params != NULL) ? Params->TimeoutAnswer : 0;
  172. unsigned int ActualAnswers = Answers;
  173. if ((Params == NULL) || Params->AllowHelp)
  174. {
  175. Answers = Answers | qaHelp;
  176. }
  177. if (IsInternalErrorHelpKeyword(HelpKeyword))
  178. {
  179. Answers = Answers | qaReport;
  180. }
  181. if ((MoreMessages != NULL) && (MoreMessages->Count == 0))
  182. {
  183. MoreMessages = NULL;
  184. }
  185. UnicodeString ImageName;
  186. UnicodeString MoreMessagesUrl;
  187. TSize MoreMessagesSize;
  188. UnicodeString CustomCaption;
  189. if (Params != NULL)
  190. {
  191. ImageName = Params->ImageName;
  192. MoreMessagesUrl = Params->MoreMessagesUrl;
  193. MoreMessagesSize = Params->MoreMessagesSize;
  194. CustomCaption = Params->CustomCaption;
  195. }
  196. const TQueryButtonAlias * Aliases = (Params != NULL) ? Params->Aliases : NULL;
  197. unsigned int AliasesCount = (Params != NULL) ? Params->AliasesCount : 0;
  198. UnicodeString NeverAskAgainCaption;
  199. bool HasNeverAskAgain = (Params != NULL) && FLAGSET(Params->Params, mpNeverAskAgainCheck);
  200. if (HasNeverAskAgain)
  201. {
  202. NeverAskAgainCaption =
  203. !Params->NeverAskAgainTitle.IsEmpty() ?
  204. (UnicodeString)Params->NeverAskAgainTitle :
  205. // qaOK | qaIgnore is used, when custom "non-answer" button is required
  206. LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ?
  207. NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN);
  208. }
  209. TForm * Dialog = CreateMoreMessageDialog(Msg, MoreMessages, DlgType, Answers,
  210. Aliases, AliasesCount, TimeoutAnswer, &TimeoutButton, ImageName, NeverAskAgainCaption,
  211. MoreMessagesUrl, MoreMessagesSize, CustomCaption);
  212. try
  213. {
  214. if (HasNeverAskAgain && DebugAlwaysTrue(Params != NULL))
  215. {
  216. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  217. NeverAskAgainCheck->Checked = Params->NeverAskAgainCheckedInitially;
  218. if (Params->NeverAskAgainAnswer > 0)
  219. {
  220. NeverAskAgainCheck->Tag = Params->NeverAskAgainAnswer;
  221. }
  222. TNotifyEvent OnClick;
  223. ((TMethod*)&OnClick)->Code = NeverAskAgainCheckClick;
  224. NeverAskAgainCheck->OnClick = OnClick;
  225. }
  226. Dialog->HelpKeyword = HelpKeyword;
  227. if (FLAGSET(Answers, qaHelp))
  228. {
  229. Dialog->BorderIcons = Dialog->BorderIcons << biHelp;
  230. }
  231. ResetSystemSettings(Dialog);
  232. }
  233. catch(...)
  234. {
  235. delete Dialog;
  236. throw;
  237. }
  238. return Dialog;
  239. }
  240. //---------------------------------------------------------------------------
  241. unsigned int __fastcall ExecuteMessageDialog(TForm * Dialog, unsigned int Answers, const TMessageParams * Params)
  242. {
  243. FlashOnBackground();
  244. unsigned int Answer = Dialog->ShowModal();
  245. // mrCancel is returned always when X button is pressed, despite
  246. // no Cancel button was on the dialog. Find valid "cancel" answer.
  247. // mrNone is returned when Windows session is closing (log off)
  248. if ((Answer == mrCancel) || (Answer == mrNone))
  249. {
  250. Answer = CancelAnswer(Answers);
  251. }
  252. if ((Params != NULL) && (Params->Params & mpNeverAskAgainCheck))
  253. {
  254. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  255. if (NeverAskAgainCheck->Checked)
  256. {
  257. bool PositiveAnswer =
  258. (Params->NeverAskAgainAnswer > 0) ?
  259. (Answer == Params->NeverAskAgainAnswer) :
  260. IsPositiveAnswer(Answer);
  261. if (PositiveAnswer)
  262. {
  263. Answer = qaNeverAskAgain;
  264. }
  265. }
  266. }
  267. return Answer;
  268. }
  269. //---------------------------------------------------------------------------
  270. class TMessageTimer : public TTimer
  271. {
  272. public:
  273. TQueryParamsTimerEvent Event;
  274. TForm * Dialog;
  275. __fastcall TMessageTimer(TComponent * AOwner);
  276. protected:
  277. void __fastcall DoTimer(TObject * Sender);
  278. };
  279. //---------------------------------------------------------------------------
  280. __fastcall TMessageTimer::TMessageTimer(TComponent * AOwner) : TTimer(AOwner)
  281. {
  282. Event = NULL;
  283. OnTimer = DoTimer;
  284. Dialog = NULL;
  285. }
  286. //---------------------------------------------------------------------------
  287. void __fastcall TMessageTimer::DoTimer(TObject * /*Sender*/)
  288. {
  289. if (Event != NULL)
  290. {
  291. unsigned int Result = 0;
  292. Event(Result);
  293. if (Result != 0)
  294. {
  295. Dialog->ModalResult = Result;
  296. }
  297. }
  298. }
  299. //---------------------------------------------------------------------------
  300. class TMessageTimeout : public TTimer
  301. {
  302. public:
  303. __fastcall TMessageTimeout(TComponent * AOwner, unsigned int Timeout, TButton * Button, unsigned int Answer);
  304. protected:
  305. unsigned int FOrigTimeout;
  306. unsigned int FTimeout;
  307. TButton * FButton;
  308. UnicodeString FOrigCaption;
  309. TPoint FOrigCursorPos;
  310. std::unique_ptr<TApplicationEvents> FApplicationEvents;
  311. unsigned int FAnswer;
  312. void __fastcall DoTimer(TObject * Sender);
  313. void __fastcall UpdateButton();
  314. void __fastcall ApplicationMessage(TMsg & Msg, bool & Handled);
  315. void __fastcall MouseMove();
  316. void __fastcall Cancel();
  317. };
  318. //---------------------------------------------------------------------------
  319. __fastcall TMessageTimeout::TMessageTimeout(TComponent * AOwner,
  320. unsigned int Timeout, TButton * Button, unsigned int Answer) :
  321. TTimer(AOwner), FOrigTimeout(Timeout), FTimeout(Timeout), FButton(Button), FAnswer(Answer)
  322. {
  323. OnTimer = DoTimer;
  324. Interval = MSecsPerSec;
  325. FOrigCaption = FButton->Caption;
  326. FOrigCursorPos = Mouse->CursorPos;
  327. FApplicationEvents.reset(new TApplicationEvents(Application));
  328. FApplicationEvents->OnMessage = ApplicationMessage;
  329. UpdateButton();
  330. }
  331. //---------------------------------------------------------------------------
  332. void __fastcall TMessageTimeout::ApplicationMessage(TMsg & Msg, bool & DebugUsedArg(Handled))
  333. {
  334. if (Msg.message == WM_MOUSEMOVE)
  335. {
  336. MouseMove();
  337. }
  338. else if ((Msg.message == WM_LBUTTONDOWN) || (Msg.message == WM_RBUTTONDOWN) ||
  339. (Msg.message == WM_KEYDOWN) || (Msg.message == WM_SYSKEYDOWN))
  340. {
  341. Cancel();
  342. }
  343. }
  344. //---------------------------------------------------------------------------
  345. void __fastcall TMessageTimeout::MouseMove()
  346. {
  347. TPoint CursorPos = Mouse->CursorPos;
  348. int Delta = std::max(std::abs(FOrigCursorPos.X - CursorPos.X), std::abs(FOrigCursorPos.Y - CursorPos.Y));
  349. int Threshold = 8;
  350. if (DebugAlwaysTrue(FButton != NULL))
  351. {
  352. Threshold = ScaleByTextHeight(FButton, Threshold);
  353. }
  354. if (Delta > Threshold)
  355. {
  356. FOrigCursorPos = CursorPos;
  357. const unsigned int SuspendTime = 30 * MSecsPerSec;
  358. FTimeout = std::max(FOrigTimeout, SuspendTime);
  359. UpdateButton();
  360. }
  361. }
  362. //---------------------------------------------------------------------------
  363. void __fastcall TMessageTimeout::Cancel()
  364. {
  365. Enabled = false;
  366. UpdateButton();
  367. }
  368. //---------------------------------------------------------------------------
  369. void __fastcall TMessageTimeout::UpdateButton()
  370. {
  371. DebugAssert(FButton != NULL);
  372. FButton->Caption =
  373. !Enabled ? FOrigCaption : FMTLOAD(TIMEOUT_BUTTON, (FOrigCaption, int(FTimeout / MSecsPerSec)));
  374. }
  375. //---------------------------------------------------------------------------
  376. void __fastcall TMessageTimeout::DoTimer(TObject * /*Sender*/)
  377. {
  378. if (FTimeout <= Interval)
  379. {
  380. DebugAssert(FButton != NULL);
  381. // Needed particularly for "keep up to date" dialog, which does not close on the button click
  382. Enabled = false;
  383. TModalResult PrevModalResult = FButton->ModalResult;
  384. if (FAnswer != 0)
  385. {
  386. FButton->ModalResult = FAnswer;
  387. }
  388. try
  389. {
  390. FButton->Click();
  391. }
  392. __finally
  393. {
  394. FButton->ModalResult = PrevModalResult;
  395. }
  396. }
  397. else
  398. {
  399. FTimeout -= Interval;
  400. UpdateButton();
  401. }
  402. }
  403. //---------------------------------------------------------------------------
  404. void InitiateDialogTimeout(TForm * Dialog, unsigned int Timeout, TButton * Button, unsigned int Answer)
  405. {
  406. TMessageTimeout * MessageTimeout = new TMessageTimeout(Application, Timeout, Button, Answer);
  407. MessageTimeout->Name = L"MessageTimeout";
  408. Dialog->InsertComponent(MessageTimeout);
  409. }
  410. //---------------------------------------------------------------------
  411. class TPublicControl : public TControl
  412. {
  413. friend void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled);
  414. };
  415. //---------------------------------------------------------------------------
  416. // Merge with CreateMessageDialogEx
  417. TForm * __fastcall CreateMoreMessageDialogEx(const UnicodeString Message, TStrings * MoreMessages,
  418. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  419. {
  420. std::unique_ptr<TForm> Dialog;
  421. UnicodeString AMessage = Message;
  422. TMessageTimer * Timer = NULL;
  423. if ((Params != NULL) && (Params->Timer > 0))
  424. {
  425. Timer = new TMessageTimer(Application);
  426. Timer->Interval = Params->Timer;
  427. Timer->Event = Params->TimerEvent;
  428. if (Params->TimerAnswers > 0)
  429. {
  430. Answers = Params->TimerAnswers;
  431. }
  432. if (Params->TimerQueryType >= 0)
  433. {
  434. Type = Params->TimerQueryType;
  435. }
  436. if (!Params->TimerMessage.IsEmpty())
  437. {
  438. AMessage = Params->TimerMessage;
  439. }
  440. Timer->Name = L"MessageTimer";
  441. }
  442. TButton * TimeoutButton = NULL;
  443. Dialog.reset(
  444. CreateMessageDialogEx(
  445. AMessage, MoreMessages, Type, Answers, HelpKeyword, Params, TimeoutButton));
  446. if (Timer != NULL)
  447. {
  448. Timer->Dialog = Dialog.get();
  449. Dialog->InsertComponent(Timer);
  450. }
  451. if (Params != NULL)
  452. {
  453. if (Params->Timeout > 0)
  454. {
  455. InitiateDialogTimeout(Dialog.get(), Params->Timeout, TimeoutButton, Params->TimeoutResponse);
  456. }
  457. }
  458. return Dialog.release();
  459. }
  460. //---------------------------------------------------------------------------
  461. unsigned int __fastcall MoreMessageDialog(const UnicodeString Message, TStrings * MoreMessages,
  462. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  463. {
  464. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, MoreMessages, Type, Answers, HelpKeyword, Params));
  465. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, Params);
  466. return Result;
  467. }
  468. //---------------------------------------------------------------------------
  469. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  470. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  471. {
  472. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  473. }
  474. //---------------------------------------------------------------------------
  475. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  476. {
  477. unsigned int Result;
  478. TStrings * More = NULL;
  479. try
  480. {
  481. if (!MoreMessages.IsEmpty())
  482. {
  483. More = TextToStringList(MoreMessages);
  484. }
  485. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  486. }
  487. __finally
  488. {
  489. delete More;
  490. }
  491. return Result;
  492. }
  493. //---------------------------------------------------------------------------
  494. static TStrings * __fastcall StackInfoListToStrings(
  495. TJclStackInfoList * StackInfoList)
  496. {
  497. std::unique_ptr<TStrings> StackTrace(new TStringList());
  498. StackInfoList->AddToStrings(StackTrace.get(), true, false, true, true);
  499. for (int Index = 0; Index < StackTrace->Count; Index++)
  500. {
  501. UnicodeString Frame = StackTrace->Strings[Index];
  502. // get rid of declarations "flags" that are included in .map
  503. Frame = ReplaceStr(Frame, L"__fastcall ", L"");
  504. Frame = ReplaceStr(Frame, L"__linkproc__ ", L"");
  505. if (DebugAlwaysTrue(!Frame.IsEmpty() && (Frame[1] == L'(')))
  506. {
  507. int Start = Frame.Pos(L"[");
  508. int End = Frame.Pos(L"]");
  509. if (DebugAlwaysTrue((Start > 1) && (End > Start) && (Frame[Start - 1] == L' ')))
  510. {
  511. // remove absolute address
  512. Frame.Delete(Start - 1, End - Start + 2);
  513. }
  514. }
  515. StackTrace->Strings[Index] = Frame;
  516. }
  517. return StackTrace.release();
  518. }
  519. //---------------------------------------------------------------------------
  520. static std::unique_ptr<TCriticalSection> StackTraceCriticalSection(TraceInitPtr(new TCriticalSection()));
  521. typedef std::map<DWORD, TStrings *> TStackTraceMap;
  522. static TStackTraceMap StackTraceMap;
  523. //---------------------------------------------------------------------------
  524. UnicodeString __fastcall GetExceptionDebugInfo()
  525. {
  526. UnicodeString Result;
  527. TGuard Guard(StackTraceCriticalSection.get());
  528. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  529. if (Iterator != StackTraceMap.end())
  530. {
  531. TStrings * StackTrace = Iterator->second;
  532. for (int Index = 0; Index < StackTrace->Count; Index++)
  533. {
  534. UnicodeString Frame = StackTrace->Strings[Index];
  535. // The last line might be empty
  536. if (!Frame.IsEmpty())
  537. {
  538. int P = Frame.Pos(L")");
  539. if (DebugAlwaysTrue(P > 0))
  540. {
  541. UnicodeString Symbol = Frame.SubString(P + 1, Frame.Length() - P).Trim();
  542. if ((Symbol != L"KERNELBASE.dll.RaiseException") &&
  543. (Symbol != L"Jclhookexcept::JclAddExceptNotifier") &&
  544. (Symbol != L"_ReThrowException") &&
  545. (Symbol != L"____ExceptionHandler") &&
  546. (Symbol != L"__ExceptionHandler") &&
  547. (Symbol != L"___doGlobalUnwind") &&
  548. (Symbol != L"_ThrowExceptionLDTC"))
  549. {
  550. AddToList(Result, Symbol, L";");
  551. }
  552. }
  553. }
  554. }
  555. }
  556. return Result;
  557. }
  558. //---------------------------------------------------------------------------
  559. bool __fastcall AppendExceptionStackTraceAndForget(TStrings *& MoreMessages)
  560. {
  561. bool Result = false;
  562. TGuard Guard(StackTraceCriticalSection.get());
  563. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  564. if (Iterator != StackTraceMap.end())
  565. {
  566. std::unique_ptr<TStrings> OwnedMoreMessages;
  567. if (MoreMessages == NULL)
  568. {
  569. OwnedMoreMessages.reset(new TStringList());
  570. MoreMessages = OwnedMoreMessages.get();
  571. Result = true;
  572. }
  573. if (!MoreMessages->Text.IsEmpty())
  574. {
  575. MoreMessages->Text = MoreMessages->Text + "\n";
  576. }
  577. MoreMessages->Text = MoreMessages->Text + LoadStr(STACK_TRACE) + "\n";
  578. MoreMessages->AddStrings(Iterator->second);
  579. delete Iterator->second;
  580. StackTraceMap.erase(Iterator);
  581. OwnedMoreMessages.release();
  582. }
  583. return Result;
  584. }
  585. //---------------------------------------------------------------------------
  586. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  587. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  588. const TMessageParams * Params)
  589. {
  590. TStrings * MoreMessages = NULL;
  591. ExtException * EE = dynamic_cast<ExtException *>(E);
  592. if (EE != NULL)
  593. {
  594. MoreMessages = EE->MoreMessages;
  595. }
  596. UnicodeString Message;
  597. // this is always called from within ExceptionMessage check,
  598. // so it should never fail here
  599. DebugCheck(ExceptionMessageFormatted(E, Message));
  600. if (!MessageFormat.IsEmpty())
  601. {
  602. Message = FORMAT(MessageFormat, (UnformatMessage(Message)));
  603. }
  604. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  605. std::unique_ptr<TStrings> OwnedMoreMessages;
  606. if (AppendExceptionStackTraceAndForget(MoreMessages))
  607. {
  608. OwnedMoreMessages.reset(MoreMessages);
  609. }
  610. return MoreMessageDialog(
  611. Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  612. }
  613. //---------------------------------------------------------------------------
  614. unsigned int __fastcall FatalExceptionMessageDialog(
  615. Exception * E, TQueryType Type, const UnicodeString & MessageFormat, unsigned int Answers,
  616. const UnicodeString & HelpKeyword, const TMessageParams * Params)
  617. {
  618. DebugAssert(FLAGCLEAR(Answers, qaRetry));
  619. Answers |= qaRetry;
  620. TQueryButtonAlias Aliases[1];
  621. Aliases[0].Button = qaRetry;
  622. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  623. TMessageParams AParams;
  624. if (Params != NULL)
  625. {
  626. AParams = *Params;
  627. }
  628. DebugAssert(AParams.Aliases == NULL);
  629. AParams.Aliases = Aliases;
  630. AParams.AliasesCount = LENOF(Aliases);
  631. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  632. }
  633. //---------------------------------------------------------------------------
  634. //---------------------------------------------------------------------------
  635. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  636. bool OSException, void * BaseOfStack)
  637. {
  638. if (ExceptObj != NULL)
  639. {
  640. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  641. if ((E != NULL) && IsInternalException(E))
  642. {
  643. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  644. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  645. if (DebugAlwaysTrue(StackInfoList != NULL))
  646. {
  647. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  648. DWORD ThreadID = GetCurrentThreadId();
  649. TGuard Guard(StackTraceCriticalSection.get());
  650. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  651. if (Iterator != StackTraceMap.end())
  652. {
  653. Iterator->second->Add(L"");
  654. Iterator->second->AddStrings(StackTrace.get());
  655. }
  656. else
  657. {
  658. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  659. }
  660. // this chains so that JclLastExceptStackList() returns NULL the next time
  661. // for the current thread
  662. delete StackInfoList;
  663. }
  664. }
  665. }
  666. }
  667. //---------------------------------------------------------------------------
  668. void * __fastcall BusyStart()
  669. {
  670. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  671. Screen->Cursor = crHourGlass;
  672. return Token;
  673. }
  674. //---------------------------------------------------------------------------
  675. void __fastcall BusyEnd(void * Token)
  676. {
  677. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  678. }
  679. //---------------------------------------------------------------------------
  680. //---------------------------------------------------------------------------
  681. static DWORD MainThread = 0;
  682. static TDateTime LastGUIUpdate = 0;
  683. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  684. static bool NoGUI = false;
  685. //---------------------------------------------------------------------------
  686. void __fastcall SetNoGUI()
  687. {
  688. NoGUI = true;
  689. }
  690. //---------------------------------------------------------------------------
  691. bool __fastcall ProcessGUI(bool Force)
  692. {
  693. DebugAssert(MainThread != 0);
  694. bool Result = false;
  695. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  696. // As we do not really need to call it in scripting/.NET, just skip it.
  697. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  698. {
  699. TDateTime N = Now();
  700. if (Force ||
  701. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  702. {
  703. LastGUIUpdate = N;
  704. Application->ProcessMessages();
  705. Result = true;
  706. }
  707. }
  708. return Result;
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall CopyParamListButton(TButton * Button)
  712. {
  713. if (!SupportsSplitButton())
  714. {
  715. MenuButton(Button);
  716. }
  717. }
  718. //---------------------------------------------------------------------------
  719. const int cpiDefault = -1;
  720. const int cpiConfigure = -2;
  721. const int cpiCustom = -3;
  722. const int cpiSaveSettings = -4;
  723. const int cpiGenerateCode = -5;
  724. const int cpiSavePreset = -6;
  725. //---------------------------------------------------------------------------
  726. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  727. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  728. int Options, int CopyParamAttrs, bool SaveSettings)
  729. {
  730. Menu->Items->Clear();
  731. TMenuItem * Item;
  732. Item = new TMenuItem(Menu);
  733. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  734. Item->Tag = cpiCustom;
  735. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  736. Item->OnClick = OnClick;
  737. Menu->Items->Add(Item);
  738. TMenuItem * CustomizeItem = Item;
  739. if (FLAGSET(Options, cplSaveSettings))
  740. {
  741. Item = new TMenuItem(Menu);
  742. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  743. Item->Tag = cpiSaveSettings;
  744. Item->Checked = SaveSettings;
  745. Item->OnClick = OnClick;
  746. Menu->Items->Add(Item);
  747. }
  748. Item = new TMenuItem(Menu);
  749. Item->Caption = LoadStr(COPY_PARAM_SAVE_PRESET);
  750. Item->Tag = cpiSavePreset;
  751. Item->OnClick = OnClick;
  752. Menu->Items->Add(Item);
  753. Item = new TMenuItem(Menu);
  754. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  755. Item->Visible = false;
  756. Item->Enabled = false;
  757. Menu->Items->Add(Item);
  758. bool AnyChecked = false;
  759. Item = new TMenuItem(Menu);
  760. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  761. Item->Tag = cpiDefault;
  762. Item->Checked =
  763. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  764. AnyChecked = AnyChecked || Item->Checked;
  765. Item->OnClick = OnClick;
  766. Menu->Items->Add(Item);
  767. TCopyParamType DefaultParam;
  768. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  769. for (int i = 0; i < CopyParamList->Count; i++)
  770. {
  771. UnicodeString Name = CopyParamList->Names[i];
  772. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  773. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  774. // This makes "Binary" preset visible,
  775. // as long as we care about transfer mode
  776. ((AParam == DefaultParam) &&
  777. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  778. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  779. {
  780. Item = new TMenuItem(Menu);
  781. Item->Caption = Name;
  782. Item->Tag = i;
  783. Item->Checked =
  784. (Preset == Name) && (AParam == Param);
  785. AnyChecked = AnyChecked || Item->Checked;
  786. Item->OnClick = OnClick;
  787. Menu->Items->Add(Item);
  788. }
  789. }
  790. CustomizeItem->Checked = !AnyChecked;
  791. Item = new TMenuItem(Menu);
  792. Item->Caption = L"-";
  793. Menu->Items->Add(Item);
  794. Item = new TMenuItem(Menu);
  795. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  796. Item->Tag = cpiConfigure;
  797. Item->OnClick = OnClick;
  798. Menu->Items->Add(Item);
  799. if (FLAGSET(Options, cplGenerateCode))
  800. {
  801. Item = new TMenuItem(Menu);
  802. Item->Caption = L"-";
  803. Menu->Items->Add(Item);
  804. Item = new TMenuItem(Menu);
  805. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  806. Item->Tag = cpiGenerateCode;
  807. Item->OnClick = OnClick;
  808. Menu->Items->Add(Item);
  809. }
  810. MenuPopup(Menu, Rect, NULL);
  811. }
  812. //---------------------------------------------------------------------------
  813. int __fastcall CopyParamListPopupClick(TObject * Sender,
  814. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  815. bool * SaveSettings)
  816. {
  817. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  818. DebugAssert(Item != NULL);
  819. DebugAssert((Item->Tag >= cpiSavePreset) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  820. int Result;
  821. if (Item->Tag == cpiConfigure)
  822. {
  823. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  824. DoPreferencesDialog(pmPresets);
  825. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  826. if (Result > 0)
  827. {
  828. // For cast, see a comment below
  829. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  830. }
  831. }
  832. else if (Item->Tag == cpiCustom)
  833. {
  834. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  835. }
  836. else if (Item->Tag == cpiSaveSettings)
  837. {
  838. if (DebugAlwaysTrue(SaveSettings != NULL))
  839. {
  840. *SaveSettings = !*SaveSettings;
  841. }
  842. Result = 0;
  843. }
  844. else if (Item->Tag == cpiSavePreset)
  845. {
  846. std::unique_ptr<TCopyParamList> CopyParamList(new TCopyParamList());
  847. *CopyParamList = *GUIConfiguration->CopyParamList;
  848. int Index = -1;
  849. if (DoCopyParamPresetDialog(CopyParamList.get(), Index, cpmAdd, NULL, Param))
  850. {
  851. GUIConfiguration->CopyParamList = CopyParamList.get();
  852. // If saved unmodified, then make this the selected preset
  853. if (*CopyParamList->CopyParams[Index] == Param)
  854. {
  855. Preset = CopyParamList->Names[Index];
  856. }
  857. }
  858. Result = 0;
  859. }
  860. else if (Item->Tag == cpiGenerateCode)
  861. {
  862. Result = -cplGenerateCode;
  863. }
  864. else
  865. {
  866. Preset = (Item->Tag >= 0) ?
  867. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  868. // The cast strips away the "queue" properties of the TGUICopyParamType
  869. // that are not configurable in presets
  870. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  871. Result = 1;
  872. }
  873. return Result;
  874. }
  875. //---------------------------------------------------------------------------
  876. //---------------------------------------------------------------------------
  877. class TCustomCommandPromptsDialog : public TCustomDialog
  878. {
  879. public:
  880. __fastcall TCustomCommandPromptsDialog(
  881. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  882. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults);
  883. bool __fastcall Execute(TUnicodeStringVector & Values);
  884. private:
  885. UnicodeString __fastcall HistoryKey(int Index);
  886. std::vector<THistoryComboBox *> FEdits;
  887. TUnicodeStringVector FPrompts;
  888. UnicodeString FCustomCommandName;
  889. };
  890. //---------------------------------------------------------------------------
  891. __fastcall TCustomCommandPromptsDialog::TCustomCommandPromptsDialog(
  892. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  893. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults) :
  894. TCustomDialog(HelpKeyword)
  895. {
  896. FCustomCommandName = CustomCommandName;
  897. Caption = FMTLOAD(CUSTOM_COMMANDS_PARAMS_TITLE, (FCustomCommandName));
  898. FPrompts = Prompts;
  899. DebugAssert(FPrompts.size() == Defaults.size());
  900. for (size_t Index = 0; Index < FPrompts.size(); Index++)
  901. {
  902. UnicodeString Prompt = FPrompts[Index];
  903. if (Prompt.IsEmpty())
  904. {
  905. Prompt = LoadStr(CUSTOM_COMMANDS_PARAM_PROMPT2);
  906. }
  907. THistoryComboBox * ComboBox = new THistoryComboBox(this);
  908. ComboBox->AutoComplete = false;
  909. AddComboBox(ComboBox, CreateLabel(Prompt));
  910. ComboBox->Items = CustomWinConfiguration->History[HistoryKey(Index)];
  911. ComboBox->Text = Defaults[Index];
  912. FEdits.push_back(ComboBox);
  913. }
  914. }
  915. //---------------------------------------------------------------------------
  916. UnicodeString __fastcall TCustomCommandPromptsDialog::HistoryKey(int Index)
  917. {
  918. UnicodeString Result = FPrompts[Index];
  919. if (Result.IsEmpty())
  920. {
  921. Result = IntToStr(Index);
  922. }
  923. Result = FORMAT(L"%s_%s", (FCustomCommandName, Result));
  924. Result = CustomWinConfiguration->GetValidHistoryKey(Result);
  925. return L"CustomCommandParam_" + Result;
  926. }
  927. //---------------------------------------------------------------------------
  928. bool __fastcall TCustomCommandPromptsDialog::Execute(TUnicodeStringVector & Values)
  929. {
  930. bool Result = TCustomDialog::Execute();
  931. if (Result)
  932. {
  933. for (size_t Index = 0; Index < FEdits.size(); Index++)
  934. {
  935. Values.push_back(FEdits[Index]->Text);
  936. FEdits[Index]->SaveToHistory();
  937. CustomWinConfiguration->History[HistoryKey(Index)] = FEdits[Index]->Items;
  938. }
  939. }
  940. return Result;
  941. }
  942. //---------------------------------------------------------------------------
  943. //---------------------------------------------------------------------------
  944. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  945. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName, const UnicodeString HelpKeyword) :
  946. TInteractiveCustomCommand(ChildCustomCommand)
  947. {
  948. FCustomCommandName = StripEllipsis(StripHotkey(CustomCommandName));
  949. FHelpKeyword = HelpKeyword;
  950. }
  951. //---------------------------------------------------------------------------
  952. void __fastcall TWinInteractiveCustomCommand::PatternHint(int Index, const UnicodeString & Pattern)
  953. {
  954. if (IsPromptPattern(Pattern))
  955. {
  956. UnicodeString Prompt;
  957. UnicodeString Default;
  958. bool Delimit = false;
  959. ParsePromptPattern(Pattern, Prompt, Default, Delimit);
  960. FIndexes.insert(std::make_pair(Index, FPrompts.size()));
  961. FPrompts.push_back(Prompt);
  962. FDefaults.push_back(Default);
  963. }
  964. }
  965. //---------------------------------------------------------------------------
  966. void __fastcall TWinInteractiveCustomCommand::Prompt(
  967. int Index, const UnicodeString & /*Prompt*/, UnicodeString & Value)
  968. {
  969. if (DebugAlwaysTrue(FIndexes.find(Index) != FIndexes.end()))
  970. {
  971. size_t PromptIndex = FIndexes[Index];
  972. if (FValues.empty())
  973. {
  974. UnicodeString HelpKeyword = FHelpKeyword;
  975. if (HelpKeyword.IsEmpty())
  976. {
  977. HelpKeyword = HELP_CUSTOM_COMMAND_PARAM;
  978. }
  979. std::unique_ptr<TCustomCommandPromptsDialog> Dialog(
  980. new TCustomCommandPromptsDialog(FCustomCommandName, HelpKeyword, FPrompts, FDefaults));
  981. if (!Dialog->Execute(FValues))
  982. {
  983. Abort();
  984. }
  985. }
  986. if (DebugAlwaysTrue(FValues.size() == FPrompts.size()) &&
  987. DebugAlwaysTrue(PromptIndex < FValues.size()))
  988. {
  989. Value = FValues[PromptIndex];
  990. }
  991. }
  992. }
  993. //---------------------------------------------------------------------------
  994. void __fastcall TWinInteractiveCustomCommand::Execute(
  995. const UnicodeString & Command, UnicodeString & Value)
  996. {
  997. DWORD DummyExitCode;
  998. ExecuteProcessAndReadOutput(Command, Value, DummyExitCode, false);
  999. // trim trailing cr/lf
  1000. Value = TrimRight(Value);
  1001. }
  1002. //---------------------------------------------------------------------------
  1003. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  1004. {
  1005. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  1009. {
  1010. TControl * Control = dynamic_cast<TControl *>(Sender);
  1011. DebugAssert(Control != NULL);
  1012. TPoint Point;
  1013. if ((MousePos.x == -1) && (MousePos.y == -1))
  1014. {
  1015. Point = Control->ClientToScreen(TPoint(0, 0));
  1016. }
  1017. else
  1018. {
  1019. Point = Control->ClientToScreen(MousePos);
  1020. }
  1021. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  1022. DebugAssert(PopupMenu != NULL);
  1023. TRect Rect(Point, Point);
  1024. MenuPopup(PopupMenu, Rect, Control);
  1025. Handled = true;
  1026. }
  1027. //---------------------------------------------------------------------------
  1028. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  1029. {
  1030. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1031. DebugAssert(Item != NULL);
  1032. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1033. DebugAssert(PopupMenu != NULL);
  1034. DebugAssert(PopupMenu->PopupComponent != NULL);
  1035. return PopupMenu->PopupComponent;
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. static void __fastcall SetMenuButtonImages(TButton * Button)
  1039. {
  1040. Button->Images = GetButtonImages(Button);
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. static void __fastcall MenuButtonRescale(TComponent * Sender, TObject * /*Token*/)
  1044. {
  1045. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1046. SetMenuButtonImages(Button);
  1047. }
  1048. //---------------------------------------------------------------------------
  1049. void __fastcall MenuButton(TButton * Button)
  1050. {
  1051. SetMenuButtonImages(Button);
  1052. Button->ImageIndex = 0;
  1053. Button->DisabledImageIndex = 1;
  1054. Button->ImageAlignment = iaRight;
  1055. SetRescaleFunction(Button, MenuButtonRescale);
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. TRect __fastcall CalculatePopupRect(TButton * Button)
  1059. {
  1060. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1061. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1062. TRect Rect(UpPoint, DownPoint);
  1063. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1064. int Offset = UseThemes() ? -1 : 0;
  1065. Rect.Inflate(Offset, Offset);
  1066. return Rect;
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1070. {
  1071. MousePos = Control->ClientToScreen(MousePos);
  1072. TRect Rect(MousePos, MousePos);
  1073. return Rect;
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall FixButtonImage(TButton * Button)
  1077. {
  1078. // with themes enabled, button image is by default drawn too high
  1079. if (UseThemes())
  1080. {
  1081. Button->ImageMargins->Top = 1;
  1082. }
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. void __fastcall CenterButtonImage(TButton * Button)
  1086. {
  1087. // with themes disabled, the text seems to be drawn over the icon,
  1088. // so that the padding spaces hide away most of the icon
  1089. if (UseThemes())
  1090. {
  1091. Button->ImageAlignment = iaCenter;
  1092. int ImageWidth = Button->Images->Width;
  1093. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(Button));
  1094. UnicodeString Caption;
  1095. // Centering unlinks the caption from the action
  1096. TAction * Action = dynamic_cast<TAction *>(Button->Action);
  1097. if (Action != NULL)
  1098. {
  1099. Caption = Action->Caption;
  1100. }
  1101. else
  1102. {
  1103. Caption = Button->Caption.Trim();
  1104. }
  1105. UnicodeString Padding;
  1106. while (Canvas->TextWidth(Padding) < ImageWidth)
  1107. {
  1108. Padding += L" ";
  1109. }
  1110. if (Button->IsRightToLeft())
  1111. {
  1112. Caption = Caption + Padding;
  1113. }
  1114. else
  1115. {
  1116. Caption = Padding + Caption;
  1117. }
  1118. Button->Caption = Caption;
  1119. int CaptionWidth = Canvas->TextWidth(Caption);
  1120. // The margins seem to extend the area over which the image is centered,
  1121. // so we have to set it to a double of desired padding.
  1122. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1123. // the one below is equivalent, but with reduced rounding.
  1124. // Without the change, the rounding caused the space between icon and caption too
  1125. // small on 200% zoom.
  1126. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1127. // is approximately same as half of caption width before padding.
  1128. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1129. }
  1130. else
  1131. {
  1132. // at least do not draw it so near to the edge
  1133. Button->ImageMargins->Left = 1;
  1134. }
  1135. }
  1136. //---------------------------------------------------------------------------
  1137. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1138. {
  1139. int Result = !S.IsEmpty() && StrToInt(S);
  1140. switch (LocaleFlagOverride)
  1141. {
  1142. default:
  1143. case lfoLanguageIfRecommended:
  1144. if (!Recommended)
  1145. {
  1146. Result = Off;
  1147. }
  1148. break;
  1149. case lfoLanguage:
  1150. // noop = as configured in locale
  1151. break;
  1152. case lfoAlways:
  1153. Result = On;
  1154. break;
  1155. case lfoNever:
  1156. Result = Off;
  1157. break;
  1158. }
  1159. return Result;
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1163. {
  1164. if (GlobalOnMinimize == NULL)
  1165. {
  1166. GlobalOnMinimize = OnMinimize;
  1167. }
  1168. }
  1169. //---------------------------------------------------------------------------
  1170. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1171. {
  1172. if (GlobalOnMinimize == OnMinimize)
  1173. {
  1174. GlobalOnMinimize = NULL;
  1175. }
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1179. {
  1180. Configuration->Usage->Inc(L"OperationMinimizations");
  1181. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1182. {
  1183. GlobalOnMinimize(Sender);
  1184. }
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. bool MinimizedToTray = false;
  1188. //---------------------------------------------------------------------------
  1189. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1190. {
  1191. TForm * MainForm = Application->MainForm;
  1192. TForm * MainLikeForm = GetMainForm();
  1193. bool MinimizeToTray;
  1194. if (Minimize)
  1195. {
  1196. MinimizeToTray = WinConfiguration->MinimizeToTray;
  1197. }
  1198. else
  1199. {
  1200. // Use tray restore code, even if minimization to tray is not on anymore when restoring.
  1201. // This is particularly used for ad-hoc minimize to tray from "keep up to date" dialog.
  1202. MinimizeToTray = MinimizedToTray;
  1203. }
  1204. MinimizedToTray = false; // reset in any case, even if we somehow got restored from tray without invoking this code
  1205. if ((MainLikeForm != MainForm) && !MinimizeToTray)
  1206. {
  1207. static TWindowState PreviousWindowState = wsNormal;
  1208. if (Minimize)
  1209. {
  1210. PreviousWindowState = MainLikeForm->WindowState;
  1211. // This works correctly with child windows thanks to Application->OnGetMainFormHandle
  1212. MainLikeForm->WindowState = wsMinimized;
  1213. }
  1214. else
  1215. {
  1216. MainLikeForm->WindowState = PreviousWindowState;
  1217. }
  1218. }
  1219. else
  1220. {
  1221. // What is described below should not ever happen, except when minimizing to tray,
  1222. // as we capture command-line operation above.
  1223. // Had we called TApplication::Minimize, it would hide all non-MainForm windows, including MainLineForm,
  1224. // so it actually also hides taskbar button, what we do not want.
  1225. // WORKAROUND
  1226. // When main window is hidden (command-line operation),
  1227. // we do not want it to be shown by TApplication.Restore,
  1228. // so we temporarily detach it from an application.
  1229. // Probably not really necessary for minimizing phase,
  1230. // but we do it for consistency anyway.
  1231. bool RestoreMainForm = false;
  1232. if (DebugAlwaysTrue(MainForm != NULL) &&
  1233. !MainForm->Visible)
  1234. {
  1235. SetAppMainForm(NULL);
  1236. RestoreMainForm = true;
  1237. }
  1238. try
  1239. {
  1240. if (Minimize)
  1241. {
  1242. Application->Minimize();
  1243. MinimizedToTray = WinConfiguration->MinimizeToTray;
  1244. }
  1245. else
  1246. {
  1247. Application->Restore();
  1248. }
  1249. }
  1250. __finally
  1251. {
  1252. if (RestoreMainForm)
  1253. {
  1254. SetAppMainForm(MainForm);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. void __fastcall ApplicationMinimize()
  1261. {
  1262. DoApplicationMinimizeRestore(true);
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. void __fastcall ApplicationRestore()
  1266. {
  1267. DoApplicationMinimizeRestore(false);
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. bool __fastcall IsApplicationMinimized()
  1271. {
  1272. // VCL help recommends handling Application->OnMinimize/OnRestore
  1273. // for tracking state, but OnRestore is actually not called
  1274. // (OnMinimize is), when app is minimized from e.g. Progress window
  1275. bool AppMinimized = IsIconic(Application->Handle);
  1276. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1277. return AppMinimized || MainFormMinimized;
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1281. {
  1282. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1283. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1284. bool Result = (Cmd == SC_MINIMIZE);
  1285. if (Result)
  1286. {
  1287. ApplicationMinimize();
  1288. SysCommand.Result = 1;
  1289. }
  1290. return Result;
  1291. }
  1292. //---------------------------------------------------------------------------
  1293. void __fastcall ClickToolbarItem(TTBCustomItem * Item, bool PositionCursor)
  1294. {
  1295. TTBCustomItem * TopItem = Item;
  1296. while (TopItem->Parent != NULL)
  1297. {
  1298. TopItem = TopItem->Parent;
  1299. }
  1300. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(TopItem->ParentComponent);
  1301. DebugAssert(Toolbar != NULL);
  1302. TTBItemViewer * Viewer = Toolbar->View->Find(Item);
  1303. DebugAssert(Viewer != NULL);
  1304. int X = Viewer->BoundsRect.Left + (Viewer->BoundsRect.Width() / 2);
  1305. int Y = Viewer->BoundsRect.Top + (Viewer->BoundsRect.Height() / 2);
  1306. if (PositionCursor)
  1307. {
  1308. Mouse->CursorPos = Toolbar->ClientToScreen(TPoint(X, Y));
  1309. }
  1310. PostMessage(Toolbar->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(X, Y));
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. //---------------------------------------------------------------------------
  1314. UnicodeString DumpCallstackEventName(int ProcessId)
  1315. {
  1316. return FORMAT(DUMPCALLSTACK_EVENT, (ProcessId));
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. UnicodeString DumpCallstackFileName(int ProcessId)
  1320. {
  1321. UnicodeString FileName = FORMAT(L"%s.txt", (DumpCallstackEventName(ProcessId)));
  1322. UnicodeString Result = TPath::Combine(SystemTemporaryDirectory(), FileName);
  1323. return Result;
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. void CheckConfigurationForceSave()
  1327. {
  1328. if (UseAlternativeFunction() && Configuration->Persistent &&
  1329. (Configuration->Storage == stIniFile) && Sysutils::FileExists(ApiPath(Configuration->IniFileStorageName)) &&
  1330. !Configuration->ForceSave)
  1331. {
  1332. int Attr = GetFileAttributes(ApiPath(Configuration->IniFileStorageName).c_str());
  1333. if (FLAGSET(Attr, FILE_ATTRIBUTE_READONLY))
  1334. {
  1335. UnicodeString Message = FMTLOAD(READONLY_INI_FILE_OVERWRITE, (Configuration->IniFileStorageName));
  1336. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_READONLY_INI_FILE) == qaOK)
  1337. {
  1338. Configuration->ForceSave = true;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. class TCallstackThread : public TSignalThread
  1345. {
  1346. public:
  1347. __fastcall TCallstackThread();
  1348. protected:
  1349. virtual void __fastcall ProcessEvent();
  1350. private:
  1351. static HANDLE DoCreateEvent();
  1352. };
  1353. //---------------------------------------------------------------------------
  1354. __fastcall TCallstackThread::TCallstackThread() :
  1355. TSignalThread(true, DoCreateEvent())
  1356. {
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. void __fastcall TCallstackThread::ProcessEvent()
  1360. {
  1361. try
  1362. {
  1363. UnicodeString Path = DumpCallstackFileName(GetCurrentProcessId());
  1364. std::unique_ptr<TStrings> StackStrings;
  1365. HANDLE MainThreadHandle = reinterpret_cast<HANDLE>(MainThreadID);
  1366. if (SuspendThread(MainThreadHandle) < 0)
  1367. {
  1368. RaiseLastOSError();
  1369. }
  1370. try
  1371. {
  1372. TJclStackInfoList * StackInfoList = JclCreateThreadStackTraceFromID(true, MainThreadID);
  1373. if (StackInfoList == NULL)
  1374. {
  1375. RaiseLastOSError();
  1376. }
  1377. StackStrings.reset(StackInfoListToStrings(StackInfoList));
  1378. }
  1379. __finally
  1380. {
  1381. if (ResumeThread(MainThreadHandle) < 0)
  1382. {
  1383. RaiseLastOSError();
  1384. }
  1385. }
  1386. TFile::WriteAllText(Path, StackStrings->Text);
  1387. }
  1388. catch (...)
  1389. {
  1390. }
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. HANDLE TCallstackThread::DoCreateEvent()
  1394. {
  1395. UnicodeString Name = DumpCallstackEventName(GetCurrentProcessId());
  1396. return CreateEvent(NULL, false, false, Name.c_str());
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. //---------------------------------------------------------------------------
  1400. std::unique_ptr<TCallstackThread> CallstackThread;
  1401. //---------------------------------------------------------------------------
  1402. static void __fastcall AppGetMainFormHandle(void * /*Data*/, HWND & Handle)
  1403. {
  1404. TForm * MainForm = GetMainForm();
  1405. // This, among other, causes minimizing of the top-level non-MainForm minimize other child windows.
  1406. // Like clicking "Minimize" on Progress window over Synchronization progress window over Synchronization checklist window.
  1407. // Would also have a lot of other effects (hopefully positive) and may render lot of existing MainFormLike code obsolete.
  1408. if ((MainForm != NULL) && IsMainFormLike(MainForm) && MainForm->HandleAllocated())
  1409. {
  1410. Handle = MainForm->Handle;
  1411. }
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. void __fastcall WinInitialize()
  1415. {
  1416. if (JclHookExceptions())
  1417. {
  1418. JclStackTrackingOptions << stAllModules;
  1419. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1420. CallstackThread.reset(new TCallstackThread());
  1421. CallstackThread->Start();
  1422. }
  1423. SetErrorMode(SEM_FAILCRITICALERRORS);
  1424. OnApiPath = ApiPath;
  1425. MainThread = GetCurrentThreadId();
  1426. Application->OnGetMainFormHandle = MakeMethod<TGetHandleEvent>(NULL, AppGetMainFormHandle);
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. void __fastcall WinFinalize()
  1430. {
  1431. CallstackThread.reset(NULL);
  1432. JclRemoveExceptNotifier(DoExceptNotify);
  1433. }
  1434. //---------------------------------------------------------------------------
  1435. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1436. {
  1437. FVisible = false;
  1438. FOnClick = NULL;
  1439. FOnBalloonClick = NULL;
  1440. FBalloonUserData = NULL;
  1441. FTrayIcon = new NOTIFYICONDATA;
  1442. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1443. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1444. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1445. // LoadIconMetric is available from Windows Vista only
  1446. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1447. if (DebugAlwaysTrue(ComCtl32Dll))
  1448. {
  1449. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1450. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1451. if (LoadIconMetric != NULL)
  1452. {
  1453. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1454. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1455. }
  1456. }
  1457. if (FTrayIcon->hIcon == 0)
  1458. {
  1459. FTrayIcon->hIcon = Application->Icon->Handle;
  1460. }
  1461. FTrayIcon->uID = Id;
  1462. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1463. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1464. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1465. }
  1466. //---------------------------------------------------------------------------
  1467. __fastcall ::TTrayIcon::~TTrayIcon()
  1468. {
  1469. // make sure we hide icon even in case it was shown just to pop up the balloon
  1470. // (in which case Visible == false)
  1471. CancelBalloon();
  1472. Visible = false;
  1473. DeallocateHWnd(FTrayIcon->hWnd);
  1474. delete FTrayIcon;
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1478. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1479. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1480. {
  1481. if (Timeout > 30000)
  1482. {
  1483. // this is probably system limit, do not try more, especially for
  1484. // the timeout-driven hiding of the tray icon (for Win2k)
  1485. Timeout = 30000;
  1486. }
  1487. FTrayIcon->uFlags |= NIF_INFO;
  1488. AppLogFmt("Tray popup balloon: %s - %s", (Title, Str));
  1489. Title = Title + TitleSeparator + AppNameString();
  1490. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1491. UnicodeString Info = Str;
  1492. // When szInfo is empty, balloon is not shown
  1493. // (or actually it means the balloon should be deleted, if any)
  1494. if (Info.IsEmpty())
  1495. {
  1496. Info = L" ";
  1497. }
  1498. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1499. FTrayIcon->uTimeout = Timeout;
  1500. switch (QueryType)
  1501. {
  1502. case qtError:
  1503. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1504. break;
  1505. case qtInformation:
  1506. case qtConfirmation:
  1507. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1508. break;
  1509. case qtWarning:
  1510. default:
  1511. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1512. break;
  1513. }
  1514. KillTimer(FTrayIcon->hWnd, 1);
  1515. if (Visible)
  1516. {
  1517. Update();
  1518. }
  1519. else
  1520. {
  1521. Notify(NIM_ADD);
  1522. }
  1523. FOnBalloonClick = OnBalloonClick;
  1524. delete FBalloonUserData;
  1525. FBalloonUserData = BalloonUserData;
  1526. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1527. // unless CancelBalloon is called explicitly
  1528. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. void __fastcall ::TTrayIcon::BalloonCancelled()
  1532. {
  1533. FOnBalloonClick = NULL;
  1534. delete FBalloonUserData;
  1535. FBalloonUserData = NULL;
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. void __fastcall ::TTrayIcon::CancelBalloon()
  1539. {
  1540. KillTimer(FTrayIcon->hWnd, 1);
  1541. if (Visible)
  1542. {
  1543. FTrayIcon->uFlags |= NIF_INFO;
  1544. FTrayIcon->szInfo[0] = L'\0';
  1545. Update();
  1546. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1547. }
  1548. else
  1549. {
  1550. Notify(NIM_DELETE);
  1551. }
  1552. BalloonCancelled();
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1556. {
  1557. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1558. if (Result && (Message == NIM_ADD))
  1559. {
  1560. UINT Timeout = FTrayIcon->uTimeout;
  1561. try
  1562. {
  1563. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1564. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1565. }
  1566. __finally
  1567. {
  1568. FTrayIcon->uTimeout = Timeout;
  1569. }
  1570. }
  1571. return Result;
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. void __fastcall ::TTrayIcon::Update()
  1575. {
  1576. if (Visible)
  1577. {
  1578. Notify(NIM_MODIFY);
  1579. }
  1580. }
  1581. //---------------------------------------------------------------------------
  1582. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1583. {
  1584. if (Visible != value)
  1585. {
  1586. if (value)
  1587. {
  1588. FVisible = Notify(NIM_ADD);
  1589. }
  1590. else
  1591. {
  1592. FVisible = false;
  1593. KillTimer(FTrayIcon->hWnd, 1);
  1594. Notify(NIM_DELETE);
  1595. BalloonCancelled();
  1596. }
  1597. }
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1601. {
  1602. try
  1603. {
  1604. if (Message.Msg == WM_TRAY_ICON)
  1605. {
  1606. DebugAssert(Message.WParam == 0);
  1607. switch (Message.LParam)
  1608. {
  1609. // old shell32
  1610. case WM_LBUTTONUP:
  1611. case WM_RBUTTONUP:
  1612. // new shell32:
  1613. case WM_CONTEXTMENU:
  1614. if (OnClick != NULL)
  1615. {
  1616. OnClick(NULL);
  1617. }
  1618. Message.Result = true;
  1619. break;
  1620. }
  1621. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1622. {
  1623. if (FOnBalloonClick != NULL)
  1624. {
  1625. // prevent the user data from being freed by possible call
  1626. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1627. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1628. FBalloonUserData = NULL;
  1629. FOnBalloonClick(UserData.get());
  1630. }
  1631. else if (OnClick != NULL)
  1632. {
  1633. OnClick(NULL);
  1634. }
  1635. }
  1636. switch (Message.LParam)
  1637. {
  1638. case NIN_BALLOONHIDE:
  1639. case NIN_BALLOONTIMEOUT:
  1640. case NIN_BALLOONUSERCLICK:
  1641. KillTimer(FTrayIcon->hWnd, 1);
  1642. // if icon was shown just to display balloon, hide it with the balloon
  1643. if (!Visible)
  1644. {
  1645. Notify(NIM_DELETE);
  1646. }
  1647. BalloonCancelled();
  1648. break;
  1649. }
  1650. }
  1651. else if (Message.Msg == WM_TIMER)
  1652. {
  1653. // sanity check
  1654. Notify(NIM_DELETE);
  1655. BalloonCancelled();
  1656. }
  1657. else if (Message.Msg == FTaskbarCreatedMsg)
  1658. {
  1659. if (Visible)
  1660. {
  1661. // force recreation
  1662. Visible = false;
  1663. Visible = true;
  1664. }
  1665. }
  1666. else
  1667. {
  1668. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1669. }
  1670. }
  1671. catch(Exception & E)
  1672. {
  1673. Application->HandleException(&E);
  1674. }
  1675. }
  1676. //---------------------------------------------------------------------------
  1677. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1678. {
  1679. return FTrayIcon->szTip;
  1680. }
  1681. //---------------------------------------------------------------------------
  1682. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1683. {
  1684. if (Hint != value)
  1685. {
  1686. unsigned int Max = LENOF(FTrayIcon->szTip);
  1687. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1688. Update();
  1689. }
  1690. }
  1691. //---------------------------------------------------------------------------