WinInterface.cpp 61 KB

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