WinInterface.cpp 57 KB

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