1
0

WinInterface.cpp 61 KB

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