WinInterface.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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. //---------------------------------------------------------------------------
  745. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  746. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  747. int Options, int CopyParamAttrs, bool SaveSettings)
  748. {
  749. Menu->Items->Clear();
  750. TMenuItem * CustomizeItem = NULL;
  751. TMenuItem * Item;
  752. if (FLAGSET(Options, cplCustomize))
  753. {
  754. Item = new TMenuItem(Menu);
  755. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  756. Item->Tag = cpiCustom;
  757. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  758. Item->OnClick = OnClick;
  759. Menu->Items->Add(Item);
  760. CustomizeItem = Item;
  761. }
  762. if (FLAGSET(Options, cplSaveSettings))
  763. {
  764. Item = new TMenuItem(Menu);
  765. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  766. Item->Tag = cpiSaveSettings;
  767. Item->Checked = SaveSettings;
  768. Item->OnClick = OnClick;
  769. Menu->Items->Add(Item);
  770. }
  771. Item = new TMenuItem(Menu);
  772. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  773. Item->Visible = false;
  774. Item->Enabled = false;
  775. Menu->Items->Add(Item);
  776. bool AnyChecked = false;
  777. Item = new TMenuItem(Menu);
  778. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  779. Item->Tag = cpiDefault;
  780. Item->Checked =
  781. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  782. AnyChecked = AnyChecked || Item->Checked;
  783. Item->OnClick = OnClick;
  784. Menu->Items->Add(Item);
  785. TCopyParamType DefaultParam;
  786. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  787. for (int i = 0; i < CopyParamList->Count; i++)
  788. {
  789. UnicodeString Name = CopyParamList->Names[i];
  790. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  791. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  792. // This makes "Binary" preset visible,
  793. // as long as we care about transfer mode
  794. ((AParam == DefaultParam) &&
  795. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  796. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  797. {
  798. Item = new TMenuItem(Menu);
  799. Item->Caption = Name;
  800. Item->Tag = i;
  801. Item->Checked =
  802. (Preset == Name) && (AParam == Param);
  803. AnyChecked = AnyChecked || Item->Checked;
  804. Item->OnClick = OnClick;
  805. Menu->Items->Add(Item);
  806. }
  807. }
  808. if (CustomizeItem != NULL)
  809. {
  810. CustomizeItem->Checked = !AnyChecked;
  811. }
  812. Item = new TMenuItem(Menu);
  813. Item->Caption = L"-";
  814. Menu->Items->Add(Item);
  815. Item = new TMenuItem(Menu);
  816. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  817. Item->Tag = cpiConfigure;
  818. Item->OnClick = OnClick;
  819. Menu->Items->Add(Item);
  820. if (FLAGSET(Options, cplGenerateCode))
  821. {
  822. Item = new TMenuItem(Menu);
  823. Item->Caption = L"-";
  824. Menu->Items->Add(Item);
  825. Item = new TMenuItem(Menu);
  826. Item->Caption = LoadStr(COPY_PARAM_GENERATE_CODE);
  827. Item->Tag = cpiGenerateCode;
  828. Item->OnClick = OnClick;
  829. Menu->Items->Add(Item);
  830. }
  831. MenuPopup(Menu, Rect, NULL);
  832. }
  833. //---------------------------------------------------------------------------
  834. int __fastcall CopyParamListPopupClick(TObject * Sender,
  835. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  836. bool * SaveSettings)
  837. {
  838. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  839. DebugAssert(Item != NULL);
  840. DebugAssert((Item->Tag >= cpiGenerateCode) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  841. int Result;
  842. if (Item->Tag == cpiConfigure)
  843. {
  844. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  845. DoPreferencesDialog(pmPresets);
  846. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]) ? 1 : 0;
  847. if (Result > 0)
  848. {
  849. // For cast, see a comment below
  850. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  851. }
  852. }
  853. else if (Item->Tag == cpiCustom)
  854. {
  855. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs) ? 1 : 0;
  856. }
  857. else if (Item->Tag == cpiSaveSettings)
  858. {
  859. if (DebugAlwaysTrue(SaveSettings != NULL))
  860. {
  861. *SaveSettings = !*SaveSettings;
  862. }
  863. Result = 0;
  864. }
  865. else if (Item->Tag == cpiGenerateCode)
  866. {
  867. Result = -cplGenerateCode;
  868. }
  869. else
  870. {
  871. Preset = (Item->Tag >= 0) ?
  872. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  873. // The cast strips away the "queue" properties of the TGUICopyParamType
  874. // that are not configurable in presets
  875. Param = TCopyParamType(GUIConfiguration->CopyParamPreset[Preset]);
  876. Result = 1;
  877. }
  878. return Result;
  879. }
  880. //---------------------------------------------------------------------------
  881. //---------------------------------------------------------------------------
  882. class TCustomCommandPromptsDialog : public TCustomDialog
  883. {
  884. public:
  885. __fastcall TCustomCommandPromptsDialog(
  886. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  887. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults);
  888. bool __fastcall Execute(TUnicodeStringVector & Values);
  889. private:
  890. UnicodeString __fastcall HistoryKey(int Index);
  891. std::vector<THistoryComboBox *> FEdits;
  892. TUnicodeStringVector FPrompts;
  893. UnicodeString FCustomCommandName;
  894. };
  895. //---------------------------------------------------------------------------
  896. __fastcall TCustomCommandPromptsDialog::TCustomCommandPromptsDialog(
  897. const UnicodeString & CustomCommandName, const UnicodeString & HelpKeyword,
  898. const TUnicodeStringVector & Prompts, const TUnicodeStringVector & Defaults) :
  899. TCustomDialog(HelpKeyword)
  900. {
  901. FCustomCommandName = CustomCommandName;
  902. Caption = FMTLOAD(CUSTOM_COMMANDS_PARAMS_TITLE, (FCustomCommandName));
  903. FPrompts = Prompts;
  904. DebugAssert(FPrompts.size() == Defaults.size());
  905. for (size_t Index = 0; Index < FPrompts.size(); Index++)
  906. {
  907. UnicodeString Prompt = FPrompts[Index];
  908. if (Prompt.IsEmpty())
  909. {
  910. Prompt = LoadStr(CUSTOM_COMMANDS_PARAM_PROMPT2);
  911. }
  912. THistoryComboBox * ComboBox = new THistoryComboBox(this);
  913. ComboBox->AutoComplete = false;
  914. AddComboBox(ComboBox, CreateLabel(Prompt));
  915. ComboBox->Items = CustomWinConfiguration->History[HistoryKey(Index)];
  916. ComboBox->Text = Defaults[Index];
  917. FEdits.push_back(ComboBox);
  918. }
  919. }
  920. //---------------------------------------------------------------------------
  921. UnicodeString __fastcall TCustomCommandPromptsDialog::HistoryKey(int Index)
  922. {
  923. UnicodeString Result = FPrompts[Index];
  924. if (Result.IsEmpty())
  925. {
  926. Result = IntToStr(Index);
  927. }
  928. Result = FORMAT(L"%s_%s", (FCustomCommandName, Result));
  929. Result = CustomWinConfiguration->GetValidHistoryKey(Result);
  930. return L"CustomCommandParam_" + Result;
  931. }
  932. //---------------------------------------------------------------------------
  933. bool __fastcall TCustomCommandPromptsDialog::Execute(TUnicodeStringVector & Values)
  934. {
  935. bool Result = TCustomDialog::Execute();
  936. if (Result)
  937. {
  938. for (size_t Index = 0; Index < FEdits.size(); Index++)
  939. {
  940. Values.push_back(FEdits[Index]->Text);
  941. FEdits[Index]->SaveToHistory();
  942. CustomWinConfiguration->History[HistoryKey(Index)] = FEdits[Index]->Items;
  943. }
  944. }
  945. return Result;
  946. }
  947. //---------------------------------------------------------------------------
  948. //---------------------------------------------------------------------------
  949. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  950. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName, const UnicodeString HelpKeyword) :
  951. TInteractiveCustomCommand(ChildCustomCommand)
  952. {
  953. FCustomCommandName = StripEllipsis(StripHotkey(CustomCommandName));
  954. FHelpKeyword = HelpKeyword;
  955. }
  956. //---------------------------------------------------------------------------
  957. void __fastcall TWinInteractiveCustomCommand::PatternHint(int Index, const UnicodeString & Pattern)
  958. {
  959. if (IsPromptPattern(Pattern))
  960. {
  961. UnicodeString Prompt;
  962. UnicodeString Default;
  963. bool Delimit = false;
  964. ParsePromptPattern(Pattern, Prompt, Default, Delimit);
  965. FIndexes.insert(std::make_pair(Index, FPrompts.size()));
  966. FPrompts.push_back(Prompt);
  967. FDefaults.push_back(Default);
  968. }
  969. }
  970. //---------------------------------------------------------------------------
  971. void __fastcall TWinInteractiveCustomCommand::Prompt(
  972. int Index, const UnicodeString & /*Prompt*/, UnicodeString & Value)
  973. {
  974. if (DebugAlwaysTrue(FIndexes.find(Index) != FIndexes.end()))
  975. {
  976. size_t PromptIndex = FIndexes[Index];
  977. if (FValues.empty())
  978. {
  979. UnicodeString HelpKeyword = FHelpKeyword;
  980. if (HelpKeyword.IsEmpty())
  981. {
  982. HelpKeyword = HELP_CUSTOM_COMMAND_PARAM;
  983. }
  984. std::unique_ptr<TCustomCommandPromptsDialog> Dialog(
  985. new TCustomCommandPromptsDialog(FCustomCommandName, HelpKeyword, FPrompts, FDefaults));
  986. if (!Dialog->Execute(FValues))
  987. {
  988. Abort();
  989. }
  990. }
  991. if (DebugAlwaysTrue(FValues.size() == FPrompts.size()) &&
  992. DebugAlwaysTrue(PromptIndex < FValues.size()))
  993. {
  994. Value = FValues[PromptIndex];
  995. }
  996. }
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall TWinInteractiveCustomCommand::Execute(
  1000. const UnicodeString & Command, UnicodeString & Value)
  1001. {
  1002. // inspired by
  1003. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  1004. HANDLE StdOutOutput;
  1005. HANDLE StdOutInput;
  1006. HANDLE StdInOutput;
  1007. HANDLE StdInInput;
  1008. SECURITY_ATTRIBUTES SecurityAttributes;
  1009. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  1010. SecurityAttributes.lpSecurityDescriptor = NULL;
  1011. SecurityAttributes.bInheritHandle = TRUE;
  1012. try
  1013. {
  1014. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  1015. {
  1016. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  1017. }
  1018. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  1019. {
  1020. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  1021. }
  1022. else
  1023. {
  1024. STARTUPINFO StartupInfo;
  1025. PROCESS_INFORMATION ProcessInformation;
  1026. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  1027. StartupInfo.cb = sizeof(StartupInfo);
  1028. StartupInfo.wShowWindow = SW_HIDE;
  1029. StartupInfo.hStdInput = StdInOutput;
  1030. StartupInfo.hStdOutput = StdOutInput;
  1031. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1032. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  1033. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  1034. {
  1035. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  1036. }
  1037. else
  1038. {
  1039. try
  1040. {
  1041. // wait until the console program terminated
  1042. bool Running = true;
  1043. while (Running)
  1044. {
  1045. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  1046. {
  1047. case WAIT_TIMEOUT:
  1048. Application->ProcessMessages();
  1049. break;
  1050. case WAIT_OBJECT_0:
  1051. Running = false;
  1052. break;
  1053. default:
  1054. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  1055. }
  1056. }
  1057. char Buffer[1024];
  1058. unsigned long Read;
  1059. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  1060. (Read > 0))
  1061. {
  1062. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  1063. {
  1064. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  1065. }
  1066. else if (Read > 0)
  1067. {
  1068. Value += AnsiToString(Buffer, Read);
  1069. }
  1070. }
  1071. // trim trailing cr/lf
  1072. Value = TrimRight(Value);
  1073. }
  1074. __finally
  1075. {
  1076. CloseHandle(ProcessInformation.hProcess);
  1077. CloseHandle(ProcessInformation.hThread);
  1078. }
  1079. }
  1080. }
  1081. }
  1082. __finally
  1083. {
  1084. if (StdOutOutput != INVALID_HANDLE_VALUE)
  1085. {
  1086. CloseHandle(StdOutOutput);
  1087. }
  1088. if (StdOutInput != INVALID_HANDLE_VALUE)
  1089. {
  1090. CloseHandle(StdOutInput);
  1091. }
  1092. if (StdInOutput != INVALID_HANDLE_VALUE)
  1093. {
  1094. CloseHandle(StdInOutput);
  1095. }
  1096. if (StdInInput != INVALID_HANDLE_VALUE)
  1097. {
  1098. CloseHandle(StdInInput);
  1099. }
  1100. }
  1101. }
  1102. //---------------------------------------------------------------------------
  1103. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  1104. {
  1105. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  1109. {
  1110. TControl * Control = dynamic_cast<TControl *>(Sender);
  1111. DebugAssert(Control != NULL);
  1112. TPoint Point;
  1113. if ((MousePos.x == -1) && (MousePos.y == -1))
  1114. {
  1115. Point = Control->ClientToScreen(TPoint(0, 0));
  1116. }
  1117. else
  1118. {
  1119. Point = Control->ClientToScreen(MousePos);
  1120. }
  1121. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  1122. DebugAssert(PopupMenu != NULL);
  1123. TRect Rect(Point, Point);
  1124. MenuPopup(PopupMenu, Rect, Control);
  1125. Handled = true;
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. TComponent * __fastcall GetPopupComponent(TObject * Sender)
  1129. {
  1130. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  1131. DebugAssert(Item != NULL);
  1132. TPopupMenu * PopupMenu = dynamic_cast<TPopupMenu *>(Item->Owner);
  1133. DebugAssert(PopupMenu != NULL);
  1134. DebugAssert(PopupMenu->PopupComponent != NULL);
  1135. return PopupMenu->PopupComponent;
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. static void __fastcall SetMenuButtonImages(TButton * Button)
  1139. {
  1140. Button->Images = GetButtonImages(Button);
  1141. }
  1142. //---------------------------------------------------------------------------
  1143. static void __fastcall MenuButtonRescale(TComponent * Sender, TObject * /*Token*/)
  1144. {
  1145. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1146. SetMenuButtonImages(Button);
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. void __fastcall MenuButton(TButton * Button)
  1150. {
  1151. SetMenuButtonImages(Button);
  1152. Button->ImageIndex = 0;
  1153. Button->DisabledImageIndex = 1;
  1154. Button->ImageAlignment = iaRight;
  1155. SetRescaleFunction(Button, MenuButtonRescale);
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. TRect __fastcall CalculatePopupRect(TButton * Button)
  1159. {
  1160. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  1161. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  1162. TRect Rect(UpPoint, DownPoint);
  1163. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  1164. int Offset = UseThemes() ? -1 : 0;
  1165. Rect.Inflate(Offset, Offset);
  1166. return Rect;
  1167. }
  1168. //---------------------------------------------------------------------------
  1169. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  1170. {
  1171. MousePos = Control->ClientToScreen(MousePos);
  1172. TRect Rect(MousePos, MousePos);
  1173. return Rect;
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. void __fastcall FixButtonImage(TButton * Button)
  1177. {
  1178. // with themes enabled, button image is by default drawn too high
  1179. if (UseThemes())
  1180. {
  1181. Button->ImageMargins->Top = 1;
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall CenterButtonImage(TButton * Button)
  1186. {
  1187. // with themes disabled, the text seems to be drawn over the icon,
  1188. // so that the padding spaces hide away most of the icon
  1189. if (UseThemes())
  1190. {
  1191. Button->ImageAlignment = iaCenter;
  1192. int ImageWidth = Button->Images->Width;
  1193. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  1194. Canvas->Control = Button;
  1195. Canvas->Font = Button->Font;
  1196. UnicodeString Caption = Button->Caption.Trim();
  1197. UnicodeString Padding;
  1198. while (Canvas->TextWidth(Padding) < ImageWidth)
  1199. {
  1200. Padding += L" ";
  1201. }
  1202. if (Button->IsRightToLeft())
  1203. {
  1204. Caption = Caption + Padding;
  1205. }
  1206. else
  1207. {
  1208. Caption = Padding + Caption;
  1209. }
  1210. Button->Caption = Caption;
  1211. int CaptionWidth = Canvas->TextWidth(Caption);
  1212. // The margins seem to extend the area over which the image is centered,
  1213. // so we have to set it to a double of desired padding.
  1214. // The original formula is - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2))
  1215. // the one below is equivalent, but with reduced rouding.
  1216. // Without the change, the rouding caused the space between icon and caption too
  1217. // small on 200% zoom.
  1218. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  1219. // is approximatelly same as half of caption width before padding.
  1220. Button->ImageMargins->Left = -(CaptionWidth - ImageWidth + ScaleByTextHeight(Button, 4));
  1221. }
  1222. else
  1223. {
  1224. // at least do not draw it so near to the edge
  1225. Button->ImageMargins->Left = 1;
  1226. }
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. int __fastcall AdjustLocaleFlag(const UnicodeString & S, TLocaleFlagOverride LocaleFlagOverride, bool Recommended, int On, int Off)
  1230. {
  1231. int Result = !S.IsEmpty() && StrToInt(S);
  1232. switch (LocaleFlagOverride)
  1233. {
  1234. default:
  1235. case lfoLanguageIfRecommended:
  1236. if (!Recommended)
  1237. {
  1238. Result = Off;
  1239. }
  1240. break;
  1241. case lfoLanguage:
  1242. // noop = as configured in locale
  1243. break;
  1244. case lfoAlways:
  1245. Result = On;
  1246. break;
  1247. case lfoNever:
  1248. Result = Off;
  1249. break;
  1250. }
  1251. return Result;
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  1255. {
  1256. if (GlobalOnMinimize == NULL)
  1257. {
  1258. GlobalOnMinimize = OnMinimize;
  1259. }
  1260. }
  1261. //---------------------------------------------------------------------------
  1262. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  1263. {
  1264. if (GlobalOnMinimize == OnMinimize)
  1265. {
  1266. GlobalOnMinimize = NULL;
  1267. }
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  1271. {
  1272. Configuration->Usage->Inc(L"OperationMinimizations");
  1273. if (DebugAlwaysTrue(GlobalOnMinimize != NULL))
  1274. {
  1275. GlobalOnMinimize(Sender);
  1276. }
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  1280. {
  1281. TForm * MainForm = Application->MainForm;
  1282. TForm * MainLikeForm = GetMainForm();
  1283. if ((MainLikeForm != MainForm) && !WinConfiguration->MinimizeToTray)
  1284. {
  1285. TWindowState PreviousWindowState;
  1286. if (Minimize)
  1287. {
  1288. PreviousWindowState = MainLikeForm->WindowState;
  1289. MainLikeForm->WindowState = wsMinimized;
  1290. }
  1291. else
  1292. {
  1293. MainLikeForm->WindowState = PreviousWindowState;
  1294. }
  1295. }
  1296. else
  1297. {
  1298. // What is described below should not ever happen, except when minimizing to tray,
  1299. // as we capture command-line operation above.
  1300. // Had we called TApplication::Minimize, it would hide all non-MainForm windows, including MainLineForm,
  1301. // so it actually also hides taskbar button, what we do not want.
  1302. // WORKAROUND
  1303. // When main window is hidden (command-line operation),
  1304. // we do not want it to be shown by TApplication.Restore,
  1305. // so we temporarily detach it from an application.
  1306. // Probably not really necessary for minimizing phase,
  1307. // but we do it for consistency anyway.
  1308. bool RestoreMainForm = false;
  1309. if (DebugAlwaysTrue(MainForm != NULL) &&
  1310. !MainForm->Visible)
  1311. {
  1312. SetAppMainForm(NULL);
  1313. RestoreMainForm = true;
  1314. }
  1315. try
  1316. {
  1317. if (Minimize)
  1318. {
  1319. Application->Minimize();
  1320. }
  1321. else
  1322. {
  1323. Application->Restore();
  1324. }
  1325. }
  1326. __finally
  1327. {
  1328. if (RestoreMainForm)
  1329. {
  1330. SetAppMainForm(MainForm);
  1331. }
  1332. }
  1333. }
  1334. }
  1335. //---------------------------------------------------------------------------
  1336. void __fastcall ApplicationMinimize()
  1337. {
  1338. DoApplicationMinimizeRestore(true);
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. void __fastcall ApplicationRestore()
  1342. {
  1343. DoApplicationMinimizeRestore(false);
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. bool __fastcall IsApplicationMinimized()
  1347. {
  1348. // VCL help recommends handling Application->OnMinimize/OnRestore
  1349. // for tracking state, but OnRestore is actually not called
  1350. // (OnMinimize is), when app is minimized from e.g. Progress window
  1351. bool AppMinimized = IsIconic(Application->Handle);
  1352. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  1353. return AppMinimized || MainFormMinimized;
  1354. }
  1355. //---------------------------------------------------------------------------
  1356. bool __fastcall HandleMinimizeSysCommand(TMessage & Message)
  1357. {
  1358. TWMSysCommand & SysCommand = reinterpret_cast<TWMSysCommand &>(Message);
  1359. unsigned int Cmd = (SysCommand.CmdType & 0xFFF0);
  1360. bool Result = (Cmd == SC_MINIMIZE);
  1361. if (Result)
  1362. {
  1363. ApplicationMinimize();
  1364. SysCommand.Result = 1;
  1365. }
  1366. return Result;
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. void __fastcall ClickToolbarItem(TTBCustomItem * Item, bool PositionCursor)
  1370. {
  1371. TTBCustomItem * TopItem = Item;
  1372. while (TopItem->Parent != NULL)
  1373. {
  1374. TopItem = TopItem->Parent;
  1375. }
  1376. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(TopItem->ParentComponent);
  1377. DebugAssert(Toolbar != NULL);
  1378. TTBItemViewer * Viewer = Toolbar->View->Find(Item);
  1379. DebugAssert(Viewer != NULL);
  1380. int X = Viewer->BoundsRect.Left + (Viewer->BoundsRect.Width() / 2);
  1381. int Y = Viewer->BoundsRect.Top + (Viewer->BoundsRect.Height() / 2);
  1382. if (PositionCursor)
  1383. {
  1384. Mouse->CursorPos = Toolbar->ClientToScreen(TPoint(X, Y));
  1385. }
  1386. PostMessage(Toolbar->Handle, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(X, Y));
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. //---------------------------------------------------------------------------
  1390. UnicodeString DumpCallstackEventName(int ProcessId)
  1391. {
  1392. return FORMAT(DUMPCALLSTACK_EVENT, (ProcessId));
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. UnicodeString DumpCallstackFileName(int ProcessId)
  1396. {
  1397. UnicodeString FileName = FORMAT(L"%s.txt", (DumpCallstackEventName(ProcessId)));
  1398. UnicodeString Result = TPath::Combine(SystemTemporaryDirectory(), FileName);
  1399. return Result;
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. class TCallstackThread : public TSignalThread
  1403. {
  1404. public:
  1405. __fastcall TCallstackThread();
  1406. protected:
  1407. virtual void __fastcall ProcessEvent();
  1408. private:
  1409. static HANDLE DoCreateEvent();
  1410. };
  1411. //---------------------------------------------------------------------------
  1412. __fastcall TCallstackThread::TCallstackThread() :
  1413. TSignalThread(true, DoCreateEvent())
  1414. {
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. void __fastcall TCallstackThread::ProcessEvent()
  1418. {
  1419. try
  1420. {
  1421. UnicodeString Path = DumpCallstackFileName(GetCurrentProcessId());
  1422. std::unique_ptr<TStrings> StackStrings;
  1423. HANDLE MainThreadHandle = reinterpret_cast<HANDLE>(MainThreadID);
  1424. if (SuspendThread(MainThreadHandle) < 0)
  1425. {
  1426. RaiseLastOSError();
  1427. }
  1428. try
  1429. {
  1430. TJclStackInfoList * StackInfoList = JclCreateThreadStackTraceFromID(true, MainThreadID);
  1431. if (StackInfoList == NULL)
  1432. {
  1433. RaiseLastOSError();
  1434. }
  1435. StackStrings.reset(StackInfoListToStrings(StackInfoList));
  1436. }
  1437. __finally
  1438. {
  1439. if (ResumeThread(MainThreadHandle) < 0)
  1440. {
  1441. RaiseLastOSError();
  1442. }
  1443. }
  1444. TFile::WriteAllText(Path, StackStrings->Text);
  1445. }
  1446. catch (...)
  1447. {
  1448. }
  1449. }
  1450. //---------------------------------------------------------------------------
  1451. HANDLE TCallstackThread::DoCreateEvent()
  1452. {
  1453. UnicodeString Name = DumpCallstackEventName(GetCurrentProcessId());
  1454. return CreateEvent(NULL, false, false, Name.c_str());
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. //---------------------------------------------------------------------------
  1458. std::unique_ptr<TCallstackThread> CallstackThread;
  1459. //---------------------------------------------------------------------------
  1460. void __fastcall WinInitialize()
  1461. {
  1462. if (JclHookExceptions())
  1463. {
  1464. JclStackTrackingOptions << stAllModules;
  1465. JclAddExceptNotifier(DoExceptNotify, npFirstChain);
  1466. CallstackThread.reset(new TCallstackThread());
  1467. CallstackThread->Start();
  1468. }
  1469. SetErrorMode(SEM_FAILCRITICALERRORS);
  1470. OnApiPath = ApiPath;
  1471. MainThread = GetCurrentThreadId();
  1472. #pragma warn -8111
  1473. #pragma warn .8111
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. void __fastcall WinFinalize()
  1477. {
  1478. CallstackThread.reset(NULL);
  1479. JclRemoveExceptNotifier(DoExceptNotify);
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1483. {
  1484. FVisible = false;
  1485. FOnClick = NULL;
  1486. FOnBalloonClick = NULL;
  1487. FBalloonUserData = NULL;
  1488. FTrayIcon = new NOTIFYICONDATA;
  1489. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1490. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1491. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1492. // LoadIconMetric is available from Windows Vista only
  1493. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1494. if (DebugAlwaysTrue(ComCtl32Dll))
  1495. {
  1496. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1497. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1498. if (LoadIconMetric != NULL)
  1499. {
  1500. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1501. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1502. }
  1503. }
  1504. if (FTrayIcon->hIcon == 0)
  1505. {
  1506. FTrayIcon->hIcon = Application->Icon->Handle;
  1507. }
  1508. FTrayIcon->uID = Id;
  1509. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1510. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1511. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1512. }
  1513. //---------------------------------------------------------------------------
  1514. __fastcall ::TTrayIcon::~TTrayIcon()
  1515. {
  1516. // make sure we hide icon even in case it was shown just to pop up the balloon
  1517. // (in which case Visible == false)
  1518. CancelBalloon();
  1519. Visible = false;
  1520. DeallocateHWnd(FTrayIcon->hWnd);
  1521. delete FTrayIcon;
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1525. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1526. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1527. {
  1528. if (Timeout > 30000)
  1529. {
  1530. // this is probably system limit, do not try more, especially for
  1531. // the timeout-driven hiding of the tray icon (for Win2k)
  1532. Timeout = 30000;
  1533. }
  1534. FTrayIcon->uFlags |= NIF_INFO;
  1535. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1536. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1537. UnicodeString Info = Str;
  1538. // When szInfo is empty, balloon is not shown
  1539. // (or actually it means the balloon should be deleted, if any)
  1540. if (Info.IsEmpty())
  1541. {
  1542. Info = L" ";
  1543. }
  1544. StrPLCopy(FTrayIcon->szInfo, Info, LENOF(FTrayIcon->szInfo) - 1);
  1545. FTrayIcon->uTimeout = Timeout;
  1546. switch (QueryType)
  1547. {
  1548. case qtError:
  1549. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1550. break;
  1551. case qtInformation:
  1552. case qtConfirmation:
  1553. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1554. break;
  1555. case qtWarning:
  1556. default:
  1557. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1558. break;
  1559. }
  1560. KillTimer(FTrayIcon->hWnd, 1);
  1561. if (Visible)
  1562. {
  1563. Update();
  1564. }
  1565. else
  1566. {
  1567. Notify(NIM_ADD);
  1568. }
  1569. FOnBalloonClick = OnBalloonClick;
  1570. delete FBalloonUserData;
  1571. FBalloonUserData = BalloonUserData;
  1572. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1573. // unless CancelBalloon is called explicitly
  1574. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1575. }
  1576. //---------------------------------------------------------------------------
  1577. void __fastcall ::TTrayIcon::BalloonCancelled()
  1578. {
  1579. FOnBalloonClick = NULL;
  1580. delete FBalloonUserData;
  1581. FBalloonUserData = NULL;
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. void __fastcall ::TTrayIcon::CancelBalloon()
  1585. {
  1586. KillTimer(FTrayIcon->hWnd, 1);
  1587. if (Visible)
  1588. {
  1589. FTrayIcon->uFlags |= NIF_INFO;
  1590. FTrayIcon->szInfo[0] = L'\0';
  1591. Update();
  1592. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1593. }
  1594. else
  1595. {
  1596. Notify(NIM_DELETE);
  1597. }
  1598. BalloonCancelled();
  1599. }
  1600. //---------------------------------------------------------------------------
  1601. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1602. {
  1603. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1604. if (Result && (Message == NIM_ADD))
  1605. {
  1606. UINT Timeout = FTrayIcon->uTimeout;
  1607. try
  1608. {
  1609. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1610. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1611. }
  1612. __finally
  1613. {
  1614. FTrayIcon->uTimeout = Timeout;
  1615. }
  1616. }
  1617. return Result;
  1618. }
  1619. //---------------------------------------------------------------------------
  1620. void __fastcall ::TTrayIcon::Update()
  1621. {
  1622. if (Visible)
  1623. {
  1624. Notify(NIM_MODIFY);
  1625. }
  1626. }
  1627. //---------------------------------------------------------------------------
  1628. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1629. {
  1630. if (Visible != value)
  1631. {
  1632. if (value)
  1633. {
  1634. FVisible = Notify(NIM_ADD);
  1635. }
  1636. else
  1637. {
  1638. FVisible = false;
  1639. KillTimer(FTrayIcon->hWnd, 1);
  1640. Notify(NIM_DELETE);
  1641. BalloonCancelled();
  1642. }
  1643. }
  1644. }
  1645. //---------------------------------------------------------------------------
  1646. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1647. {
  1648. try
  1649. {
  1650. if (Message.Msg == WM_TRAY_ICON)
  1651. {
  1652. DebugAssert(Message.WParam == 0);
  1653. switch (Message.LParam)
  1654. {
  1655. // old shell32
  1656. case WM_LBUTTONUP:
  1657. case WM_RBUTTONUP:
  1658. // new shell32:
  1659. case WM_CONTEXTMENU:
  1660. if (OnClick != NULL)
  1661. {
  1662. OnClick(NULL);
  1663. }
  1664. Message.Result = true;
  1665. break;
  1666. }
  1667. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1668. {
  1669. if (FOnBalloonClick != NULL)
  1670. {
  1671. // prevent the user data from being freed by possible call
  1672. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1673. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1674. FBalloonUserData = NULL;
  1675. FOnBalloonClick(UserData.get());
  1676. }
  1677. else if (OnClick != NULL)
  1678. {
  1679. OnClick(NULL);
  1680. }
  1681. }
  1682. switch (Message.LParam)
  1683. {
  1684. case NIN_BALLOONHIDE:
  1685. case NIN_BALLOONTIMEOUT:
  1686. case NIN_BALLOONUSERCLICK:
  1687. KillTimer(FTrayIcon->hWnd, 1);
  1688. // if icon was shown just to display balloon, hide it with the balloon
  1689. if (!Visible)
  1690. {
  1691. Notify(NIM_DELETE);
  1692. }
  1693. BalloonCancelled();
  1694. break;
  1695. }
  1696. }
  1697. else if (Message.Msg == WM_TIMER)
  1698. {
  1699. // sanity check
  1700. Notify(NIM_DELETE);
  1701. BalloonCancelled();
  1702. }
  1703. else if (Message.Msg == FTaskbarCreatedMsg)
  1704. {
  1705. if (Visible)
  1706. {
  1707. // force recreation
  1708. Visible = false;
  1709. Visible = true;
  1710. }
  1711. }
  1712. else
  1713. {
  1714. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1715. }
  1716. }
  1717. catch(Exception & E)
  1718. {
  1719. Application->HandleException(&E);
  1720. }
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1724. {
  1725. return FTrayIcon->szTip;
  1726. }
  1727. //---------------------------------------------------------------------------
  1728. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1729. {
  1730. if (Hint != value)
  1731. {
  1732. unsigned int Max = LENOF(FTrayIcon->szTip);
  1733. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1734. Update();
  1735. }
  1736. }
  1737. //---------------------------------------------------------------------------