WinInterface.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  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. HANDLE StdOutOutput;
  1006. HANDLE StdOutInput;
  1007. HANDLE StdInOutput;
  1008. HANDLE StdInInput;
  1009. SECURITY_ATTRIBUTES SecurityAttributes;
  1010. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  1011. SecurityAttributes.lpSecurityDescriptor = NULL;
  1012. SecurityAttributes.bInheritHandle = TRUE;
  1013. try
  1014. {
  1015. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  1016. {
  1017. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  1018. }
  1019. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  1020. {
  1021. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  1022. }
  1023. else
  1024. {
  1025. STARTUPINFO StartupInfo;
  1026. PROCESS_INFORMATION ProcessInformation;
  1027. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  1028. StartupInfo.cb = sizeof(StartupInfo);
  1029. StartupInfo.wShowWindow = SW_HIDE;
  1030. StartupInfo.hStdInput = StdInOutput;
  1031. StartupInfo.hStdOutput = StdOutInput;
  1032. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1033. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  1034. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  1035. {
  1036. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  1037. }
  1038. else
  1039. {
  1040. try
  1041. {
  1042. // wait until the console program terminated
  1043. bool Running = true;
  1044. while (Running)
  1045. {
  1046. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  1047. {
  1048. case WAIT_TIMEOUT:
  1049. Application->ProcessMessages();
  1050. break;
  1051. case WAIT_OBJECT_0:
  1052. Running = false;
  1053. break;
  1054. default:
  1055. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  1056. }
  1057. }
  1058. char Buffer[1024];
  1059. unsigned long Read;
  1060. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  1061. (Read > 0))
  1062. {
  1063. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  1064. {
  1065. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  1066. }
  1067. else if (Read > 0)
  1068. {
  1069. Value += AnsiToString(Buffer, Read);
  1070. }
  1071. }
  1072. // trim trailing cr/lf
  1073. Value = TrimRight(Value);
  1074. }
  1075. __finally
  1076. {
  1077. CloseHandle(ProcessInformation.hProcess);
  1078. CloseHandle(ProcessInformation.hThread);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. __finally
  1084. {
  1085. if (StdOutOutput != INVALID_HANDLE_VALUE)
  1086. {
  1087. CloseHandle(StdOutOutput);
  1088. }
  1089. if (StdOutInput != INVALID_HANDLE_VALUE)
  1090. {
  1091. CloseHandle(StdOutInput);
  1092. }
  1093. if (StdInOutput != INVALID_HANDLE_VALUE)
  1094. {
  1095. CloseHandle(StdInOutput);
  1096. }
  1097. if (StdInInput != INVALID_HANDLE_VALUE)
  1098. {
  1099. CloseHandle(StdInInput);
  1100. }
  1101. }
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  1105. {
  1106. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  1110. {
  1111. TControl * Control = dynamic_cast<TControl *>(Sender);
  1112. DebugAssert(Control != NULL);
  1113. TPoint Point;
  1114. if ((MousePos.x == -1) && (MousePos.y == -1))
  1115. {
  1116. Point = Control->ClientToScreen(TPoint(0, 0));
  1117. }
  1118. else
  1119. {
  1120. Point = Control->ClientToScreen(MousePos);
  1121. }
  1122. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  1123. DebugAssert(PopupMenu != NULL);
  1124. TRect Rect(Point, Point);
  1125. MenuPopup(PopupMenu, Rect, Control);
  1126. Handled = true;
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  1130. {
  1131. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1132. DebugAssert(Item != NULL);
  1133. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1134. DebugAssert(PopupMenu != NULL);
  1135. DebugAssert(PopupMenu->PopupComponent != NULL);
  1136. return PopupMenu->PopupComponent;
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. static void __fastcall SetMenuButtonImages(TButton * Button)
  1140. {
  1141. Button->Images = GetButtonImages(Button);
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. static void __fastcall MenuButtonRescale(TComponent * Sender, TObject * /*Token*/)
  1145. {
  1146. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1147. SetMenuButtonImages(Button);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall MenuButton(TButton * Button)
  1151. {
  1152. SetMenuButtonImages(Button);
  1153. Button->ImageIndex = 0;
  1154. Button->DisabledImageIndex = 1;
  1155. Button->ImageAlignment = iaRight;
  1156. SetRescaleFunction(Button, MenuButtonRescale);
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. TRect __fastcall CalculatePopupRect(TButton * Button)
  1160. {
  1161. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1162. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1163. TRect Rect(UpPoint, DownPoint);
  1164. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1165. int Offset = UseThemes() ? -1 : 0;
  1166. Rect.Inflate(Offset, Offset);
  1167. return Rect;
  1168. }
  1169. //---------------------------------------------------------------------------
  1170. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1171. {
  1172. MousePos = Control->ClientToScreen(MousePos);
  1173. TRect Rect(MousePos, MousePos);
  1174. return Rect;
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. void __fastcall FixButtonImage(TButton * Button)
  1178. {
  1179. // with themes enabled, button image is by default drawn too high
  1180. if (UseThemes())
  1181. {
  1182. Button->ImageMargins->Top = 1;
  1183. }
  1184. }
  1185. //---------------------------------------------------------------------------
  1186. void __fastcall CenterButtonImage(TButton * Button)
  1187. {
  1188. // with themes disabled, the text seems to be drawn over the icon,
  1189. // so that the padding spaces hide away most of the icon
  1190. if (UseThemes())
  1191. {
  1192. Button->ImageAlignment = iaCenter;
  1193. int ImageWidth = Button->Images->Width;
  1194. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(Button));
  1195. UnicodeString Caption;
  1196. // Centering unlinks the caption from the action
  1197. TAction * Action = dynamic_cast<TAction *>(Button->Action);
  1198. if (Action != NULL)
  1199. {
  1200. Caption = Action->Caption;
  1201. }
  1202. else
  1203. {
  1204. Caption = Button->Caption.Trim();
  1205. }
  1206. UnicodeString Padding;
  1207. while (Canvas->TextWidth(Padding) < ImageWidth)
  1208. {
  1209. Padding += L" ";
  1210. }
  1211. if (Button->IsRightToLeft())
  1212. {
  1213. Caption = Caption + Padding;
  1214. }
  1215. else
  1216. {
  1217. Caption = Padding + Caption;
  1218. }
  1219. Button->Caption = Caption;
  1220. int CaptionWidth = Canvas->TextWidth(Caption);
  1221. // The margins seem to extend the area over which the image is centered,
  1222. // so we have to set it to a double of desired padding.
  1223. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1224. // the one below is equivalent, but with reduced rouding.
  1225. // Without the change, the rounding caused the space between icon and caption too
  1226. // small on 200% zoom.
  1227. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1228. // is approximatelly same as half of caption width before padding.
  1229. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1230. }
  1231. else
  1232. {
  1233. // at least do not draw it so near to the edge
  1234. Button->ImageMargins->Left = 1;
  1235. }
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1239. {
  1240. int Result = !S.IsEmpty() && StrToInt(S);
  1241. switch (LocaleFlagOverride)
  1242. {
  1243. default:
  1244. case lfoLanguageIfRecommended:
  1245. if (!Recommended)
  1246. {
  1247. Result = Off;
  1248. }
  1249. break;
  1250. case lfoLanguage:
  1251. // noop = as configured in locale
  1252. break;
  1253. case lfoAlways:
  1254. Result = On;
  1255. break;
  1256. case lfoNever:
  1257. Result = Off;
  1258. break;
  1259. }
  1260. return Result;
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1264. {
  1265. if (GlobalOnMinimize == NULL)
  1266. {
  1267. GlobalOnMinimize = OnMinimize;
  1268. }
  1269. }
  1270. //---------------------------------------------------------------------------
  1271. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1272. {
  1273. if (GlobalOnMinimize == OnMinimize)
  1274. {
  1275. GlobalOnMinimize = NULL;
  1276. }
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1280. {
  1281. Configuration->Usage->Inc(L"OperationMinimizations");
  1282. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1283. {
  1284. GlobalOnMinimize(Sender);
  1285. }
  1286. }
  1287. //---------------------------------------------------------------------------
  1288. bool MinimizedToTray = false;
  1289. //---------------------------------------------------------------------------
  1290. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1291. {
  1292. TForm * MainForm = Application->MainForm;
  1293. TForm * MainLikeForm = GetMainForm();
  1294. bool MinimizeToTray;
  1295. if (Minimize)
  1296. {
  1297. MinimizeToTray = WinConfiguration->MinimizeToTray;
  1298. }
  1299. else
  1300. {
  1301. // Use tray restore code, even if minimization to tray is not on anymore when restoring.
  1302. // This is particularly used for ad-hoc minimize to tray from "keep up to date" dialog.
  1303. MinimizeToTray = MinimizedToTray;
  1304. }
  1305. MinimizedToTray = false; // reset in any case, even if we somehow got restored from tray without invoking this code
  1306. if ((MainLikeForm != MainForm) && !MinimizeToTray)
  1307. {
  1308. static TWindowState PreviousWindowState = wsNormal;
  1309. if (Minimize)
  1310. {
  1311. PreviousWindowState = MainLikeForm->WindowState;
  1312. // This works correctly with child windows thanks to Application->OnGetMainFormHandle
  1313. MainLikeForm->WindowState = wsMinimized;
  1314. }
  1315. else
  1316. {
  1317. MainLikeForm->WindowState = PreviousWindowState;
  1318. }
  1319. }
  1320. else
  1321. {
  1322. // What is described below should not ever happen, except when minimizing to tray,
  1323. // as we capture command-line operation above.
  1324. // Had we called TApplication::Minimize, it would hide all non-MainForm windows, including MainLineForm,
  1325. // so it actually also hides taskbar button, what we do not want.
  1326. // WORKAROUND
  1327. // When main window is hidden (command-line operation),
  1328. // we do not want it to be shown by TApplication.Restore,
  1329. // so we temporarily detach it from an application.
  1330. // Probably not really necessary for minimizing phase,
  1331. // but we do it for consistency anyway.
  1332. bool RestoreMainForm = false;
  1333. if (DebugAlwaysTrue(MainForm != NULL) &&
  1334. !MainForm->Visible)
  1335. {
  1336. SetAppMainForm(NULL);
  1337. RestoreMainForm = true;
  1338. }
  1339. try
  1340. {
  1341. if (Minimize)
  1342. {
  1343. Application->Minimize();
  1344. MinimizedToTray = WinConfiguration->MinimizeToTray;
  1345. }
  1346. else
  1347. {
  1348. Application->Restore();
  1349. }
  1350. }
  1351. __finally
  1352. {
  1353. if (RestoreMainForm)
  1354. {
  1355. SetAppMainForm(MainForm);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. void __fastcall ApplicationMinimize()
  1362. {
  1363. DoApplicationMinimizeRestore(true);
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. void __fastcall ApplicationRestore()
  1367. {
  1368. DoApplicationMinimizeRestore(false);
  1369. }
  1370. //---------------------------------------------------------------------------
  1371. bool __fastcall IsApplicationMinimized()
  1372. {
  1373. // VCL help recommends handling Application->OnMinimize/OnRestore
  1374. // for tracking state, but OnRestore is actually not called
  1375. // (OnMinimize is), when app is minimized from e.g. Progress window
  1376. bool AppMinimized = IsIconic(Application->Handle);
  1377. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1378. return AppMinimized || MainFormMinimized;
  1379. }
  1380. //---------------------------------------------------------------------------
  1381. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1382. {
  1383. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1384. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1385. bool Result = (Cmd == SC_MINIMIZE);
  1386. if (Result)
  1387. {
  1388. ApplicationMinimize();
  1389. SysCommand.Result = 1;
  1390. }
  1391. return Result;
  1392. }
  1393. //---------------------------------------------------------------------------
  1394. void __fastcall ClickToolbarItem(TTBCustomItem * Item, bool PositionCursor)
  1395. {
  1396. TTBCustomItem * TopItem = Item;
  1397. while (TopItem->Parent != NULL)
  1398. {
  1399. TopItem = TopItem->Parent;
  1400. }
  1401. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(TopItem->ParentComponent);
  1402. DebugAssert(Toolbar != NULL);
  1403. TTBItemViewer * Viewer = Toolbar->View->Find(Item);
  1404. DebugAssert(Viewer != NULL);
  1405. int X = Viewer->BoundsRect.Left + (Viewer->BoundsRect.Width() / 2);
  1406. int Y = Viewer->BoundsRect.Top + (Viewer->BoundsRect.Height() / 2);
  1407. if (PositionCursor)
  1408. {
  1409. Mouse->CursorPos = Toolbar->ClientToScreen(TPoint(X, Y));
  1410. }
  1411. PostMessage(Toolbar->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(X, Y));
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. //---------------------------------------------------------------------------
  1415. UnicodeString DumpCallstackEventName(int ProcessId)
  1416. {
  1417. return FORMAT(DUMPCALLSTACK_EVENT, (ProcessId));
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. UnicodeString DumpCallstackFileName(int ProcessId)
  1421. {
  1422. UnicodeString FileName = FORMAT(L"%s.txt", (DumpCallstackEventName(ProcessId)));
  1423. UnicodeString Result = TPath::Combine(SystemTemporaryDirectory(), FileName);
  1424. return Result;
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. void CheckConfigurationForceSave()
  1428. {
  1429. if (UseAlternativeFunction() && Configuration->Persistent &&
  1430. (Configuration->Storage == stIniFile) && Sysutils::FileExists(ApiPath(Configuration->IniFileStorageName)) &&
  1431. !Configuration->ForceSave)
  1432. {
  1433. int Attr = GetFileAttributes(ApiPath(Configuration->IniFileStorageName).c_str());
  1434. if (FLAGSET(Attr, FILE_ATTRIBUTE_READONLY))
  1435. {
  1436. UnicodeString Message = FMTLOAD(READONLY_INI_FILE_OVERWRITE, (Configuration->IniFileStorageName));
  1437. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_READONLY_INI_FILE) == qaOK)
  1438. {
  1439. Configuration->ForceSave = true;
  1440. }
  1441. }
  1442. }
  1443. }
  1444. //---------------------------------------------------------------------------
  1445. class TCallstackThread : public TSignalThread
  1446. {
  1447. public:
  1448. __fastcall TCallstackThread();
  1449. protected:
  1450. virtual void __fastcall ProcessEvent();
  1451. private:
  1452. static HANDLE DoCreateEvent();
  1453. };
  1454. //---------------------------------------------------------------------------
  1455. __fastcall TCallstackThread::TCallstackThread() :
  1456. TSignalThread(true, DoCreateEvent())
  1457. {
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. void __fastcall TCallstackThread::ProcessEvent()
  1461. {
  1462. try
  1463. {
  1464. UnicodeString Path = DumpCallstackFileName(GetCurrentProcessId());
  1465. std::unique_ptr<TStrings> StackStrings;
  1466. HANDLE MainThreadHandle = reinterpret_cast<HANDLE>(MainThreadID);
  1467. if (SuspendThread(MainThreadHandle) < 0)
  1468. {
  1469. RaiseLastOSError();
  1470. }
  1471. try
  1472. {
  1473. TJclStackInfoList * StackInfoList = JclCreateThreadStackTraceFromID(true, MainThreadID);
  1474. if (StackInfoList == NULL)
  1475. {
  1476. RaiseLastOSError();
  1477. }
  1478. StackStrings.reset(StackInfoListToStrings(StackInfoList));
  1479. }
  1480. __finally
  1481. {
  1482. if (ResumeThread(MainThreadHandle) < 0)
  1483. {
  1484. RaiseLastOSError();
  1485. }
  1486. }
  1487. TFile::WriteAllText(Path, StackStrings->Text);
  1488. }
  1489. catch (...)
  1490. {
  1491. }
  1492. }
  1493. //---------------------------------------------------------------------------
  1494. HANDLE TCallstackThread::DoCreateEvent()
  1495. {
  1496. UnicodeString Name = DumpCallstackEventName(GetCurrentProcessId());
  1497. return CreateEvent(NULL, false, false, Name.c_str());
  1498. }
  1499. //---------------------------------------------------------------------------
  1500. //---------------------------------------------------------------------------
  1501. std::unique_ptr<TCallstackThread> CallstackThread;
  1502. //---------------------------------------------------------------------------
  1503. static void __fastcall AppGetMainFormHandle(void * /*Data*/, HWND & Handle)
  1504. {
  1505. TForm * MainForm = GetMainForm();
  1506. // This, among other, causes minimizing of the top-level non-MainForm minimize other child windows.
  1507. // Like clicking "Minimize" on Progress window over Synchronization progress window over Synchronization checklist window.
  1508. // Would also have a lot of other effects (hopefully possitive) and may render lot of existing MainFormLike code obsolete.
  1509. if ((MainForm != NULL) && IsMainFormLike(MainForm) && MainForm->HandleAllocated())
  1510. {
  1511. Handle = MainForm->Handle;
  1512. }
  1513. }
  1514. //---------------------------------------------------------------------------
  1515. void __fastcall WinInitialize()
  1516. {
  1517. if (JclHookExceptions())
  1518. {
  1519. JclStackTrackingOptions << stAllModules;
  1520. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1521. CallstackThread.reset(new TCallstackThread());
  1522. CallstackThread->Start();
  1523. }
  1524. SetErrorMode(SEM_FAILCRITICALERRORS);
  1525. OnApiPath = ApiPath;
  1526. MainThread = GetCurrentThreadId();
  1527. Application->OnGetMainFormHandle = MakeMethod<TGetHandleEvent>(NULL, AppGetMainFormHandle);
  1528. #pragma warn -8111
  1529. #pragma warn .8111
  1530. }
  1531. //---------------------------------------------------------------------------
  1532. void __fastcall WinFinalize()
  1533. {
  1534. CallstackThread.reset(NULL);
  1535. JclRemoveExceptNotifier(DoExceptNotify);
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1539. {
  1540. FVisible = false;
  1541. FOnClick = NULL;
  1542. FOnBalloonClick = NULL;
  1543. FBalloonUserData = NULL;
  1544. FTrayIcon = new NOTIFYICONDATA;
  1545. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1546. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1547. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1548. // LoadIconMetric is available from Windows Vista only
  1549. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1550. if (DebugAlwaysTrue(ComCtl32Dll))
  1551. {
  1552. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1553. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1554. if (LoadIconMetric != NULL)
  1555. {
  1556. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1557. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1558. }
  1559. }
  1560. if (FTrayIcon->hIcon == 0)
  1561. {
  1562. FTrayIcon->hIcon = Application->Icon->Handle;
  1563. }
  1564. FTrayIcon->uID = Id;
  1565. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1566. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1567. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. __fastcall ::TTrayIcon::~TTrayIcon()
  1571. {
  1572. // make sure we hide icon even in case it was shown just to pop up the balloon
  1573. // (in which case Visible == false)
  1574. CancelBalloon();
  1575. Visible = false;
  1576. DeallocateHWnd(FTrayIcon->hWnd);
  1577. delete FTrayIcon;
  1578. }
  1579. //---------------------------------------------------------------------------
  1580. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1581. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1582. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1583. {
  1584. if (Timeout > 30000)
  1585. {
  1586. // this is probably system limit, do not try more, especially for
  1587. // the timeout-driven hiding of the tray icon (for Win2k)
  1588. Timeout = 30000;
  1589. }
  1590. FTrayIcon->uFlags |= NIF_INFO;
  1591. AppLogFmt("Tray popup balloon: %s - %s", (Title, Str));
  1592. Title = Title + TitleSeparator + AppNameString();
  1593. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1594. UnicodeString Info = Str;
  1595. // When szInfo is empty, balloon is not shown
  1596. // (or actually it means the balloon should be deleted, if any)
  1597. if (Info.IsEmpty())
  1598. {
  1599. Info = L" ";
  1600. }
  1601. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1602. FTrayIcon->uTimeout = Timeout;
  1603. switch (QueryType)
  1604. {
  1605. case qtError:
  1606. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1607. break;
  1608. case qtInformation:
  1609. case qtConfirmation:
  1610. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1611. break;
  1612. case qtWarning:
  1613. default:
  1614. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1615. break;
  1616. }
  1617. KillTimer(FTrayIcon->hWnd, 1);
  1618. if (Visible)
  1619. {
  1620. Update();
  1621. }
  1622. else
  1623. {
  1624. Notify(NIM_ADD);
  1625. }
  1626. FOnBalloonClick = OnBalloonClick;
  1627. delete FBalloonUserData;
  1628. FBalloonUserData = BalloonUserData;
  1629. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1630. // unless CancelBalloon is called explicitly
  1631. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1632. }
  1633. //---------------------------------------------------------------------------
  1634. void __fastcall ::TTrayIcon::BalloonCancelled()
  1635. {
  1636. FOnBalloonClick = NULL;
  1637. delete FBalloonUserData;
  1638. FBalloonUserData = NULL;
  1639. }
  1640. //---------------------------------------------------------------------------
  1641. void __fastcall ::TTrayIcon::CancelBalloon()
  1642. {
  1643. KillTimer(FTrayIcon->hWnd, 1);
  1644. if (Visible)
  1645. {
  1646. FTrayIcon->uFlags |= NIF_INFO;
  1647. FTrayIcon->szInfo[0] = L'\0';
  1648. Update();
  1649. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1650. }
  1651. else
  1652. {
  1653. Notify(NIM_DELETE);
  1654. }
  1655. BalloonCancelled();
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1659. {
  1660. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1661. if (Result && (Message == NIM_ADD))
  1662. {
  1663. UINT Timeout = FTrayIcon->uTimeout;
  1664. try
  1665. {
  1666. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1667. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1668. }
  1669. __finally
  1670. {
  1671. FTrayIcon->uTimeout = Timeout;
  1672. }
  1673. }
  1674. return Result;
  1675. }
  1676. //---------------------------------------------------------------------------
  1677. void __fastcall ::TTrayIcon::Update()
  1678. {
  1679. if (Visible)
  1680. {
  1681. Notify(NIM_MODIFY);
  1682. }
  1683. }
  1684. //---------------------------------------------------------------------------
  1685. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1686. {
  1687. if (Visible != value)
  1688. {
  1689. if (value)
  1690. {
  1691. FVisible = Notify(NIM_ADD);
  1692. }
  1693. else
  1694. {
  1695. FVisible = false;
  1696. KillTimer(FTrayIcon->hWnd, 1);
  1697. Notify(NIM_DELETE);
  1698. BalloonCancelled();
  1699. }
  1700. }
  1701. }
  1702. //---------------------------------------------------------------------------
  1703. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1704. {
  1705. try
  1706. {
  1707. if (Message.Msg == WM_TRAY_ICON)
  1708. {
  1709. DebugAssert(Message.WParam == 0);
  1710. switch (Message.LParam)
  1711. {
  1712. // old shell32
  1713. case WM_LBUTTONUP:
  1714. case WM_RBUTTONUP:
  1715. // new shell32:
  1716. case WM_CONTEXTMENU:
  1717. if (OnClick != NULL)
  1718. {
  1719. OnClick(NULL);
  1720. }
  1721. Message.Result = true;
  1722. break;
  1723. }
  1724. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1725. {
  1726. if (FOnBalloonClick != NULL)
  1727. {
  1728. // prevent the user data from being freed by possible call
  1729. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1730. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1731. FBalloonUserData = NULL;
  1732. FOnBalloonClick(UserData.get());
  1733. }
  1734. else if (OnClick != NULL)
  1735. {
  1736. OnClick(NULL);
  1737. }
  1738. }
  1739. switch (Message.LParam)
  1740. {
  1741. case NIN_BALLOONHIDE:
  1742. case NIN_BALLOONTIMEOUT:
  1743. case NIN_BALLOONUSERCLICK:
  1744. KillTimer(FTrayIcon->hWnd, 1);
  1745. // if icon was shown just to display balloon, hide it with the balloon
  1746. if (!Visible)
  1747. {
  1748. Notify(NIM_DELETE);
  1749. }
  1750. BalloonCancelled();
  1751. break;
  1752. }
  1753. }
  1754. else if (Message.Msg == WM_TIMER)
  1755. {
  1756. // sanity check
  1757. Notify(NIM_DELETE);
  1758. BalloonCancelled();
  1759. }
  1760. else if (Message.Msg == FTaskbarCreatedMsg)
  1761. {
  1762. if (Visible)
  1763. {
  1764. // force recreation
  1765. Visible = false;
  1766. Visible = true;
  1767. }
  1768. }
  1769. else
  1770. {
  1771. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1772. }
  1773. }
  1774. catch(Exception & E)
  1775. {
  1776. Application->HandleException(&E);
  1777. }
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1781. {
  1782. return FTrayIcon->szTip;
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1786. {
  1787. if (Hint != value)
  1788. {
  1789. unsigned int Max = LENOF(FTrayIcon->szTip);
  1790. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1791. Update();
  1792. }
  1793. }
  1794. //---------------------------------------------------------------------------