WinInterface.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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. AppLogFmt(L"Message dialog: %s", (Message));
  465. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, MoreMessages, Type, Answers, HelpKeyword, Params));
  466. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, Params);
  467. AppLogFmt(L"Message dialog answer: %d", (Integer(Result)));
  468. return Result;
  469. }
  470. //---------------------------------------------------------------------------
  471. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  472. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  473. {
  474. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  475. }
  476. //---------------------------------------------------------------------------
  477. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  478. {
  479. unsigned int Result;
  480. TStrings * More = NULL;
  481. try
  482. {
  483. if (!MoreMessages.IsEmpty())
  484. {
  485. More = TextToStringList(MoreMessages);
  486. }
  487. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  488. }
  489. __finally
  490. {
  491. delete More;
  492. }
  493. return Result;
  494. }
  495. //---------------------------------------------------------------------------
  496. static TStrings * __fastcall StackInfoListToStrings(
  497. TJclStackInfoList * StackInfoList)
  498. {
  499. std::unique_ptr<TStrings> StackTrace(new TStringList());
  500. StackInfoList->AddToStrings(StackTrace.get(), true, false, true, true);
  501. for (int Index = 0; Index < StackTrace->Count; Index++)
  502. {
  503. UnicodeString Frame = StackTrace->Strings[Index];
  504. // get rid of declarations "flags" that are included in .map
  505. Frame = ReplaceStr(Frame, L"__fastcall ", L"");
  506. Frame = ReplaceStr(Frame, L"__linkproc__ ", L"");
  507. if (DebugAlwaysTrue(!Frame.IsEmpty() && (Frame[1] == L'(')))
  508. {
  509. int Start = Frame.Pos(L"[");
  510. int End = Frame.Pos(L"]");
  511. if (DebugAlwaysTrue((Start > 1) && (End > Start) && (Frame[Start - 1] == L' ')))
  512. {
  513. // remove absolute address
  514. Frame.Delete(Start - 1, End - Start + 2);
  515. }
  516. }
  517. StackTrace->Strings[Index] = Frame;
  518. }
  519. return StackTrace.release();
  520. }
  521. //---------------------------------------------------------------------------
  522. static std::unique_ptr<TCriticalSection> StackTraceCriticalSection(TraceInitPtr(new TCriticalSection()));
  523. typedef std::map<DWORD, TStrings *> TStackTraceMap;
  524. static TStackTraceMap StackTraceMap;
  525. //---------------------------------------------------------------------------
  526. UnicodeString __fastcall GetExceptionDebugInfo()
  527. {
  528. UnicodeString Result;
  529. TGuard Guard(StackTraceCriticalSection.get());
  530. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  531. if (Iterator != StackTraceMap.end())
  532. {
  533. TStrings * StackTrace = Iterator->second;
  534. for (int Index = 0; Index < StackTrace->Count; Index++)
  535. {
  536. UnicodeString Frame = StackTrace->Strings[Index];
  537. // The last line might be empty
  538. if (!Frame.IsEmpty())
  539. {
  540. int P = Frame.Pos(L")");
  541. if (DebugAlwaysTrue(P > 0))
  542. {
  543. UnicodeString Symbol = Frame.SubString(P + 1, Frame.Length() - P).Trim();
  544. if ((Symbol != L"KERNELBASE.dll.RaiseException") &&
  545. (Symbol != L"Jclhookexcept::JclAddExceptNotifier") &&
  546. (Symbol != L"_ReThrowException") &&
  547. (Symbol != L"____ExceptionHandler") &&
  548. (Symbol != L"__ExceptionHandler") &&
  549. (Symbol != L"___doGlobalUnwind") &&
  550. (Symbol != L"_ThrowExceptionLDTC"))
  551. {
  552. AddToList(Result, Symbol, L";");
  553. }
  554. }
  555. }
  556. }
  557. }
  558. return Result;
  559. }
  560. //---------------------------------------------------------------------------
  561. bool __fastcall AppendExceptionStackTraceAndForget(TStrings *& MoreMessages)
  562. {
  563. bool Result = false;
  564. TGuard Guard(StackTraceCriticalSection.get());
  565. TStackTraceMap::iterator Iterator = StackTraceMap.find(GetCurrentThreadId());
  566. if (Iterator != StackTraceMap.end())
  567. {
  568. std::unique_ptr<TStrings> OwnedMoreMessages;
  569. if (MoreMessages == NULL)
  570. {
  571. OwnedMoreMessages.reset(new TStringList());
  572. MoreMessages = OwnedMoreMessages.get();
  573. Result = true;
  574. }
  575. if (!MoreMessages->Text.IsEmpty())
  576. {
  577. MoreMessages->Text = MoreMessages->Text + "\n";
  578. }
  579. MoreMessages->Text = MoreMessages->Text + LoadStr(STACK_TRACE) + "\n";
  580. MoreMessages->AddStrings(Iterator->second);
  581. delete Iterator->second;
  582. StackTraceMap.erase(Iterator);
  583. OwnedMoreMessages.release();
  584. }
  585. return Result;
  586. }
  587. //---------------------------------------------------------------------------
  588. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  589. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  590. const TMessageParams * Params)
  591. {
  592. TStrings * MoreMessages = NULL;
  593. ExtException * EE = dynamic_cast<ExtException *>(E);
  594. if (EE != NULL)
  595. {
  596. MoreMessages = EE->MoreMessages;
  597. }
  598. UnicodeString Message;
  599. // this is always called from within ExceptionMessage check,
  600. // so it should never fail here
  601. DebugCheck(ExceptionMessageFormatted(E, Message));
  602. if (!MessageFormat.IsEmpty())
  603. {
  604. Message = FORMAT(MessageFormat, (UnformatMessage(Message)));
  605. }
  606. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  607. std::unique_ptr<TStrings> OwnedMoreMessages;
  608. if (AppendExceptionStackTraceAndForget(MoreMessages))
  609. {
  610. OwnedMoreMessages.reset(MoreMessages);
  611. }
  612. return MoreMessageDialog(
  613. Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  614. }
  615. //---------------------------------------------------------------------------
  616. unsigned int __fastcall FatalExceptionMessageDialog(
  617. Exception * E, TQueryType Type, const UnicodeString & MessageFormat, unsigned int Answers,
  618. const UnicodeString & HelpKeyword, const TMessageParams * Params)
  619. {
  620. DebugAssert(FLAGCLEAR(Answers, qaRetry));
  621. Answers |= qaRetry;
  622. TQueryButtonAlias Aliases[1];
  623. Aliases[0].Button = qaRetry;
  624. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  625. TMessageParams AParams;
  626. if (Params != NULL)
  627. {
  628. AParams = *Params;
  629. }
  630. DebugAssert(AParams.Aliases == NULL);
  631. AParams.Aliases = Aliases;
  632. AParams.AliasesCount = LENOF(Aliases);
  633. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  634. }
  635. //---------------------------------------------------------------------------
  636. //---------------------------------------------------------------------------
  637. static void __fastcall DoExceptNotify(TObject * ExceptObj, void * ExceptAddr,
  638. bool OSException, void * BaseOfStack)
  639. {
  640. if (ExceptObj != NULL)
  641. {
  642. Exception * E = dynamic_cast<Exception *>(ExceptObj);
  643. if ((E != NULL) && IsInternalException(E))
  644. {
  645. DoExceptionStackTrace(ExceptObj, ExceptAddr, OSException, BaseOfStack);
  646. TJclStackInfoList * StackInfoList = JclLastExceptStackList();
  647. if (DebugAlwaysTrue(StackInfoList != NULL))
  648. {
  649. std::unique_ptr<TStrings> StackTrace(StackInfoListToStrings(StackInfoList));
  650. DWORD ThreadID = GetCurrentThreadId();
  651. TGuard Guard(StackTraceCriticalSection.get());
  652. TStackTraceMap::iterator Iterator = StackTraceMap.find(ThreadID);
  653. if (Iterator != StackTraceMap.end())
  654. {
  655. Iterator->second->Add(L"");
  656. Iterator->second->AddStrings(StackTrace.get());
  657. }
  658. else
  659. {
  660. StackTraceMap.insert(std::make_pair(ThreadID, StackTrace.release()));
  661. }
  662. // this chains so that JclLastExceptStackList() returns NULL the next time
  663. // for the current thread
  664. delete StackInfoList;
  665. }
  666. }
  667. }
  668. }
  669. //---------------------------------------------------------------------------
  670. void * __fastcall BusyStart()
  671. {
  672. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  673. Screen->Cursor = crHourGlass;
  674. return Token;
  675. }
  676. //---------------------------------------------------------------------------
  677. void __fastcall BusyEnd(void * Token)
  678. {
  679. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  680. }
  681. //---------------------------------------------------------------------------
  682. //---------------------------------------------------------------------------
  683. static DWORD MainThread = 0;
  684. static TDateTime LastGUIUpdate = 0;
  685. static double GUIUpdateIntervalFrac = static_cast<double>(OneSecond/1000*GUIUpdateInterval); // 1/5 sec
  686. static bool NoGUI = false;
  687. //---------------------------------------------------------------------------
  688. void __fastcall SetNoGUI()
  689. {
  690. NoGUI = true;
  691. }
  692. //---------------------------------------------------------------------------
  693. bool __fastcall ProcessGUI(bool Force)
  694. {
  695. DebugAssert(MainThread != 0);
  696. bool Result = false;
  697. // Calling ProcessMessages in Azure WebJob causes access violation in VCL.
  698. // As we do not really need to call it in scripting/.NET, just skip it.
  699. if ((MainThread == GetCurrentThreadId()) && !NoGUI)
  700. {
  701. TDateTime N = Now();
  702. if (Force ||
  703. (double(N) - double(LastGUIUpdate) > GUIUpdateIntervalFrac))
  704. {
  705. LastGUIUpdate = N;
  706. Application->ProcessMessages();
  707. Result = true;
  708. }
  709. }
  710. return Result;
  711. }
  712. //---------------------------------------------------------------------------
  713. const int cpiDefault = -1;
  714. const int cpiConfigure = -2;
  715. const int cpiCustom = -3;
  716. const int cpiSaveSettings = -4;
  717. const int cpiGenerateCode = -5;
  718. const int cpiSavePreset = -6;
  719. //---------------------------------------------------------------------------
  720. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  721. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  722. int Options, int CopyParamAttrs, bool SaveSettings)
  723. {
  724. Menu->Items->Clear();
  725. TMenuItem * Item;
  726. Item = new TMenuItem(Menu);
  727. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  728. Item->Tag = cpiCustom;
  729. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  730. Item->OnClick = OnClick;
  731. Menu->Items->Add(Item);
  732. TMenuItem * CustomizeItem = Item;
  733. if (FLAGSET(Options, cplSaveSettings))
  734. {
  735. Item = new TMenuItem(Menu);
  736. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  737. Item->Tag = cpiSaveSettings;
  738. Item->Checked = SaveSettings;
  739. Item->OnClick = OnClick;
  740. Menu->Items->Add(Item);
  741. }
  742. Item = new TMenuItem(Menu);
  743. Item->Caption = LoadStr(COPY_PARAM_SAVE_PRESET);
  744. Item->Tag = cpiSavePreset;
  745. Item->OnClick = OnClick;
  746. Menu->Items->Add(Item);
  747. Item = new TMenuItem(Menu);
  748. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  749. Item->Visible = false;
  750. Item->Enabled = false;
  751. Menu->Items->Add(Item);
  752. bool AnyChecked = false;
  753. Item = new TMenuItem(Menu);
  754. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  755. Item->Tag = cpiDefault;
  756. Item->Checked =
  757. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  758. AnyChecked = AnyChecked || Item->Checked;
  759. Item->OnClick = OnClick;
  760. Menu->Items->Add(Item);
  761. TCopyParamType DefaultParam;
  762. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  763. for (int i = 0; i < CopyParamList->Count; i++)
  764. {
  765. UnicodeString Name = CopyParamList->Names[i];
  766. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  767. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  768. // This makes "Binary" preset visible,
  769. // as long as we care about transfer mode
  770. ((AParam == DefaultParam) &&
  771. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  772. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  773. {
  774. Item = new TMenuItem(Menu);
  775. Item->Caption = Name;
  776. Item->Tag = i;
  777. Item->Checked =
  778. (Preset == Name) && (AParam == Param);
  779. AnyChecked = AnyChecked || Item->Checked;
  780. Item->OnClick = OnClick;
  781. Menu->Items->Add(Item);
  782. }
  783. }
  784. CustomizeItem->Checked = !AnyChecked;
  785. Item = new TMenuItem(Menu);
  786. Item->Caption = L"-";
  787. Menu->Items->Add(Item);
  788. Item = new TMenuItem(Menu);
  789. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  790. Item->Tag = cpiConfigure;
  791. Item->OnClick = OnClick;
  792. Menu->Items->Add(Item);
  793. if (FLAGSET(Options, cplGenerateCode))
  794. {
  795. Item = new TMenuItem(Menu);
  796. Item->Caption = L"-";
  797. Menu->Items->Add(Item);
  798. Item = new TMenuItem(Menu);
  799. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  800. Item->Tag = cpiGenerateCode;
  801. Item->OnClick = OnClick;
  802. Menu->Items->Add(Item);
  803. }
  804. MenuPopup(Menu, Rect, NULL);
  805. }
  806. //---------------------------------------------------------------------------
  807. int __fastcall CopyParamListPopupClick(TObject * Sender,
  808. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  809. bool * SaveSettings)
  810. {
  811. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  812. DebugAssert(Item != NULL);
  813. DebugAssert((Item->Tag >= cpiSavePreset) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  814. int Result;
  815. if (Item->Tag == cpiConfigure)
  816. {
  817. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  818. DoPreferencesDialog(pmPresets);
  819. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  820. if (Result > 0)
  821. {
  822. // For cast, see a comment below
  823. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  824. }
  825. }
  826. else if (Item->Tag == cpiCustom)
  827. {
  828. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  829. }
  830. else if (Item->Tag == cpiSaveSettings)
  831. {
  832. if (DebugAlwaysTrue(SaveSettings != NULL))
  833. {
  834. *SaveSettings = !*SaveSettings;
  835. }
  836. Result = 0;
  837. }
  838. else if (Item->Tag == cpiSavePreset)
  839. {
  840. std::unique_ptr<TCopyParamList> CopyParamList(new TCopyParamList());
  841. *CopyParamList = *GUIConfiguration->CopyParamList;
  842. int Index = -1;
  843. if (DoCopyParamPresetDialog(CopyParamList.get(), Index, cpmAdd, NULL, Param))
  844. {
  845. GUIConfiguration->CopyParamList = CopyParamList.get();
  846. // If saved unmodified, then make this the selected preset
  847. if (*CopyParamList->CopyParams[Index] == Param)
  848. {
  849. Preset = CopyParamList->Names[Index];
  850. }
  851. }
  852. Result = 0;
  853. }
  854. else if (Item->Tag == cpiGenerateCode)
  855. {
  856. Result = -cplGenerateCode;
  857. }
  858. else
  859. {
  860. Preset = (Item->Tag >= 0) ?
  861. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  862. // The cast strips away the "queue" properties of the TGUICopyParamType
  863. // that are not configurable in presets
  864. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  865. Result = 1;
  866. }
  867. return Result;
  868. }
  869. //---------------------------------------------------------------------------
  870. //---------------------------------------------------------------------------
  871. class TCustomCommandPromptsDialog : public TCustomDialog
  872. {
  873. public:
  874. __fastcall TCustomCommandPromptsDialog(
  875. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  876. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults);
  877. bool __fastcall Execute(TUnicodeStringVector & Values);
  878. private:
  879. UnicodeString __fastcall HistoryKey(int Index);
  880. std::vector<THistoryComboBox *> FEdits;
  881. TUnicodeStringVector FPrompts;
  882. UnicodeString FCustomCommandName;
  883. };
  884. //---------------------------------------------------------------------------
  885. __fastcall TCustomCommandPromptsDialog::TCustomCommandPromptsDialog(
  886. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  887. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults) :
  888. TCustomDialog(HelpKeyword)
  889. {
  890. FCustomCommandName = CustomCommandName;
  891. Caption = FMTLOAD(CUSTOM_COMMANDS_PARAMS_TITLE, (FCustomCommandName));
  892. FPrompts = Prompts;
  893. DebugAssert(FPrompts.size() == Defaults.size());
  894. for (size_t Index = 0; Index < FPrompts.size(); Index++)
  895. {
  896. UnicodeString Prompt = FPrompts[Index];
  897. if (Prompt.IsEmpty())
  898. {
  899. Prompt = LoadStr(CUSTOM_COMMANDS_PARAM_PROMPT2);
  900. }
  901. THistoryComboBox * ComboBox = new THistoryComboBox(this);
  902. ComboBox->AutoComplete = false;
  903. AddComboBox(ComboBox, CreateLabel(Prompt));
  904. ComboBox->Items = CustomWinConfiguration->History[HistoryKey(Index)];
  905. ComboBox->Text = Defaults[Index];
  906. FEdits.push_back(ComboBox);
  907. }
  908. }
  909. //---------------------------------------------------------------------------
  910. UnicodeString __fastcall TCustomCommandPromptsDialog::HistoryKey(int Index)
  911. {
  912. UnicodeString Result = FPrompts[Index];
  913. if (Result.IsEmpty())
  914. {
  915. Result = IntToStr(Index);
  916. }
  917. Result = FORMAT(L"%s_%s", (FCustomCommandName, Result));
  918. Result = CustomWinConfiguration->GetValidHistoryKey(Result);
  919. return L"CustomCommandParam_" + Result;
  920. }
  921. //---------------------------------------------------------------------------
  922. bool __fastcall TCustomCommandPromptsDialog::Execute(TUnicodeStringVector & Values)
  923. {
  924. bool Result = TCustomDialog::Execute();
  925. if (Result)
  926. {
  927. for (size_t Index = 0; Index < FEdits.size(); Index++)
  928. {
  929. Values.push_back(FEdits[Index]->Text);
  930. FEdits[Index]->SaveToHistory();
  931. CustomWinConfiguration->History[HistoryKey(Index)] = FEdits[Index]->Items;
  932. }
  933. }
  934. return Result;
  935. }
  936. //---------------------------------------------------------------------------
  937. //---------------------------------------------------------------------------
  938. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  939. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName, const UnicodeString HelpKeyword) :
  940. TInteractiveCustomCommand(ChildCustomCommand)
  941. {
  942. FCustomCommandName = StripEllipsis(StripHotkey(CustomCommandName));
  943. FHelpKeyword = HelpKeyword;
  944. }
  945. //---------------------------------------------------------------------------
  946. void __fastcall TWinInteractiveCustomCommand::PatternHint(int Index, const UnicodeString & Pattern)
  947. {
  948. if (IsPromptPattern(Pattern))
  949. {
  950. UnicodeString Prompt;
  951. UnicodeString Default;
  952. bool Delimit = false;
  953. ParsePromptPattern(Pattern, Prompt, Default, Delimit);
  954. FIndexes.insert(std::make_pair(Index, FPrompts.size()));
  955. FPrompts.push_back(Prompt);
  956. FDefaults.push_back(Default);
  957. }
  958. }
  959. //---------------------------------------------------------------------------
  960. void __fastcall TWinInteractiveCustomCommand::Prompt(
  961. int Index, const UnicodeString & /*Prompt*/, UnicodeString & Value)
  962. {
  963. if (DebugAlwaysTrue(FIndexes.find(Index) != FIndexes.end()))
  964. {
  965. size_t PromptIndex = FIndexes[Index];
  966. if (FValues.empty())
  967. {
  968. UnicodeString HelpKeyword = FHelpKeyword;
  969. if (HelpKeyword.IsEmpty())
  970. {
  971. HelpKeyword = HELP_CUSTOM_COMMAND_PARAM;
  972. }
  973. std::unique_ptr<TCustomCommandPromptsDialog> Dialog(
  974. new TCustomCommandPromptsDialog(FCustomCommandName, HelpKeyword, FPrompts, FDefaults));
  975. if (!Dialog->Execute(FValues))
  976. {
  977. Abort();
  978. }
  979. }
  980. if (DebugAlwaysTrue(FValues.size() == FPrompts.size()) &&
  981. DebugAlwaysTrue(PromptIndex < FValues.size()))
  982. {
  983. Value = FValues[PromptIndex];
  984. }
  985. }
  986. }
  987. //---------------------------------------------------------------------------
  988. void __fastcall TWinInteractiveCustomCommand::Execute(
  989. const UnicodeString & Command, UnicodeString & Value)
  990. {
  991. DWORD DummyExitCode;
  992. ExecuteProcessAndReadOutput(Command, Value, DummyExitCode, false);
  993. // trim trailing cr/lf
  994. Value = TrimRight(Value);
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  998. {
  999. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  1000. }
  1001. //---------------------------------------------------------------------------
  1002. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  1003. {
  1004. TControl * Control = dynamic_cast<TControl *>(Sender);
  1005. DebugAssert(Control != NULL);
  1006. TPoint Point;
  1007. if ((MousePos.x == -1) && (MousePos.y == -1))
  1008. {
  1009. Point = Control->ClientToScreen(TPoint(0, 0));
  1010. }
  1011. else
  1012. {
  1013. Point = Control->ClientToScreen(MousePos);
  1014. }
  1015. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  1016. DebugAssert(PopupMenu != NULL);
  1017. TRect Rect(Point, Point);
  1018. MenuPopup(PopupMenu, Rect, Control);
  1019. Handled = true;
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  1023. {
  1024. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1025. DebugAssert(Item != NULL);
  1026. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1027. DebugAssert(PopupMenu != NULL);
  1028. DebugAssert(PopupMenu->PopupComponent != NULL);
  1029. return PopupMenu->PopupComponent;
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. static void __fastcall SetMenuButtonImages(TButton * Button)
  1033. {
  1034. Button->Images = GetButtonImages(Button);
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. static void __fastcall MenuButtonRescale(TComponent * Sender, TObject * /*Token*/)
  1038. {
  1039. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1040. SetMenuButtonImages(Button);
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall MenuButton(TButton * Button)
  1044. {
  1045. SetMenuButtonImages(Button);
  1046. Button->ImageIndex = UseDarkModeForControl(Button) ? 2 : 0;
  1047. Button->DisabledImageIndex = 1;
  1048. Button->ImageAlignment = iaRight;
  1049. SetRescaleFunction(Button, MenuButtonRescale);
  1050. }
  1051. //---------------------------------------------------------------------------
  1052. TRect __fastcall CalculatePopupRect(TButton * Button)
  1053. {
  1054. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1055. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1056. TRect Rect(UpPoint, DownPoint);
  1057. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1058. int Offset = UseThemes() ? -1 : 0;
  1059. Rect.Inflate(Offset, Offset);
  1060. return Rect;
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1064. {
  1065. MousePos = Control->ClientToScreen(MousePos);
  1066. TRect Rect(MousePos, MousePos);
  1067. return Rect;
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall FixButtonImage(TButton * Button)
  1071. {
  1072. // with themes enabled, button image is by default drawn too high
  1073. if (UseThemes())
  1074. {
  1075. Button->ImageMargins->Top = 1;
  1076. }
  1077. }
  1078. //---------------------------------------------------------------------------
  1079. void __fastcall CenterButtonImage(TButton * Button)
  1080. {
  1081. // with themes disabled, the text seems to be drawn over the icon,
  1082. // so that the padding spaces hide away most of the icon
  1083. if (UseThemes())
  1084. {
  1085. Button->ImageAlignment = iaCenter;
  1086. int ImageWidth = Button->Images->Width;
  1087. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(Button));
  1088. UnicodeString Caption;
  1089. // Centering unlinks the caption from the action
  1090. TAction * Action = dynamic_cast<TAction *>(Button->Action);
  1091. if (Action != NULL)
  1092. {
  1093. Caption = Action->Caption;
  1094. }
  1095. else
  1096. {
  1097. Caption = Button->Caption.Trim();
  1098. }
  1099. UnicodeString Padding;
  1100. while (Canvas->TextWidth(Padding) < ImageWidth)
  1101. {
  1102. Padding += L" ";
  1103. }
  1104. if (Button->IsRightToLeft())
  1105. {
  1106. Caption = Caption + Padding;
  1107. }
  1108. else
  1109. {
  1110. Caption = Padding + Caption;
  1111. }
  1112. Button->Caption = Caption;
  1113. int CaptionWidth = Canvas->TextWidth(Caption);
  1114. // The margins seem to extend the area over which the image is centered,
  1115. // so we have to set it to a double of desired padding.
  1116. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1117. // the one below is equivalent, but with reduced rounding.
  1118. // Without the change, the rounding caused the space between icon and caption too
  1119. // small on 200% zoom.
  1120. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1121. // is approximately same as half of caption width before padding.
  1122. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1123. }
  1124. else
  1125. {
  1126. // at least do not draw it so near to the edge
  1127. Button->ImageMargins->Left = 1;
  1128. }
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1132. {
  1133. int Result = !S.IsEmpty() && StrToInt(S);
  1134. switch (LocaleFlagOverride)
  1135. {
  1136. default:
  1137. case lfoLanguageIfRecommended:
  1138. if (!Recommended)
  1139. {
  1140. Result = Off;
  1141. }
  1142. break;
  1143. case lfoLanguage:
  1144. // noop = as configured in locale
  1145. break;
  1146. case lfoAlways:
  1147. Result = On;
  1148. break;
  1149. case lfoNever:
  1150. Result = Off;
  1151. break;
  1152. }
  1153. return Result;
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1157. {
  1158. if (GlobalOnMinimize == NULL)
  1159. {
  1160. GlobalOnMinimize = OnMinimize;
  1161. }
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1165. {
  1166. if (GlobalOnMinimize == OnMinimize)
  1167. {
  1168. GlobalOnMinimize = NULL;
  1169. }
  1170. }
  1171. //---------------------------------------------------------------------------
  1172. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1173. {
  1174. Configuration->Usage->Inc(L"OperationMinimizations");
  1175. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1176. {
  1177. GlobalOnMinimize(Sender);
  1178. }
  1179. }
  1180. //---------------------------------------------------------------------------
  1181. bool MinimizedToTray = false;
  1182. //---------------------------------------------------------------------------
  1183. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1184. {
  1185. TForm * MainForm = Application->MainForm;
  1186. TForm * MainLikeForm = GetMainForm();
  1187. bool MinimizeToTray;
  1188. if (Minimize)
  1189. {
  1190. MinimizeToTray = WinConfiguration->MinimizeToTray;
  1191. }
  1192. else
  1193. {
  1194. // Use tray restore code, even if minimization to tray is not on anymore when restoring.
  1195. // This is particularly used for ad-hoc minimize to tray from "keep up to date" dialog.
  1196. MinimizeToTray = MinimizedToTray;
  1197. }
  1198. MinimizedToTray = false; // reset in any case, even if we somehow got restored from tray without invoking this code
  1199. if ((MainLikeForm != MainForm) && !MinimizeToTray)
  1200. {
  1201. static TWindowState PreviousWindowState = wsNormal;
  1202. if (Minimize)
  1203. {
  1204. PreviousWindowState = MainLikeForm->WindowState;
  1205. // This works correctly with child windows thanks to Application->OnGetMainFormHandle
  1206. MainLikeForm->WindowState = wsMinimized;
  1207. }
  1208. else
  1209. {
  1210. MainLikeForm->WindowState = PreviousWindowState;
  1211. }
  1212. }
  1213. else
  1214. {
  1215. // What is described below should not ever happen, except when minimizing to tray,
  1216. // as we capture command-line operation above.
  1217. // Had we called TApplication::Minimize, it would hide all non-MainForm windows, including MainLineForm,
  1218. // so it actually also hides taskbar button, what we do not want.
  1219. // WORKAROUND
  1220. // When main window is hidden (command-line operation),
  1221. // we do not want it to be shown by TApplication.Restore,
  1222. // so we temporarily detach it from an application.
  1223. // Probably not really necessary for minimizing phase,
  1224. // but we do it for consistency anyway.
  1225. bool RestoreMainForm = false;
  1226. if (DebugAlwaysTrue(MainForm != NULL) &&
  1227. !MainForm->Visible)
  1228. {
  1229. SetAppMainForm(NULL);
  1230. RestoreMainForm = true;
  1231. }
  1232. try
  1233. {
  1234. if (Minimize)
  1235. {
  1236. Application->Minimize();
  1237. MinimizedToTray = WinConfiguration->MinimizeToTray;
  1238. }
  1239. else
  1240. {
  1241. Application->Restore();
  1242. }
  1243. }
  1244. __finally
  1245. {
  1246. if (RestoreMainForm)
  1247. {
  1248. SetAppMainForm(MainForm);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall ApplicationMinimize()
  1255. {
  1256. DoApplicationMinimizeRestore(true);
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. void __fastcall ApplicationRestore()
  1260. {
  1261. DoApplicationMinimizeRestore(false);
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. bool __fastcall IsApplicationMinimized()
  1265. {
  1266. // VCL help recommends handling Application->OnMinimize/OnRestore
  1267. // for tracking state, but OnRestore is actually not called
  1268. // (OnMinimize is), when app is minimized from e.g. Progress window
  1269. bool AppMinimized = IsIconic(Application->Handle);
  1270. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1271. return AppMinimized || MainFormMinimized;
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1275. {
  1276. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1277. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1278. bool Result = (Cmd == SC_MINIMIZE);
  1279. if (Result)
  1280. {
  1281. ApplicationMinimize();
  1282. SysCommand.Result = 1;
  1283. }
  1284. return Result;
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall ClickToolbarItem(TTBCustomItem * Item, bool PositionCursor)
  1288. {
  1289. TTBCustomItem * TopItem = Item;
  1290. while (TopItem->Parent != NULL)
  1291. {
  1292. TopItem = TopItem->Parent;
  1293. }
  1294. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(TopItem->ParentComponent);
  1295. DebugAssert(Toolbar != NULL);
  1296. TTBItemViewer * Viewer = Toolbar->View->Find(Item);
  1297. DebugAssert(Viewer != NULL);
  1298. int X = Viewer->BoundsRect.Left + (Viewer->BoundsRect.Width() / 2);
  1299. int Y = Viewer->BoundsRect.Top + (Viewer->BoundsRect.Height() / 2);
  1300. if (PositionCursor)
  1301. {
  1302. Mouse->CursorPos = Toolbar->ClientToScreen(TPoint(X, Y));
  1303. }
  1304. PostMessage(Toolbar->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(X, Y));
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. //---------------------------------------------------------------------------
  1308. UnicodeString DumpCallstackEventName(int ProcessId)
  1309. {
  1310. return FORMAT(DUMPCALLSTACK_EVENT, (ProcessId));
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. UnicodeString DumpCallstackFileName(int ProcessId)
  1314. {
  1315. UnicodeString FileName = FORMAT(L"%s.txt", (DumpCallstackEventName(ProcessId)));
  1316. UnicodeString Result = CombinePaths(SystemTemporaryDirectory(), FileName);
  1317. return Result;
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. void CheckConfigurationForceSave()
  1321. {
  1322. if (UseAlternativeFunction() && Configuration->Persistent &&
  1323. (Configuration->Storage == stIniFile) && Sysutils::FileExists(ApiPath(Configuration->IniFileStorageName)) &&
  1324. !Configuration->ForceSave)
  1325. {
  1326. int Attr = GetFileAttributes(ApiPath(Configuration->IniFileStorageName).c_str());
  1327. if (FLAGSET(Attr, FILE_ATTRIBUTE_READONLY))
  1328. {
  1329. UnicodeString Message = FMTLOAD(READONLY_INI_FILE_OVERWRITE, (Configuration->IniFileStorageName));
  1330. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_READONLY_INI_FILE) == qaOK)
  1331. {
  1332. Configuration->ForceSave = true;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. //---------------------------------------------------------------------------
  1338. class TCallstackThread : public TSignalThread
  1339. {
  1340. public:
  1341. __fastcall TCallstackThread();
  1342. protected:
  1343. virtual void __fastcall ProcessEvent();
  1344. private:
  1345. static HANDLE DoCreateEvent();
  1346. };
  1347. //---------------------------------------------------------------------------
  1348. __fastcall TCallstackThread::TCallstackThread() :
  1349. TSignalThread(true, DoCreateEvent())
  1350. {
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TCallstackThread::ProcessEvent()
  1354. {
  1355. try
  1356. {
  1357. UnicodeString Path = DumpCallstackFileName(GetCurrentProcessId());
  1358. std::unique_ptr<TStrings> StackStrings;
  1359. HANDLE MainThreadHandle = reinterpret_cast<HANDLE>(MainThreadID);
  1360. if (SuspendThread(MainThreadHandle) < 0)
  1361. {
  1362. RaiseLastOSError();
  1363. }
  1364. try
  1365. {
  1366. TJclStackInfoList * StackInfoList = JclCreateThreadStackTraceFromID(true, MainThreadID);
  1367. if (StackInfoList == NULL)
  1368. {
  1369. RaiseLastOSError();
  1370. }
  1371. StackStrings.reset(StackInfoListToStrings(StackInfoList));
  1372. }
  1373. __finally
  1374. {
  1375. if (ResumeThread(MainThreadHandle) < 0)
  1376. {
  1377. RaiseLastOSError();
  1378. }
  1379. }
  1380. TFile::WriteAllText(Path, StackStrings->Text);
  1381. }
  1382. catch (...)
  1383. {
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. HANDLE TCallstackThread::DoCreateEvent()
  1388. {
  1389. UnicodeString Name = DumpCallstackEventName(GetCurrentProcessId());
  1390. return CreateEvent(NULL, false, false, Name.c_str());
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. //---------------------------------------------------------------------------
  1394. std::unique_ptr<TCallstackThread> CallstackThread;
  1395. //---------------------------------------------------------------------------
  1396. static void __fastcall AppGetMainFormHandle(void * /*Data*/, HWND & Handle)
  1397. {
  1398. TForm * MainForm = GetMainForm();
  1399. // This, among other, causes minimizing of the top-level non-MainForm minimize other child windows.
  1400. // Like clicking "Minimize" on Progress window over Synchronization progress window over Synchronization checklist window.
  1401. // Would also have a lot of other effects (hopefully positive) and may render lot of existing MainFormLike code obsolete.
  1402. if ((MainForm != NULL) && IsMainFormLike(MainForm) && MainForm->HandleAllocated())
  1403. {
  1404. Handle = MainForm->Handle;
  1405. }
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. void __fastcall WinInitialize()
  1409. {
  1410. if (JclHookExceptions())
  1411. {
  1412. JclStackTrackingOptions << stAllModules;
  1413. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1414. CallstackThread.reset(new TCallstackThread());
  1415. CallstackThread->Start();
  1416. }
  1417. SetErrorMode(SEM_FAILCRITICALERRORS);
  1418. OnApiPath = ApiPath;
  1419. MainThread = GetCurrentThreadId();
  1420. Application->OnGetMainFormHandle = MakeMethod<TGetHandleEvent>(NULL, AppGetMainFormHandle);
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall WinFinalize()
  1424. {
  1425. CallstackThread.reset(NULL);
  1426. JclRemoveExceptNotifier(DoExceptNotify);
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1430. {
  1431. FVisible = false;
  1432. FOnClick = NULL;
  1433. FOnBalloonClick = NULL;
  1434. FBalloonUserData = NULL;
  1435. FTrayIcon = new NOTIFYICONDATA;
  1436. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1437. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1438. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1439. // LoadIconMetric is available from Windows Vista only
  1440. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1441. if (DebugAlwaysTrue(ComCtl32Dll))
  1442. {
  1443. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1444. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1445. if (LoadIconMetric != NULL)
  1446. {
  1447. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1448. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1449. }
  1450. }
  1451. if (FTrayIcon->hIcon == 0)
  1452. {
  1453. FTrayIcon->hIcon = Application->Icon->Handle;
  1454. }
  1455. FTrayIcon->uID = Id;
  1456. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1457. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1458. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1459. }
  1460. //---------------------------------------------------------------------------
  1461. __fastcall ::TTrayIcon::~TTrayIcon()
  1462. {
  1463. // make sure we hide icon even in case it was shown just to pop up the balloon
  1464. // (in which case Visible == false)
  1465. CancelBalloon();
  1466. Visible = false;
  1467. DeallocateHWnd(FTrayIcon->hWnd);
  1468. delete FTrayIcon;
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1472. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1473. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1474. {
  1475. if (Timeout > 30000)
  1476. {
  1477. // this is probably system limit, do not try more, especially for
  1478. // the timeout-driven hiding of the tray icon (for Win2k)
  1479. Timeout = 30000;
  1480. }
  1481. FTrayIcon->uFlags |= NIF_INFO;
  1482. AppLogFmt("Tray popup balloon: %s - %s", (Title, Str));
  1483. Title = Title + TitleSeparator + AppNameString();
  1484. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1485. UnicodeString Info = Str;
  1486. // When szInfo is empty, balloon is not shown
  1487. // (or actually it means the balloon should be deleted, if any)
  1488. if (Info.IsEmpty())
  1489. {
  1490. Info = L" ";
  1491. }
  1492. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1493. FTrayIcon->uTimeout = Timeout;
  1494. switch (QueryType)
  1495. {
  1496. case qtError:
  1497. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1498. break;
  1499. case qtInformation:
  1500. case qtConfirmation:
  1501. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1502. break;
  1503. case qtWarning:
  1504. default:
  1505. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1506. break;
  1507. }
  1508. KillTimer(FTrayIcon->hWnd, 1);
  1509. if (Visible)
  1510. {
  1511. Update();
  1512. }
  1513. else
  1514. {
  1515. Notify(NIM_ADD);
  1516. }
  1517. FOnBalloonClick = OnBalloonClick;
  1518. delete FBalloonUserData;
  1519. FBalloonUserData = BalloonUserData;
  1520. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1521. // unless CancelBalloon is called explicitly
  1522. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall ::TTrayIcon::BalloonCancelled()
  1526. {
  1527. FOnBalloonClick = NULL;
  1528. delete FBalloonUserData;
  1529. FBalloonUserData = NULL;
  1530. }
  1531. //---------------------------------------------------------------------------
  1532. void __fastcall ::TTrayIcon::CancelBalloon()
  1533. {
  1534. KillTimer(FTrayIcon->hWnd, 1);
  1535. if (Visible)
  1536. {
  1537. FTrayIcon->uFlags |= NIF_INFO;
  1538. FTrayIcon->szInfo[0] = L'\0';
  1539. Update();
  1540. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1541. }
  1542. else
  1543. {
  1544. Notify(NIM_DELETE);
  1545. }
  1546. BalloonCancelled();
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1550. {
  1551. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1552. if (Result && (Message == NIM_ADD))
  1553. {
  1554. UINT Timeout = FTrayIcon->uTimeout;
  1555. try
  1556. {
  1557. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1558. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1559. }
  1560. __finally
  1561. {
  1562. FTrayIcon->uTimeout = Timeout;
  1563. }
  1564. }
  1565. return Result;
  1566. }
  1567. //---------------------------------------------------------------------------
  1568. void __fastcall ::TTrayIcon::Update()
  1569. {
  1570. if (Visible)
  1571. {
  1572. Notify(NIM_MODIFY);
  1573. }
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1577. {
  1578. if (Visible != value)
  1579. {
  1580. if (value)
  1581. {
  1582. FVisible = Notify(NIM_ADD);
  1583. }
  1584. else
  1585. {
  1586. FVisible = false;
  1587. KillTimer(FTrayIcon->hWnd, 1);
  1588. Notify(NIM_DELETE);
  1589. BalloonCancelled();
  1590. }
  1591. }
  1592. }
  1593. //---------------------------------------------------------------------------
  1594. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1595. {
  1596. try
  1597. {
  1598. if (Message.Msg == WM_TRAY_ICON)
  1599. {
  1600. DebugAssert(Message.WParam == 0);
  1601. switch (Message.LParam)
  1602. {
  1603. // old shell32
  1604. case WM_LBUTTONUP:
  1605. case WM_RBUTTONUP:
  1606. // new shell32:
  1607. case WM_CONTEXTMENU:
  1608. if (OnClick != NULL)
  1609. {
  1610. OnClick(NULL);
  1611. }
  1612. Message.Result = true;
  1613. break;
  1614. }
  1615. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1616. {
  1617. if (FOnBalloonClick != NULL)
  1618. {
  1619. // prevent the user data from being freed by possible call
  1620. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1621. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1622. FBalloonUserData = NULL;
  1623. FOnBalloonClick(UserData.get());
  1624. }
  1625. else if (OnClick != NULL)
  1626. {
  1627. OnClick(NULL);
  1628. }
  1629. }
  1630. switch (Message.LParam)
  1631. {
  1632. case NIN_BALLOONHIDE:
  1633. case NIN_BALLOONTIMEOUT:
  1634. case NIN_BALLOONUSERCLICK:
  1635. KillTimer(FTrayIcon->hWnd, 1);
  1636. // if icon was shown just to display balloon, hide it with the balloon
  1637. if (!Visible)
  1638. {
  1639. Notify(NIM_DELETE);
  1640. }
  1641. BalloonCancelled();
  1642. break;
  1643. }
  1644. }
  1645. else if (Message.Msg == WM_TIMER)
  1646. {
  1647. // sanity check
  1648. Notify(NIM_DELETE);
  1649. BalloonCancelled();
  1650. }
  1651. else if (Message.Msg == FTaskbarCreatedMsg)
  1652. {
  1653. if (Visible)
  1654. {
  1655. // force recreation
  1656. Visible = false;
  1657. Visible = true;
  1658. }
  1659. }
  1660. else
  1661. {
  1662. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1663. }
  1664. }
  1665. catch(Exception & E)
  1666. {
  1667. Application->HandleException(&E);
  1668. }
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1672. {
  1673. return FTrayIcon->szTip;
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1677. {
  1678. if (Hint != value)
  1679. {
  1680. unsigned int Max = LENOF(FTrayIcon->szTip);
  1681. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1682. Update();
  1683. }
  1684. }
  1685. //---------------------------------------------------------------------------