WinInterface.cpp 60 KB

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