1
0

WinInterface.cpp 61 KB

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