WinInterface.cpp 54 KB

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