WinInterface.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlwapi.h>
  5. #include <Common.h>
  6. #include <Exceptions.h>
  7. #include <CoreMain.h>
  8. #include <TextsCore.h>
  9. #include <TextsWin.h>
  10. #include <HelpWin.h>
  11. #include <HelpCore.h>
  12. #include <Interface.h>
  13. #include <VCLCommon.h>
  14. #include <Glyphs.h>
  15. #include <PasTools.hpp>
  16. #include "WinInterface.h"
  17. #include "CustomWinConfiguration.h"
  18. #include "GUITools.h"
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. #define WM_TRAY_ICON (WM_WINSCP_USER + 5)
  23. //---------------------------------------------------------------------
  24. TNotifyEvent GlobalOnMinimize = NULL;
  25. //---------------------------------------------------------------------
  26. void __fastcall FormHelp(TForm * Form)
  27. {
  28. InvokeHelp(Form->ActiveControl != NULL ? Form->ActiveControl : Form);
  29. }
  30. //---------------------------------------------------------------------------
  31. TMessageParams::TMessageParams(unsigned int AParams)
  32. {
  33. Reset();
  34. Params = AParams;
  35. }
  36. //---------------------------------------------------------------------------
  37. TMessageParams::TMessageParams(const TQueryParams * AParams)
  38. {
  39. Reset();
  40. if (AParams != NULL)
  41. {
  42. Aliases = AParams->Aliases;
  43. AliasesCount = AParams->AliasesCount;
  44. Timer = AParams->Timer;
  45. TimerEvent = AParams->TimerEvent;
  46. TimerMessage = AParams->TimerMessage;
  47. TimerAnswers = AParams->TimerAnswers;
  48. TimerQueryType = AParams->TimerQueryType;
  49. Timeout = AParams->Timeout;
  50. TimeoutAnswer = AParams->TimeoutAnswer;
  51. if (FLAGSET(AParams->Params, qpNeverAskAgainCheck))
  52. {
  53. Params |= mpNeverAskAgainCheck;
  54. }
  55. if (FLAGSET(AParams->Params, qpAllowContinueOnError))
  56. {
  57. Params |= mpAllowContinueOnError;
  58. }
  59. }
  60. }
  61. //---------------------------------------------------------------------------
  62. inline void TMessageParams::Reset()
  63. {
  64. Params = 0;
  65. Aliases = NULL;
  66. AliasesCount = 0;
  67. Timer = 0;
  68. TimerEvent = NULL;
  69. TimerMessage = L"";
  70. TimerAnswers = 0;
  71. TimerQueryType = static_cast<TQueryType>(-1);
  72. Timeout = 0;
  73. TimeoutAnswer = 0;
  74. NeverAskAgainTitle = L"";
  75. NeverAskAgainAnswer = 0;
  76. NeverAskAgainCheckedInitially = false;
  77. AllowHelp = true;
  78. ImageName = L"";
  79. }
  80. //---------------------------------------------------------------------------
  81. static bool __fastcall IsPositiveAnswer(unsigned int Answer)
  82. {
  83. return (Answer == qaYes) || (Answer == qaOK) || (Answer == qaYesToAll);
  84. }
  85. //---------------------------------------------------------------------------
  86. static void __fastcall NeverAskAgainCheckClick(void * /*Data*/, TObject * Sender)
  87. {
  88. TCheckBox * CheckBox = dynamic_cast<TCheckBox *>(Sender);
  89. assert(CheckBox != NULL);
  90. TForm * Dialog = dynamic_cast<TForm *>(CheckBox->Owner);
  91. assert(Dialog != NULL);
  92. unsigned int PositiveAnswer = 0;
  93. if (CheckBox->Checked)
  94. {
  95. if (CheckBox->Tag > 0)
  96. {
  97. PositiveAnswer = CheckBox->Tag;
  98. }
  99. else
  100. {
  101. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  102. {
  103. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  104. if (Button != NULL)
  105. {
  106. if (IsPositiveAnswer(Button->ModalResult))
  107. {
  108. PositiveAnswer = Button->ModalResult;
  109. break;
  110. }
  111. }
  112. }
  113. }
  114. assert(PositiveAnswer != 0);
  115. }
  116. for (int ii = 0; ii < Dialog->ControlCount; ii++)
  117. {
  118. TButton * Button = dynamic_cast<TButton *>(Dialog->Controls[ii]);
  119. if (Button != NULL)
  120. {
  121. if ((Button->ModalResult != 0) && (Button->ModalResult != static_cast<int>(qaCancel)))
  122. {
  123. Button->Enabled = !CheckBox->Checked || (Button->ModalResult == static_cast<int>(PositiveAnswer));
  124. }
  125. if (Button->DropDownMenu != NULL)
  126. {
  127. for (int iii = 0; iii < Button->DropDownMenu->Items->Count; iii++)
  128. {
  129. TMenuItem * Item = Button->DropDownMenu->Items->Items[iii];
  130. Item->Enabled = Item->Default || !CheckBox->Checked;
  131. }
  132. }
  133. }
  134. }
  135. }
  136. //---------------------------------------------------------------------------
  137. static TCheckBox * __fastcall FindNeverAskAgainCheck(TForm * Dialog)
  138. {
  139. return NOT_NULL(dynamic_cast<TCheckBox *>(Dialog->FindComponent(L"NeverAskAgainCheck")));
  140. }
  141. //---------------------------------------------------------------------------
  142. TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg,
  143. TStrings * MoreMessages, TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword,
  144. const TMessageParams * Params, TButton *& TimeoutButton)
  145. {
  146. TMsgDlgType DlgType;
  147. switch (Type) {
  148. case qtConfirmation: DlgType = mtConfirmation; break;
  149. case qtInformation: DlgType = mtInformation; break;
  150. case qtError: DlgType = mtError; break;
  151. case qtWarning: DlgType = mtWarning; break;
  152. default: assert(false);
  153. }
  154. unsigned int TimeoutAnswer = (Params != NULL) ? Params->TimeoutAnswer : 0;
  155. unsigned int ActualAnswers = Answers;
  156. if ((Params == NULL) || Params->AllowHelp)
  157. {
  158. Answers = Answers | qaHelp;
  159. }
  160. if (HelpKeyword == HELP_INTERNAL_ERROR)
  161. {
  162. Answers = Answers | qaReport;
  163. }
  164. if ((MoreMessages != NULL) && (MoreMessages->Count == 0))
  165. {
  166. MoreMessages = NULL;
  167. }
  168. UnicodeString ImageName;
  169. if (Params != NULL)
  170. {
  171. ImageName = Params->ImageName;
  172. }
  173. const TQueryButtonAlias * Aliases = (Params != NULL) ? Params->Aliases : NULL;
  174. unsigned int AliasesCount = (Params != NULL) ? Params->AliasesCount : 0;
  175. UnicodeString NeverAskAgainCaption;
  176. bool HasNeverAskAgain = (Params != NULL) && FLAGSET(Params->Params, mpNeverAskAgainCheck);
  177. if (HasNeverAskAgain)
  178. {
  179. NeverAskAgainCaption =
  180. !Params->NeverAskAgainTitle.IsEmpty() ?
  181. (UnicodeString)Params->NeverAskAgainTitle :
  182. // qaOK | qaIgnore is used, when custom "non-answer" button is required
  183. LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ?
  184. NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN);
  185. }
  186. TForm * Dialog = CreateMoreMessageDialog(Msg, MoreMessages, DlgType, Answers,
  187. Aliases, AliasesCount, TimeoutAnswer, &TimeoutButton, ImageName, NeverAskAgainCaption);
  188. try
  189. {
  190. if (HasNeverAskAgain && ALWAYS_TRUE(Params != NULL))
  191. {
  192. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  193. NeverAskAgainCheck->Checked = Params->NeverAskAgainCheckedInitially;
  194. if (Params->NeverAskAgainAnswer > 0)
  195. {
  196. NeverAskAgainCheck->Tag = Params->NeverAskAgainAnswer;
  197. }
  198. TNotifyEvent OnClick;
  199. ((TMethod*)&OnClick)->Code = NeverAskAgainCheckClick;
  200. NeverAskAgainCheck->OnClick = OnClick;
  201. }
  202. Dialog->HelpKeyword = HelpKeyword;
  203. if (FLAGSET(Answers, qaHelp))
  204. {
  205. Dialog->BorderIcons = Dialog->BorderIcons << biHelp;
  206. }
  207. ResetSystemSettings(Dialog);
  208. }
  209. catch(...)
  210. {
  211. delete Dialog;
  212. throw;
  213. }
  214. return Dialog;
  215. }
  216. //---------------------------------------------------------------------------
  217. unsigned int __fastcall ExecuteMessageDialog(TForm * Dialog, unsigned int Answers, const TMessageParams * Params)
  218. {
  219. FlashOnBackground();
  220. unsigned int Answer = Dialog->ShowModal();
  221. // mrCancel is returned always when X button is pressed, despite
  222. // no Cancel button was on the dialog. Find valid "cancel" answer.
  223. // mrNone is retuned when Windows session is closing (log off)
  224. if ((Answer == mrCancel) || (Answer == mrNone))
  225. {
  226. Answer = CancelAnswer(Answers);
  227. }
  228. if ((Params != NULL) && (Params->Params & mpNeverAskAgainCheck))
  229. {
  230. TCheckBox * NeverAskAgainCheck = FindNeverAskAgainCheck(Dialog);
  231. if (NeverAskAgainCheck->Checked)
  232. {
  233. bool PositiveAnswer =
  234. (Params->NeverAskAgainAnswer > 0) ?
  235. (Answer == Params->NeverAskAgainAnswer) :
  236. IsPositiveAnswer(Answer);
  237. if (PositiveAnswer)
  238. {
  239. Answer = qaNeverAskAgain;
  240. }
  241. }
  242. }
  243. return Answer;
  244. }
  245. //---------------------------------------------------------------------------
  246. class TMessageTimer : public TTimer
  247. {
  248. public:
  249. TQueryParamsTimerEvent Event;
  250. TForm * Dialog;
  251. __fastcall TMessageTimer(TComponent * AOwner);
  252. protected:
  253. void __fastcall DoTimer(TObject * Sender);
  254. };
  255. //---------------------------------------------------------------------------
  256. __fastcall TMessageTimer::TMessageTimer(TComponent * AOwner) : TTimer(AOwner)
  257. {
  258. Event = NULL;
  259. OnTimer = DoTimer;
  260. Dialog = NULL;
  261. }
  262. //---------------------------------------------------------------------------
  263. void __fastcall TMessageTimer::DoTimer(TObject * /*Sender*/)
  264. {
  265. if (Event != NULL)
  266. {
  267. unsigned int Result = 0;
  268. Event(Result);
  269. if (Result != 0)
  270. {
  271. Dialog->ModalResult = Result;
  272. }
  273. }
  274. }
  275. //---------------------------------------------------------------------------
  276. class TMessageTimeout : public TTimer
  277. {
  278. public:
  279. __fastcall TMessageTimeout(TComponent * AOwner, unsigned int Timeout,
  280. TButton * Button);
  281. void __fastcall Suspend();
  282. void __fastcall Cancel();
  283. protected:
  284. unsigned int FOrigTimeout;
  285. unsigned int FTimeout;
  286. unsigned int FSuspended;
  287. TButton * FButton;
  288. UnicodeString FOrigCaption;
  289. void __fastcall DoTimer(TObject * Sender);
  290. void __fastcall UpdateButton();
  291. };
  292. //---------------------------------------------------------------------------
  293. __fastcall TMessageTimeout::TMessageTimeout(TComponent * AOwner,
  294. unsigned int Timeout, TButton * Button) :
  295. TTimer(AOwner), FOrigTimeout(Timeout), FTimeout(Timeout), FButton(Button)
  296. {
  297. OnTimer = DoTimer;
  298. Interval = MSecsPerSec;
  299. FOrigCaption = FButton->Caption;
  300. FSuspended = 0;
  301. UpdateButton();
  302. }
  303. //---------------------------------------------------------------------------
  304. void __fastcall TMessageTimeout::Suspend()
  305. {
  306. FSuspended = 30 * MSecsPerSec;
  307. FTimeout = FOrigTimeout;
  308. UpdateButton();
  309. }
  310. //---------------------------------------------------------------------------
  311. void __fastcall TMessageTimeout::Cancel()
  312. {
  313. Enabled = false;
  314. UpdateButton();
  315. }
  316. //---------------------------------------------------------------------------
  317. void __fastcall TMessageTimeout::UpdateButton()
  318. {
  319. assert(FButton != NULL);
  320. FButton->Caption =
  321. !Enabled ? FOrigCaption : FMTLOAD(TIMEOUT_BUTTON, (FOrigCaption, int(FTimeout / MSecsPerSec)));
  322. }
  323. //---------------------------------------------------------------------------
  324. void __fastcall TMessageTimeout::DoTimer(TObject * /*Sender*/)
  325. {
  326. if (FTimeout <= MSecsPerSec)
  327. {
  328. assert(FButton != NULL);
  329. TForm * Dialog = dynamic_cast<TForm *>(FButton->Parent);
  330. assert(Dialog != NULL);
  331. Dialog->ModalResult = FButton->ModalResult;
  332. }
  333. else
  334. {
  335. unsigned int & Timeout = (FSuspended > 0) ? FSuspended : FTimeout;
  336. if (Timeout > Interval)
  337. {
  338. Timeout -= Interval;
  339. }
  340. else
  341. {
  342. Timeout = 0;
  343. }
  344. UpdateButton();
  345. }
  346. }
  347. //---------------------------------------------------------------------
  348. class TPublicControl : public TControl
  349. {
  350. friend void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled);
  351. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  352. };
  353. //---------------------------------------------------------------------
  354. class TPublicWinControl : public TWinControl
  355. {
  356. friend void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout);
  357. };
  358. //---------------------------------------------------------------------------
  359. static void __fastcall MessageDialogMouseMove(void * Data, TObject * /*Sender*/,
  360. TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  361. {
  362. assert(Data != NULL);
  363. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  364. Timeout->Suspend();
  365. }
  366. //---------------------------------------------------------------------------
  367. static void __fastcall MessageDialogMouseDown(void * Data, TObject * /*Sender*/,
  368. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  369. {
  370. assert(Data != NULL);
  371. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  372. Timeout->Cancel();
  373. }
  374. //---------------------------------------------------------------------------
  375. static void __fastcall MessageDialogKeyDownUp(void * Data, TObject * /*Sender*/,
  376. Word & /*Key*/, TShiftState /*Shift*/)
  377. {
  378. assert(Data != NULL);
  379. TMessageTimeout * Timeout = static_cast<TMessageTimeout *>(Data);
  380. Timeout->Cancel();
  381. }
  382. //---------------------------------------------------------------------------
  383. void __fastcall SetTimeoutEvents(TControl * Control, TMessageTimeout * Timeout)
  384. {
  385. TPublicControl * PublicControl = reinterpret_cast<TPublicControl *>(Control);
  386. assert(PublicControl->OnMouseMove == NULL);
  387. PublicControl->OnMouseMove = MakeMethod<TMouseMoveEvent>(Timeout, MessageDialogMouseMove);
  388. assert(PublicControl->OnMouseDown == NULL);
  389. PublicControl->OnMouseDown = MakeMethod<TMouseEvent>(Timeout, MessageDialogMouseDown);
  390. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  391. if (WinControl != NULL)
  392. {
  393. TPublicWinControl * PublicWinControl = reinterpret_cast<TPublicWinControl *>(Control);
  394. assert(PublicWinControl->OnKeyDown == NULL);
  395. PublicWinControl->OnKeyDown = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  396. assert(PublicWinControl->OnKeyUp == NULL);
  397. PublicWinControl->OnKeyUp = MakeMethod<TKeyEvent>(Timeout, MessageDialogKeyDownUp);
  398. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  399. {
  400. SetTimeoutEvents(WinControl->Controls[Index], Timeout);
  401. }
  402. }
  403. }
  404. //---------------------------------------------------------------------------
  405. unsigned int __fastcall MoreMessageDialog(const UnicodeString Message, TStrings * MoreMessages,
  406. TQueryType Type, unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  407. {
  408. unsigned int Result;
  409. TForm * Dialog = NULL;
  410. TMessageTimer * Timer = NULL;
  411. TMessageTimeout * Timeout = NULL;
  412. try
  413. {
  414. UnicodeString AMessage = Message;
  415. if ((Params != NULL) && (Params->Timer > 0))
  416. {
  417. Timer = new TMessageTimer(Application);
  418. Timer->Interval = Params->Timer;
  419. Timer->Event = Params->TimerEvent;
  420. if (Params->TimerAnswers > 0)
  421. {
  422. Answers = Params->TimerAnswers;
  423. }
  424. if (Params->TimerQueryType >= 0)
  425. {
  426. Type = Params->TimerQueryType;
  427. }
  428. if (!Params->TimerMessage.IsEmpty())
  429. {
  430. AMessage = Params->TimerMessage;
  431. }
  432. }
  433. TButton * TimeoutButton = NULL;
  434. Dialog = CreateMessageDialogEx(AMessage, MoreMessages, Type, Answers,
  435. HelpKeyword, Params, TimeoutButton);
  436. if (Timer != NULL)
  437. {
  438. Timer->Dialog = Dialog;
  439. }
  440. if (Params != NULL)
  441. {
  442. if (Params->Timeout > 0)
  443. {
  444. Timeout = new TMessageTimeout(Application, Params->Timeout, TimeoutButton);
  445. SetTimeoutEvents(Dialog, Timeout);
  446. }
  447. }
  448. Result = ExecuteMessageDialog(Dialog, Answers, Params);
  449. }
  450. __finally
  451. {
  452. delete Dialog;
  453. delete Timer;
  454. delete Timeout;
  455. }
  456. return Result;
  457. }
  458. //---------------------------------------------------------------------------
  459. unsigned int __fastcall MessageDialog(const UnicodeString Msg, TQueryType Type,
  460. unsigned int Answers, UnicodeString HelpKeyword, const TMessageParams * Params)
  461. {
  462. return MoreMessageDialog(Msg, NULL, Type, Answers, HelpKeyword, Params);
  463. }
  464. //---------------------------------------------------------------------------
  465. unsigned int __fastcall SimpleErrorDialog(const UnicodeString Msg, const UnicodeString MoreMessages)
  466. {
  467. unsigned int Result;
  468. TStrings * More = NULL;
  469. try
  470. {
  471. if (!MoreMessages.IsEmpty())
  472. {
  473. More = new TStringList();
  474. More->Text = MoreMessages;
  475. }
  476. Result = MoreMessageDialog(Msg, More, qtError, qaOK, HELP_NONE);
  477. }
  478. __finally
  479. {
  480. delete More;
  481. }
  482. return Result;
  483. }
  484. //---------------------------------------------------------------------------
  485. unsigned int __fastcall ExceptionMessageDialog(Exception * E, TQueryType Type,
  486. const UnicodeString MessageFormat, unsigned int Answers, UnicodeString HelpKeyword,
  487. const TMessageParams * Params)
  488. {
  489. TStrings * MoreMessages = NULL;
  490. ExtException * EE = dynamic_cast<ExtException *>(E);
  491. if (EE != NULL)
  492. {
  493. MoreMessages = EE->MoreMessages;
  494. }
  495. UnicodeString Message;
  496. // this is always called from within ExceptionMessage check,
  497. // so it should never fail here
  498. CHECK(ExceptionMessageFormatted(E, Message));
  499. HelpKeyword = MergeHelpKeyword(HelpKeyword, GetExceptionHelpKeyword(E));
  500. return MoreMessageDialog(
  501. FORMAT(MessageFormat.IsEmpty() ? UnicodeString(L"%s") : MessageFormat, (Message)),
  502. MoreMessages, Type, Answers, HelpKeyword, Params);
  503. }
  504. //---------------------------------------------------------------------------
  505. unsigned int __fastcall FatalExceptionMessageDialog(Exception * E, TQueryType Type,
  506. int SessionReopenTimeout, const UnicodeString MessageFormat, unsigned int Answers,
  507. UnicodeString HelpKeyword, const TMessageParams * Params)
  508. {
  509. assert(FLAGCLEAR(Answers, qaRetry));
  510. Answers |= qaRetry;
  511. TQueryButtonAlias Aliases[1];
  512. Aliases[0].Button = qaRetry;
  513. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  514. TMessageParams AParams;
  515. if (Params != NULL)
  516. {
  517. AParams = *Params;
  518. }
  519. assert(AParams.Timeout == 0);
  520. // the condition is de facto excess
  521. if (SessionReopenTimeout > 0)
  522. {
  523. AParams.Timeout = SessionReopenTimeout;
  524. AParams.TimeoutAnswer = qaRetry;
  525. }
  526. assert(AParams.Aliases == NULL);
  527. AParams.Aliases = Aliases;
  528. AParams.AliasesCount = LENOF(Aliases);
  529. return ExceptionMessageDialog(E, Type, MessageFormat, Answers, HelpKeyword, &AParams);
  530. }
  531. //---------------------------------------------------------------------------
  532. void * __fastcall BusyStart()
  533. {
  534. void * Token = reinterpret_cast<void *>(Screen->Cursor);
  535. Screen->Cursor = crHourGlass;
  536. return Token;
  537. }
  538. //---------------------------------------------------------------------------
  539. void __fastcall BusyEnd(void * Token)
  540. {
  541. Screen->Cursor = reinterpret_cast<TCursor>(Token);
  542. }
  543. //---------------------------------------------------------------------------
  544. void __fastcall CopyParamListButton(TButton * Button)
  545. {
  546. if (!SupportsSplitButton())
  547. {
  548. MenuButton(Button);
  549. }
  550. }
  551. //---------------------------------------------------------------------------
  552. const int cpiDefault = -1;
  553. const int cpiConfigure = -2;
  554. const int cpiCustom = -3;
  555. const int cpiSaveSettings = -4;
  556. //---------------------------------------------------------------------------
  557. void __fastcall CopyParamListPopup(TRect Rect, TPopupMenu * Menu,
  558. const TCopyParamType & Param, UnicodeString Preset, TNotifyEvent OnClick,
  559. int Options, int CopyParamAttrs, bool SaveSettings)
  560. {
  561. Menu->Items->Clear();
  562. TMenuItem * CustomizeItem = NULL;
  563. TMenuItem * Item;
  564. if (FLAGSET(Options, cplCustomize))
  565. {
  566. Item = new TMenuItem(Menu);
  567. Item->Caption = LoadStr(COPY_PARAM_CUSTOM);
  568. Item->Tag = cpiCustom;
  569. Item->Default = FLAGSET(Options, cplCustomizeDefault);
  570. Item->OnClick = OnClick;
  571. Menu->Items->Add(Item);
  572. CustomizeItem = Item;
  573. }
  574. if (FLAGSET(Options, cplSaveSettings))
  575. {
  576. Item = new TMenuItem(Menu);
  577. Item->Caption = LoadStr(COPY_PARAM_SAVE_SETTINGS);
  578. Item->Tag = cpiSaveSettings;
  579. Item->Checked = SaveSettings;
  580. Item->OnClick = OnClick;
  581. Menu->Items->Add(Item);
  582. }
  583. Item = new TMenuItem(Menu);
  584. Item->Caption = LoadStr(COPY_PARAM_PRESET_HEADER);
  585. Item->Visible = false;
  586. Item->Enabled = false;
  587. Menu->Items->Add(Item);
  588. bool AnyChecked = false;
  589. Item = new TMenuItem(Menu);
  590. Item->Caption = LoadStr(COPY_PARAM_DEFAULT);
  591. Item->Tag = cpiDefault;
  592. Item->Checked =
  593. Preset.IsEmpty() && (GUIConfiguration->CopyParamPreset[L""] == Param);
  594. AnyChecked = AnyChecked || Item->Checked;
  595. Item->OnClick = OnClick;
  596. Menu->Items->Add(Item);
  597. TCopyParamType DefaultParam;
  598. const TCopyParamList * CopyParamList = GUIConfiguration->CopyParamList;
  599. for (int i = 0; i < CopyParamList->Count; i++)
  600. {
  601. UnicodeString Name = CopyParamList->Names[i];
  602. TCopyParamType AParam = GUIConfiguration->CopyParamPreset[Name];
  603. if (AParam.AnyUsableCopyParam(CopyParamAttrs) ||
  604. // This makes "Binary" preset visible,
  605. // as long as we care about transfer mode
  606. ((AParam == DefaultParam) &&
  607. FLAGCLEAR(CopyParamAttrs, cpaIncludeMaskOnly) &&
  608. FLAGCLEAR(CopyParamAttrs, cpaNoTransferMode)))
  609. {
  610. Item = new TMenuItem(Menu);
  611. Item->Caption = Name;
  612. Item->Tag = i;
  613. Item->Checked =
  614. (Preset == Name) && (AParam == Param);
  615. AnyChecked = AnyChecked || Item->Checked;
  616. Item->OnClick = OnClick;
  617. Menu->Items->Add(Item);
  618. }
  619. }
  620. if (CustomizeItem != NULL)
  621. {
  622. CustomizeItem->Checked = !AnyChecked;
  623. }
  624. Item = new TMenuItem(Menu);
  625. Item->Caption = L"-";
  626. Menu->Items->Add(Item);
  627. Item = new TMenuItem(Menu);
  628. Item->Caption = LoadStr(COPY_PARAM_CONFIGURE);
  629. Item->Tag = cpiConfigure;
  630. Item->OnClick = OnClick;
  631. Menu->Items->Add(Item);
  632. MenuPopup(Menu, Rect, NULL);
  633. }
  634. //---------------------------------------------------------------------------
  635. bool __fastcall CopyParamListPopupClick(TObject * Sender,
  636. TCopyParamType & Param, UnicodeString & Preset, int CopyParamAttrs,
  637. bool * SaveSettings)
  638. {
  639. TComponent * Item = dynamic_cast<TComponent *>(Sender);
  640. assert(Item != NULL);
  641. assert((Item->Tag >= cpiSaveSettings) && (Item->Tag < GUIConfiguration->CopyParamList->Count));
  642. bool Result;
  643. if (Item->Tag == cpiConfigure)
  644. {
  645. bool MatchedPreset = (GUIConfiguration->CopyParamPreset[Preset] == Param);
  646. DoPreferencesDialog(pmPresets);
  647. Result = (MatchedPreset && GUIConfiguration->HasCopyParamPreset[Preset]);
  648. if (Result)
  649. {
  650. Param = GUIConfiguration->CopyParamPreset[Preset];
  651. }
  652. }
  653. else if (Item->Tag == cpiCustom)
  654. {
  655. Result = DoCopyParamCustomDialog(Param, CopyParamAttrs);
  656. }
  657. else if (Item->Tag == cpiSaveSettings)
  658. {
  659. if (ALWAYS_TRUE(SaveSettings != NULL))
  660. {
  661. *SaveSettings = !*SaveSettings;
  662. }
  663. Result = false;
  664. }
  665. else
  666. {
  667. Preset = (Item->Tag >= 0) ?
  668. GUIConfiguration->CopyParamList->Names[Item->Tag] : UnicodeString();
  669. Param = GUIConfiguration->CopyParamPreset[Preset];
  670. Result = true;
  671. }
  672. return Result;
  673. }
  674. //---------------------------------------------------------------------------
  675. TWinInteractiveCustomCommand::TWinInteractiveCustomCommand(
  676. TCustomCommand * ChildCustomCommand, const UnicodeString CustomCommandName) :
  677. TInteractiveCustomCommand(ChildCustomCommand)
  678. {
  679. FCustomCommandName = StripHotkey(CustomCommandName);
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall TWinInteractiveCustomCommand::Prompt(
  683. const UnicodeString & Prompt, UnicodeString & Value)
  684. {
  685. UnicodeString APrompt = Prompt;
  686. if (APrompt.IsEmpty())
  687. {
  688. APrompt = FMTLOAD(CUSTOM_COMMANDS_PARAM_PROMPT, (FCustomCommandName));
  689. }
  690. TStrings * History = CustomWinConfiguration->History[L"CustomCommandParam"];
  691. if (InputDialog(FMTLOAD(CUSTOM_COMMANDS_PARAM_TITLE, (FCustomCommandName)),
  692. APrompt, Value, HELP_CUSTOM_COMMAND_PARAM, History))
  693. {
  694. CustomWinConfiguration->History[L"CustomCommandParam"] = History;
  695. }
  696. else
  697. {
  698. Abort();
  699. }
  700. }
  701. //---------------------------------------------------------------------------
  702. void __fastcall TWinInteractiveCustomCommand::Execute(
  703. const UnicodeString & Command, UnicodeString & Value)
  704. {
  705. // inspired by
  706. // http://forum.codecall.net/topic/72472-execute-a-console-program-and-capture-its-output/
  707. HANDLE StdOutOutput;
  708. HANDLE StdOutInput;
  709. HANDLE StdInOutput;
  710. HANDLE StdInInput;
  711. SECURITY_ATTRIBUTES SecurityAttributes;
  712. SecurityAttributes.nLength = sizeof(SecurityAttributes);
  713. SecurityAttributes.lpSecurityDescriptor = NULL;
  714. SecurityAttributes.bInheritHandle = TRUE;
  715. try
  716. {
  717. if (!CreatePipe(&StdOutOutput, &StdOutInput, &SecurityAttributes, 0))
  718. {
  719. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"out")));
  720. }
  721. else if (!CreatePipe(&StdInOutput, &StdInInput, &SecurityAttributes, 0))
  722. {
  723. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"in")));
  724. }
  725. else
  726. {
  727. STARTUPINFO StartupInfo;
  728. PROCESS_INFORMATION ProcessInformation;
  729. FillMemory(&StartupInfo, sizeof(StartupInfo), 0);
  730. StartupInfo.cb = sizeof(StartupInfo);
  731. StartupInfo.wShowWindow = SW_HIDE;
  732. StartupInfo.hStdInput = StdInOutput;
  733. StartupInfo.hStdOutput = StdOutInput;
  734. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  735. if (!CreateProcess(NULL, Command.c_str(), &SecurityAttributes, &SecurityAttributes,
  736. TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInformation))
  737. {
  738. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"process")));
  739. }
  740. else
  741. {
  742. try
  743. {
  744. // wait until the console program terminated
  745. bool Running = true;
  746. while (Running)
  747. {
  748. switch (WaitForSingleObject(ProcessInformation.hProcess, 200))
  749. {
  750. case WAIT_TIMEOUT:
  751. Application->ProcessMessages();
  752. break;
  753. case WAIT_OBJECT_0:
  754. Running = false;
  755. break;
  756. default:
  757. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"wait")));
  758. }
  759. }
  760. char Buffer[1024];
  761. unsigned long Read;
  762. while (PeekNamedPipe(StdOutOutput, NULL, 0, NULL, &Read, NULL) &&
  763. (Read > 0))
  764. {
  765. if (!ReadFile(StdOutOutput, &Buffer, Read, &Read, NULL))
  766. {
  767. throw Exception(FMTLOAD(SHELL_PATTERN_ERROR, (Command, L"read")));
  768. }
  769. else if (Read > 0)
  770. {
  771. Value += UnicodeString(AnsiString(Buffer, Read));
  772. }
  773. }
  774. // trim trailing cr/lf
  775. Value = TrimRight(Value);
  776. }
  777. __finally
  778. {
  779. CloseHandle(ProcessInformation.hProcess);
  780. CloseHandle(ProcessInformation.hThread);
  781. }
  782. }
  783. }
  784. }
  785. __finally
  786. {
  787. if (StdOutOutput != INVALID_HANDLE_VALUE)
  788. {
  789. CloseHandle(StdOutOutput);
  790. }
  791. if (StdOutInput != INVALID_HANDLE_VALUE)
  792. {
  793. CloseHandle(StdOutInput);
  794. }
  795. if (StdInOutput != INVALID_HANDLE_VALUE)
  796. {
  797. CloseHandle(StdInOutput);
  798. }
  799. if (StdInInput != INVALID_HANDLE_VALUE)
  800. {
  801. CloseHandle(StdInInput);
  802. }
  803. }
  804. }
  805. //---------------------------------------------------------------------------
  806. void __fastcall MenuPopup(TPopupMenu * Menu, TButton * Button)
  807. {
  808. MenuPopup(Menu, CalculatePopupRect(Button), Button);
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Handled)
  812. {
  813. TControl * Control = dynamic_cast<TControl *>(Sender);
  814. assert(Control != NULL);
  815. TPoint Point;
  816. if ((MousePos.x == -1) && (MousePos.y == -1))
  817. {
  818. Point = Control->ClientToScreen(TPoint(0, 0));
  819. }
  820. else
  821. {
  822. Point = Control->ClientToScreen(MousePos);
  823. }
  824. TPopupMenu * PopupMenu = (reinterpret_cast<TPublicControl *>(Control))->PopupMenu;
  825. assert(PopupMenu != NULL);
  826. TRect Rect(Point, Point);
  827. MenuPopup(PopupMenu, Rect, Control);
  828. Handled = true;
  829. }
  830. //---------------------------------------------------------------------------
  831. void __fastcall MenuButton(TButton * Button)
  832. {
  833. Button->Images = GlyphsModule->ButtonImages;
  834. Button->ImageIndex = 0;
  835. Button->DisabledImageIndex = 1;
  836. Button->ImageAlignment = iaRight;
  837. }
  838. //---------------------------------------------------------------------------
  839. TRect __fastcall CalculatePopupRect(TButton * Button)
  840. {
  841. TPoint UpPoint = Button->ClientToScreen(TPoint(0, 0));
  842. TPoint DownPoint = Button->ClientToScreen(TPoint(Button->Width, Button->Height));
  843. TRect Rect(UpPoint, DownPoint);
  844. // With themes enabled, button are rendered 1 pixel smaller than their actual size
  845. int Offset = UseThemes() ? -1 : 0;
  846. Rect.Inflate(Offset, Offset);
  847. return Rect;
  848. }
  849. //---------------------------------------------------------------------------
  850. TRect __fastcall CalculatePopupRect(TControl * Control, TPoint MousePos)
  851. {
  852. MousePos = Control->ClientToScreen(MousePos);
  853. TRect Rect(MousePos, MousePos);
  854. return Rect;
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall FixButtonImage(TButton * Button)
  858. {
  859. // this themes enabled, button image is by default drawn too high
  860. if (UseThemes())
  861. {
  862. Button->ImageMargins->Top = 1;
  863. }
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall UncenterButtonImage(TButton * Button)
  867. {
  868. Button->ImageMargins->Left = 0;
  869. if (UseThemes())
  870. {
  871. Button->Caption = TrimLeft(Button->Caption);
  872. }
  873. }
  874. //---------------------------------------------------------------------------
  875. void __fastcall CenterButtonImage(TButton * Button)
  876. {
  877. UncenterButtonImage(Button);
  878. // with themes disabled, the text seems to be drawn over the icon,
  879. // so that the padding spaces hide away most of the icon
  880. if (UseThemes())
  881. {
  882. Button->ImageAlignment = iaCenter;
  883. int ImageWidth = Button->Images->Width;
  884. std::unique_ptr<TControlCanvas> Canvas(new TControlCanvas());
  885. Canvas->Control = Button;
  886. UnicodeString Caption = Button->Caption;
  887. UnicodeString Padding;
  888. while (Canvas->TextWidth(Padding) < ImageWidth)
  889. {
  890. Padding += L" ";
  891. }
  892. Caption = Padding + Caption;
  893. Button->Caption = Caption;
  894. int CaptionWidth = Canvas->TextWidth(Caption);
  895. // The margins seem to extend the area over which the image is centered,
  896. // so we have to set it to a double of desired padding.
  897. // Note that (CaptionWidth / 2) - (ImageWidth / 2)
  898. // is approximatelly same as half of caption width before padding.
  899. Button->ImageMargins->Left = - 2 * ((CaptionWidth / 2) - (ImageWidth / 2) + ScaleByTextHeight(Button, 2));
  900. }
  901. else
  902. {
  903. // at least do not draw it so near to the edge
  904. Button->ImageMargins->Left = 1;
  905. }
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall SetGlobalMinimizeHandler(TCustomForm * /*Form*/, TNotifyEvent OnMinimize)
  909. {
  910. if (GlobalOnMinimize == NULL)
  911. {
  912. GlobalOnMinimize = OnMinimize;
  913. }
  914. }
  915. //---------------------------------------------------------------------------
  916. void __fastcall ClearGlobalMinimizeHandler(TNotifyEvent OnMinimize)
  917. {
  918. if (GlobalOnMinimize == OnMinimize)
  919. {
  920. GlobalOnMinimize = NULL;
  921. }
  922. }
  923. //---------------------------------------------------------------------------
  924. void __fastcall CallGlobalMinimizeHandler(TObject * Sender)
  925. {
  926. Configuration->Usage->Inc(L"OperationMinimizations");
  927. if (ALWAYS_TRUE(GlobalOnMinimize != NULL))
  928. {
  929. GlobalOnMinimize(Sender);
  930. }
  931. }
  932. //---------------------------------------------------------------------------
  933. static void __fastcall DoApplicationMinimizeRestore(bool Minimize)
  934. {
  935. // WORKAROUND
  936. // When main window is hidden (command-line operation),
  937. // we do not want it to be shown by TApplication.Restore,
  938. // so we temporarily detach it from an application.
  939. // Probably not really necessary for minimizing phase,
  940. // but we do it for consistency anyway.
  941. TForm * MainForm = Application->MainForm;
  942. bool RestoreMainForm = false;
  943. if (ALWAYS_TRUE(MainForm != NULL) &&
  944. !MainForm->Visible)
  945. {
  946. SetAppMainForm(NULL);
  947. RestoreMainForm = true;
  948. }
  949. try
  950. {
  951. if (Minimize)
  952. {
  953. Application->Minimize();
  954. }
  955. else
  956. {
  957. Application->Restore();
  958. }
  959. }
  960. __finally
  961. {
  962. if (RestoreMainForm)
  963. {
  964. SetAppMainForm(MainForm);
  965. }
  966. }
  967. }
  968. //---------------------------------------------------------------------------
  969. void __fastcall ApplicationMinimize()
  970. {
  971. DoApplicationMinimizeRestore(true);
  972. }
  973. //---------------------------------------------------------------------------
  974. void __fastcall ApplicationRestore()
  975. {
  976. DoApplicationMinimizeRestore(false);
  977. }
  978. //---------------------------------------------------------------------------
  979. bool __fastcall IsApplicationMinimized()
  980. {
  981. // VCL help recommends handling Application->OnMinimize/OnRestore
  982. // for tracking state, but OnRestore is actually not called
  983. // (OnMinimize is), when app is minimized from e.g. Progress window
  984. bool AppMinimized = IsIconic(Application->Handle);
  985. bool MainFormMinimized = IsIconic(Application->MainFormHandle);
  986. return AppMinimized || MainFormMinimized;
  987. }
  988. //---------------------------------------------------------------------------
  989. UnicodeString __fastcall TranslateDateFormat(UnicodeString FormatStr)
  990. {
  991. UnicodeString Result;
  992. CALTYPE CalendarType = StrToIntDef(GetLocaleStr(GetDefaultLCID(), LOCALE_ICALENDARTYPE, L"1"), 1);
  993. if ((CalendarType != CAL_JAPAN) && (CalendarType != CAL_TAIWAN) && (CalendarType != CAL_KOREA))
  994. {
  995. bool RemoveEra =
  996. (SysLocale.PriLangID == LANG_JAPANESE) ||
  997. (SysLocale.PriLangID == LANG_CHINESE) ||
  998. (SysLocale.PriLangID == LANG_KOREAN);
  999. if (RemoveEra)
  1000. {
  1001. int I = 1;
  1002. while (I <= FormatStr.Length())
  1003. {
  1004. if ((FormatStr[I] != L'g') && (FormatStr[I] != L'G'))
  1005. {
  1006. Result += FormatStr[I];
  1007. }
  1008. I++;
  1009. }
  1010. }
  1011. else
  1012. {
  1013. Result = FormatStr;
  1014. }
  1015. }
  1016. else
  1017. {
  1018. int I = 1;
  1019. while (I <= FormatStr.Length())
  1020. {
  1021. if (FormatStr.IsLeadSurrogate(I))
  1022. {
  1023. int L = CharLength(FormatStr, I);
  1024. Result += FormatStr.SubString(I, L);
  1025. I += L;
  1026. }
  1027. else
  1028. {
  1029. if (StrLIComp(FormatStr.c_str() + I - 1, L"gg", 2) == 0)
  1030. {
  1031. Result += L"ggg";
  1032. I++;
  1033. }
  1034. else if (StrLIComp(FormatStr.c_str() + I - 1, L"yyyy", 4) == 0)
  1035. {
  1036. Result += L"eeee";
  1037. I += 4 - 1;
  1038. }
  1039. else if (StrLIComp(FormatStr.c_str() + I - 1, L"yy", 2) == 0)
  1040. {
  1041. Result += L"ee";
  1042. I += 2 - 1;
  1043. }
  1044. else if ((FormatStr[I] == L'y') || (FormatStr[I] == L'Y'))
  1045. {
  1046. Result += L"e";
  1047. }
  1048. else
  1049. {
  1050. Result += FormatStr[I];
  1051. }
  1052. I++;
  1053. }
  1054. }
  1055. }
  1056. return Result;
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall GetFormatSettingsFix()
  1060. {
  1061. // todo InitSysLocale
  1062. // todo GetMonthDayNames
  1063. // todo GetEraNamesAndYearOffsets
  1064. LCID DefaultLCID = GetDefaultLCID();
  1065. FormatSettings = TFormatSettings::Create(DefaultLCID);
  1066. #pragma warn -8111
  1067. CurrencyString = GetLocaleStr(DefaultLCID, LOCALE_SCURRENCY, L"");
  1068. CurrencyFormat = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRENCY, L"0"), 0);
  1069. NegCurrFormat = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_INEGCURR, L"0"), 0);
  1070. ThousandSeparator = GetLocaleChar(DefaultLCID, LOCALE_STHOUSAND, L',');
  1071. DecimalSeparator = GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, L'.');
  1072. CurrencyDecimals = (Byte) StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRDIGITS, L"0"), 0);
  1073. DateSeparator = GetLocaleChar(DefaultLCID, LOCALE_SDATE, L'/');
  1074. ShortDateFormat = TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SSHORTDATE, L"m/d/yy"));
  1075. LongDateFormat = TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SLONGDATE, L"mmmm d, yyyy"));
  1076. TimeSeparator = GetLocaleChar(DefaultLCID, LOCALE_STIME, L':');
  1077. TimeAMString = GetLocaleStr(DefaultLCID, LOCALE_S1159, L"am");
  1078. TimePMString = GetLocaleStr(DefaultLCID, LOCALE_S2359, L"pm");
  1079. UnicodeString HourFormat;
  1080. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITLZERO, L"0"), 0) == 0)
  1081. {
  1082. HourFormat = L"h";
  1083. }
  1084. else
  1085. {
  1086. HourFormat = L"hh";
  1087. }
  1088. UnicodeString TimePrefix, TimePostfix;
  1089. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIME, L"0"), 0) == 0)
  1090. {
  1091. if (StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIMEMARKPOSN, L"0"), 0) == 0)
  1092. {
  1093. TimePostfix = L" AMPM";
  1094. }
  1095. else
  1096. {
  1097. TimePrefix = L"AMPM ";
  1098. }
  1099. }
  1100. ShortTimeFormat = TimePrefix + HourFormat + L":mm" + TimePostfix;
  1101. LongTimeFormat = TimePrefix + HourFormat + L":mm:ss" + TimePostfix;
  1102. ListSeparator = GetLocaleChar(DefaultLCID, LOCALE_SLIST, L',');
  1103. #pragma warn .8111
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. void __fastcall WinInitialize()
  1107. {
  1108. SetErrorMode(SEM_FAILCRITICALERRORS);
  1109. // HACK
  1110. if (::IsWin7())
  1111. {
  1112. GetFormatSettingsFix();
  1113. }
  1114. #pragma warn -8111
  1115. #pragma warn .8111
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. struct TNotifyIconData5
  1119. {
  1120. DWORD cbSize;
  1121. HWND hWnd;
  1122. UINT uID;
  1123. UINT uFlags;
  1124. UINT uCallbackMessage;
  1125. HICON hIcon;
  1126. TCHAR szTip[128];
  1127. DWORD dwState;
  1128. DWORD dwStateMask;
  1129. TCHAR szInfo[256];
  1130. union {
  1131. UINT uTimeout;
  1132. UINT uVersion;
  1133. } DUMMYUNIONNAME;
  1134. TCHAR szInfoTitle[64];
  1135. DWORD dwInfoFlags;
  1136. };
  1137. //---------------------------------------------------------------------------
  1138. __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id)
  1139. {
  1140. FVisible = false;
  1141. FOnClick = NULL;
  1142. FOnBalloonClick = NULL;
  1143. FBalloonUserData = NULL;
  1144. FTrayIcon = new TNotifyIconData5;
  1145. memset(FTrayIcon, 0, sizeof(*FTrayIcon));
  1146. FTrayIcon->cbSize = sizeof(*FTrayIcon);
  1147. FTrayIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  1148. // LoadIconMetric is available from Windows Vista only
  1149. HMODULE ComCtl32Dll = GetModuleHandle(comctl32);
  1150. if (ALWAYS_TRUE(ComCtl32Dll))
  1151. {
  1152. typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico);
  1153. TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric");
  1154. if (LoadIconMetric != NULL)
  1155. {
  1156. // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason
  1157. LoadIconMetric(MainInstance, L"MAINICON", LIM_SMALL, &FTrayIcon->hIcon);
  1158. }
  1159. }
  1160. if (FTrayIcon->hIcon == 0)
  1161. {
  1162. FTrayIcon->hIcon = Application->Icon->Handle;
  1163. }
  1164. FTrayIcon->uID = Id;
  1165. FTrayIcon->hWnd = AllocateHWnd(WndProc);
  1166. FTrayIcon->uCallbackMessage = WM_TRAY_ICON;
  1167. FTaskbarCreatedMsg = RegisterWindowMessage(L"TaskbarCreated");
  1168. }
  1169. //---------------------------------------------------------------------------
  1170. __fastcall ::TTrayIcon::~TTrayIcon()
  1171. {
  1172. // make sure we hide icon even in case it was shown just to pop up the balloon
  1173. // (in which case Visible == false)
  1174. CancelBalloon();
  1175. Visible = false;
  1176. DeallocateHWnd(FTrayIcon->hWnd);
  1177. delete FTrayIcon;
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall ::TTrayIcon::PopupBalloon(UnicodeString Title,
  1181. const UnicodeString & Str, TQueryType QueryType, unsigned int Timeout,
  1182. TNotifyEvent OnBalloonClick, TObject * BalloonUserData)
  1183. {
  1184. if (Timeout > 30000)
  1185. {
  1186. // this is probably system limit, do not try more, especially for
  1187. // the timeout-driven hiding of the tray icon (for Win2k)
  1188. Timeout = 30000;
  1189. }
  1190. FTrayIcon->uFlags |= NIF_INFO;
  1191. Title = FORMAT(L"%s - %s", (Title, AppNameString()));
  1192. StrPLCopy(FTrayIcon->szInfoTitle, Title, LENOF(FTrayIcon->szInfoTitle) - 1);
  1193. StrPLCopy(FTrayIcon->szInfo, Str, LENOF(FTrayIcon->szInfo) - 1);
  1194. FTrayIcon->uTimeout = Timeout;
  1195. switch (QueryType)
  1196. {
  1197. case qtError:
  1198. FTrayIcon->dwInfoFlags = NIIF_ERROR;
  1199. break;
  1200. case qtInformation:
  1201. case qtConfirmation:
  1202. FTrayIcon->dwInfoFlags = NIIF_INFO;
  1203. break;
  1204. case qtWarning:
  1205. default:
  1206. FTrayIcon->dwInfoFlags = NIIF_WARNING;
  1207. break;
  1208. }
  1209. KillTimer(FTrayIcon->hWnd, 1);
  1210. if (Visible)
  1211. {
  1212. Update();
  1213. }
  1214. else
  1215. {
  1216. Notify(NIM_ADD);
  1217. }
  1218. FOnBalloonClick = OnBalloonClick;
  1219. delete FBalloonUserData;
  1220. FBalloonUserData = BalloonUserData;
  1221. // Clearing the flag ensures that subsequent updates does not hide the baloon
  1222. // unless CancelBalloon is called explicitly
  1223. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. void __fastcall ::TTrayIcon::BalloonCancelled()
  1227. {
  1228. FOnBalloonClick = NULL;
  1229. delete FBalloonUserData;
  1230. FBalloonUserData = NULL;
  1231. }
  1232. //---------------------------------------------------------------------------
  1233. void __fastcall ::TTrayIcon::CancelBalloon()
  1234. {
  1235. KillTimer(FTrayIcon->hWnd, 1);
  1236. if (Visible)
  1237. {
  1238. FTrayIcon->uFlags |= NIF_INFO;
  1239. FTrayIcon->szInfo[0] = L'\0';
  1240. Update();
  1241. FTrayIcon->uFlags = FTrayIcon->uFlags & ~NIF_INFO;
  1242. }
  1243. else
  1244. {
  1245. Notify(NIM_DELETE);
  1246. }
  1247. BalloonCancelled();
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. bool __fastcall ::TTrayIcon::Notify(unsigned int Message)
  1251. {
  1252. bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon));
  1253. if (Result && (Message == NIM_ADD))
  1254. {
  1255. UINT Timeout = FTrayIcon->uTimeout;
  1256. try
  1257. {
  1258. FTrayIcon->uVersion = NOTIFYICON_VERSION;
  1259. Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon));
  1260. }
  1261. __finally
  1262. {
  1263. FTrayIcon->uTimeout = Timeout;
  1264. }
  1265. }
  1266. return Result;
  1267. }
  1268. //---------------------------------------------------------------------------
  1269. void __fastcall ::TTrayIcon::Update()
  1270. {
  1271. if (Visible)
  1272. {
  1273. Notify(NIM_MODIFY);
  1274. }
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. void __fastcall ::TTrayIcon::SetVisible(bool value)
  1278. {
  1279. if (Visible != value)
  1280. {
  1281. if (value)
  1282. {
  1283. FVisible = Notify(NIM_ADD);
  1284. }
  1285. else
  1286. {
  1287. FVisible = false;
  1288. KillTimer(FTrayIcon->hWnd, 1);
  1289. Notify(NIM_DELETE);
  1290. BalloonCancelled();
  1291. }
  1292. }
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall ::TTrayIcon::WndProc(TMessage & Message)
  1296. {
  1297. try
  1298. {
  1299. if (Message.Msg == WM_TRAY_ICON)
  1300. {
  1301. assert(Message.WParam == 0);
  1302. switch (Message.LParam)
  1303. {
  1304. // old shell32
  1305. case WM_LBUTTONUP:
  1306. case WM_RBUTTONUP:
  1307. // new shell32:
  1308. case WM_CONTEXTMENU:
  1309. if (OnClick != NULL)
  1310. {
  1311. OnClick(NULL);
  1312. }
  1313. Message.Result = true;
  1314. break;
  1315. }
  1316. if (Message.LParam == NIN_BALLOONUSERCLICK)
  1317. {
  1318. if (FOnBalloonClick != NULL)
  1319. {
  1320. // prevent the user data from being freed by possible call
  1321. // to CancelBalloon or PopupBalloon during call to OnBalloonClick
  1322. std::unique_ptr<TObject> UserData(FBalloonUserData);
  1323. FBalloonUserData = NULL;
  1324. FOnBalloonClick(UserData.get());
  1325. }
  1326. else if (OnClick != NULL)
  1327. {
  1328. OnClick(NULL);
  1329. }
  1330. }
  1331. switch (Message.LParam)
  1332. {
  1333. case NIN_BALLOONHIDE:
  1334. case NIN_BALLOONTIMEOUT:
  1335. case NIN_BALLOONUSERCLICK:
  1336. KillTimer(FTrayIcon->hWnd, 1);
  1337. // if icon was shown just to display balloon, hide it with the balloon
  1338. if (!Visible)
  1339. {
  1340. Notify(NIM_DELETE);
  1341. }
  1342. BalloonCancelled();
  1343. break;
  1344. }
  1345. }
  1346. else if (Message.Msg == WM_TIMER)
  1347. {
  1348. // sanity check
  1349. Notify(NIM_DELETE);
  1350. BalloonCancelled();
  1351. }
  1352. else if (Message.Msg == FTaskbarCreatedMsg)
  1353. {
  1354. if (Visible)
  1355. {
  1356. // force recreation
  1357. Visible = false;
  1358. Visible = true;
  1359. }
  1360. }
  1361. else
  1362. {
  1363. Message.Result = DefWindowProc(FTrayIcon->hWnd, Message.Msg, Message.WParam, Message.LParam);
  1364. }
  1365. }
  1366. catch(Exception & E)
  1367. {
  1368. Application->HandleException(&E);
  1369. }
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. UnicodeString __fastcall ::TTrayIcon::GetHint()
  1373. {
  1374. return FTrayIcon->szTip;
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. void __fastcall ::TTrayIcon::SetHint(UnicodeString value)
  1378. {
  1379. if (Hint != value)
  1380. {
  1381. unsigned int Max = LENOF(FTrayIcon->szTip);
  1382. StrPLCopy(FTrayIcon->szTip, value, Max - 1);
  1383. Update();
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------