WinInterface.cpp 58 KB

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