Editor.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Common.h>
  5. #include "Editor.h"
  6. #include "TextsWin.h"
  7. #include "Tools.h"
  8. #include <CoreMain.h>
  9. #include "VCLCommon.h"
  10. #include "WinConfiguration.h"
  11. #include "HelpWin.h"
  12. #include <BaseUtils.hpp>
  13. #include <GUITools.h>
  14. //---------------------------------------------------------------------------
  15. #pragma package(smart_init)
  16. #pragma link "TB2Dock"
  17. #pragma link "TBX"
  18. #pragma link "TB2Item"
  19. #pragma link "TB2Toolbar"
  20. #pragma link "TBXStatusBars"
  21. #pragma link "PngImageList"
  22. #pragma link "TBXExtItems"
  23. #pragma resource "*.dfm"
  24. //---------------------------------------------------------------------------
  25. TForm * __fastcall ShowEditorForm(const UnicodeString FileName, TForm * ParentForm,
  26. TNotifyEvent OnFileChanged, TNotifyEvent OnFileReload, TFileClosedEvent OnClose,
  27. TNotifyEvent OnSaveAll, TAnyModifiedEvent OnAnyModified,
  28. const UnicodeString Caption, bool StandaloneEditor, TColor Color, int InternalEditorEncodingOverride,
  29. bool NewFile)
  30. {
  31. TEditorForm * Dialog = new TEditorForm(Application);
  32. try
  33. {
  34. Dialog->FileName = FileName;
  35. Dialog->ParentForm = ParentForm;
  36. UnicodeString ACaption = Caption.IsEmpty() ? FileName : Caption;
  37. Dialog->Caption = ACaption + TitleSeparator + LoadStr(EDITOR_CAPTION) + TitleSeparator + AppName;
  38. Dialog->OnFileChanged = OnFileChanged;
  39. Dialog->OnFileReload = OnFileReload;
  40. Dialog->OnSaveAll = OnSaveAll;
  41. Dialog->OnAnyModified = OnAnyModified;
  42. Dialog->StandaloneEditor = StandaloneEditor;
  43. Dialog->BackgroundColor = Color;
  44. Dialog->InternalEditorEncodingOverride = InternalEditorEncodingOverride;
  45. Dialog->NewFile = NewFile;
  46. // load before showing, so when loading failes,
  47. // we do not show an empty editor
  48. Dialog->LoadFile();
  49. Dialog->Show();
  50. // make sure editor closing is announced only if it was ever successfully shown
  51. // (at least current implementation of the events cannot handle that)
  52. Dialog->OnWindowClose = OnClose;
  53. }
  54. catch(...)
  55. {
  56. delete Dialog;
  57. throw;
  58. }
  59. return Dialog;
  60. }
  61. //---------------------------------------------------------------------------
  62. void __fastcall ReconfigureEditorForm(TForm * Form)
  63. {
  64. TEditorForm * Editor = dynamic_cast<TEditorForm *>(Form);
  65. DebugAssert(Editor != NULL);
  66. Editor->ApplyConfiguration();
  67. }
  68. //---------------------------------------------------------------------------
  69. void __fastcall EditorFormFileUploadComplete(TForm * Form)
  70. {
  71. DebugNotNull(dynamic_cast<TEditorForm *>(Form))->FileUploadComplete();
  72. }
  73. //---------------------------------------------------------------------------
  74. void __fastcall EditorFormFileSave(TForm * Form)
  75. {
  76. DebugNotNull(dynamic_cast<TEditorForm *>(Form))->SaveFile();
  77. }
  78. //---------------------------------------------------------------------------
  79. bool __fastcall IsEditorFormModified(TForm * Form)
  80. {
  81. return DebugNotNull(dynamic_cast<TEditorForm *>(Form))->IsFileModified();
  82. }
  83. //---------------------------------------------------------------------------
  84. class TPreambleFilteringFileStream : public TFileStream
  85. {
  86. public:
  87. __fastcall TPreambleFilteringFileStream(const UnicodeString AFileName, System::Word Mode,
  88. TEncoding * Encoding, bool AllowPreamble);
  89. virtual int __fastcall Write(const void * Buffer, int Count);
  90. virtual int __fastcall Write(const System::DynamicArray<System::Byte> Buffer, int Offset, int Count);
  91. private:
  92. TBytes FPreamble;
  93. bool FDisallowPreamble;
  94. };
  95. //---------------------------------------------------------------------------
  96. __fastcall TPreambleFilteringFileStream::TPreambleFilteringFileStream(
  97. const UnicodeString AFileName, System::Word Mode,
  98. TEncoding * Encoding, bool AllowPreamble) :
  99. TFileStream(AFileName, Mode)
  100. {
  101. FDisallowPreamble = (Encoding != NULL) && !AllowPreamble;
  102. if (FDisallowPreamble)
  103. {
  104. FPreamble = Encoding->GetPreamble();
  105. }
  106. }
  107. //---------------------------------------------------------------------------
  108. int __fastcall TPreambleFilteringFileStream::Write(const void * Buffer, int Count)
  109. {
  110. bool IsDisallowedPreamble = false;
  111. if (FDisallowPreamble && (Count > 0) && (FPreamble.Length == Count))
  112. {
  113. int Index = 0;
  114. IsDisallowedPreamble = true;
  115. const unsigned char * ByteBuffer = reinterpret_cast<const unsigned char *>(Buffer);
  116. while (IsDisallowedPreamble && (Index < Count))
  117. {
  118. IsDisallowedPreamble = (ByteBuffer[Index] == FPreamble[Index]);
  119. Index++;
  120. }
  121. }
  122. // only on the first write
  123. FDisallowPreamble = false;
  124. int Result;
  125. if (IsDisallowedPreamble)
  126. {
  127. Result = Count;
  128. }
  129. else
  130. {
  131. Result = TFileStream::Write(Buffer, Count);
  132. }
  133. return Result;
  134. }
  135. //---------------------------------------------------------------------------
  136. int __fastcall TPreambleFilteringFileStream::Write(
  137. const System::DynamicArray<System::Byte> /*Buffer*/, int /*Offset*/, int /*Count*/)
  138. {
  139. DebugFail();
  140. EXCEPTION;
  141. }
  142. //---------------------------------------------------------------------------
  143. class TEditorRichEdit : public TRichEdit
  144. {
  145. public:
  146. virtual __fastcall TEditorRichEdit(TComponent * AOwner);
  147. bool __fastcall LoadFromStream(TStream * Stream, TEncoding * Encoding, bool & EncodingError);
  148. void __fastcall SetFormat(const TFontConfiguration & FontConfiguration,
  149. TColor FontColor, unsigned int TabSize, bool AWordWrap);
  150. void __fastcall ResetFormat();
  151. int __fastcall FindText(const UnicodeString SearchStr, int StartPos, int Length,
  152. TSearchTypes Options, bool Down);
  153. void __fastcall Redo();
  154. void __fastcall ApplyFont();
  155. __property bool CanRedo = { read = GetCanRedo };
  156. __property bool LoadedWithPreamble = { read = FLoadedWithPreamble };
  157. protected:
  158. friend unsigned long __stdcall StreamLoad(DWORD_PTR Cookie, unsigned char * Buff, long Read, long * WasRead);
  159. virtual void __fastcall CreateParams(TCreateParams & Params);
  160. virtual void __fastcall CreateWnd();
  161. void __fastcall Dispatch(void * Message);
  162. bool __fastcall GetCanRedo();
  163. void __fastcall SetTabSize(unsigned int TabSize);
  164. void __fastcall WMPaste();
  165. void __fastcall EMStreamIn(TMessage & Message);
  166. void WMMouseWheel(TMessage & Message);
  167. void WMMouseActivate(TWMMouseActivate & Message);
  168. bool __stdcall StreamLoad(TRichEditStreamInfo * StreamInfo,
  169. unsigned char * Buff, long Read, long & WasRead);
  170. DYNAMIC void __fastcall KeyDown(Word & Key, TShiftState Shift);
  171. private:
  172. HINSTANCE FLibrary;
  173. bool FWordWrap;
  174. unsigned int FTabSize;
  175. bool FInitialized;
  176. bool FStreamLoadEncodingError;
  177. bool FStreamLoadError;
  178. bool FLoadedWithPreamble;
  179. TFontConfiguration FFontConfiguration;
  180. TColor FFontColor;
  181. };
  182. //---------------------------------------------------------------------------
  183. __fastcall TEditorRichEdit::TEditorRichEdit(TComponent * AOwner) :
  184. TRichEdit(AOwner),
  185. FLibrary(0),
  186. FTabSize(0),
  187. FWordWrap(true),
  188. FInitialized(false),
  189. FLoadedWithPreamble(false)
  190. {
  191. }
  192. //---------------------------------------------------------------------------
  193. void __fastcall TEditorRichEdit::ApplyFont()
  194. {
  195. std::unique_ptr<TFont> NewFont(new TFont());
  196. TWinConfiguration::RestoreFont(FFontConfiguration, NewFont.get());
  197. // Rich Edit 4.1 scales the font on its own
  198. NewFont->Color = GetWindowTextColor(Color, FFontColor);
  199. if (!FInitialized ||
  200. !SameFont(Font, NewFont.get()) ||
  201. (Font->Color != NewFont->Color))
  202. {
  203. Font->Assign(NewFont.get());
  204. }
  205. }
  206. //---------------------------------------------------------------------------
  207. void __fastcall TEditorRichEdit::SetFormat(
  208. const TFontConfiguration & FontConfiguration, TColor FontColor, unsigned int TabSize,
  209. bool AWordWrap)
  210. {
  211. if (!FInitialized)
  212. {
  213. // for efficiency we should be creating handle here
  214. DebugAssert(!HandleAllocated());
  215. }
  216. // setting DefAttributes is noop if we do not have a handle
  217. // (btw code below would create one anyway)
  218. // (and we now do not set DefAttributes anymore anyway)
  219. HandleNeeded();
  220. LockWindowUpdate(Handle);
  221. FFontConfiguration = FontConfiguration;
  222. FFontColor = FontColor;
  223. ApplyFont();
  224. if (!FInitialized ||
  225. (FTabSize != TabSize))
  226. {
  227. SetTabSize(TabSize);
  228. FTabSize = TabSize;
  229. }
  230. if (!FInitialized ||
  231. (FWordWrap != AWordWrap))
  232. {
  233. DebugAssert(HandleAllocated());
  234. // Undocumented usage of EM_SETTARGETDEVICE.
  235. // But note that it is used by MFC in CRichEditView::WrapChanged()
  236. SendMessage(Handle, EM_SETTARGETDEVICE, 0, (AWordWrap ? 0 : 1));
  237. FWordWrap = AWordWrap;
  238. }
  239. LockWindowUpdate(NULL);
  240. FInitialized = true;
  241. }
  242. //---------------------------------------------------------------------------
  243. void __fastcall TEditorRichEdit::ResetFormat()
  244. {
  245. // tabs are paragraph attributes, which default values cannot be set,
  246. // so we need to reapply them after loading file
  247. SetTabSize(FTabSize);
  248. }
  249. //---------------------------------------------------------------------------
  250. int __fastcall TEditorRichEdit::FindText(const UnicodeString SearchStr, int StartPos,
  251. int /*Length*/, TSearchTypes Options, bool Down)
  252. {
  253. ::FINDTEXTEX Find;
  254. memset(&Find, 0, sizeof(Find));
  255. Find.chrg.cpMin = StartPos;
  256. Find.chrg.cpMax = -1;
  257. Find.lpstrText = UnicodeString(SearchStr).c_str();
  258. unsigned int Flags =
  259. FLAGMASK(Options.Contains(stWholeWord), FR_WHOLEWORD) |
  260. FLAGMASK(Options.Contains(stMatchCase), FR_MATCHCASE) |
  261. FLAGMASK(Down, FR_DOWN);
  262. int Result = SendMessage(Handle, EM_FINDTEXTEX, Flags, (LPARAM)&Find);
  263. return Result;
  264. }
  265. //---------------------------------------------------------------------------
  266. void __fastcall TEditorRichEdit::Redo()
  267. {
  268. SendMessage(Handle, EM_REDO, 0, 0);
  269. }
  270. //---------------------------------------------------------------------------
  271. void __fastcall TEditorRichEdit::CreateParams(TCreateParams & Params)
  272. {
  273. TRichEdit::CreateParams(Params);
  274. Params.Style = Params.Style |
  275. (HideScrollBars ? 0 : ES_DISABLENOSCROLL) |
  276. (HideSelection ? 0 : ES_NOHIDESEL);
  277. Params.WindowClass.style = Params.WindowClass.style &
  278. ~(CS_HREDRAW | CS_VREDRAW);
  279. }
  280. //---------------------------------------------------------------------------
  281. void __fastcall TEditorRichEdit::CreateWnd()
  282. {
  283. TRichEdit::CreateWnd();
  284. if (!WinConfiguration->Editor.AutoFont)
  285. {
  286. int LangOptions = SendMessage(Handle, EM_GETLANGOPTIONS, 0, 0);
  287. LangOptions = (LangOptions & ~IMF_AUTOFONT) | IMF_AUTOKEYBOARD;
  288. SendMessage(Handle, EM_SETLANGOPTIONS, 0, LangOptions);
  289. }
  290. }
  291. //---------------------------------------------------------------------------
  292. void __fastcall TEditorRichEdit::WMPaste()
  293. {
  294. // override default pasting to prevent inserting formatted text (RTF).
  295. const wchar_t * Text = NULL;
  296. HANDLE Handle = OpenTextFromClipboard(Text);
  297. if (Handle != NULL)
  298. {
  299. try
  300. {
  301. // replacement for EM_PASTESPECIAL,
  302. // which ignores trailing line end for some reason
  303. Perform(EM_REPLACESEL, true, reinterpret_cast<int>(Text));
  304. }
  305. __finally
  306. {
  307. CloseTextFromClipboard(Handle);
  308. }
  309. }
  310. }
  311. //---------------------------------------------------------------------------
  312. // VCLCOPY Vcl.ComCtrls.pas
  313. static int __fastcall AdjustLineBreaks(unsigned char * Dest, const TBytes & Source, int Start, int Len)
  314. {
  315. unsigned char * P = Dest;
  316. int I = Start; // Position in Source
  317. while (I < (Len - 1))
  318. {
  319. if ((Source[I] == 10) && (Source[I + 1] == 0))
  320. {
  321. // Convert #10 to #13#10
  322. *P = 13;
  323. P++;
  324. *P = 0;
  325. P++;
  326. *P = 10;
  327. P++;
  328. *P = 0;
  329. P++;
  330. }
  331. else
  332. {
  333. *P = Source[I];
  334. P++;
  335. *P = Source[I + 1];
  336. P++;
  337. if ((Source[I] == 13) && (Source[I + 1] == 0))
  338. {
  339. // Convert #13 to #13#10
  340. *P = 10;
  341. P++;
  342. *P = 0;
  343. P++;
  344. // Skip #10 if preceeded by #13
  345. if ((I < (Len - 3)) &&
  346. (Source[I + 2] == 10) && (Source[I + 3] == 0))
  347. {
  348. I += 2;
  349. }
  350. }
  351. }
  352. I += 2;
  353. }
  354. if (I == Len - 1)
  355. {
  356. *P = Source[I];
  357. P++;
  358. }
  359. return (P - Dest);
  360. }
  361. //---------------------------------------------------------------------------
  362. struct TStreamLoadInfo
  363. {
  364. TRichEditStreamInfo * StreamInfo;
  365. TEditorRichEdit * RichEdit;
  366. };
  367. //---------------------------------------------------------------------------
  368. // VCLCOPY Vcl.ComCtrls.pas,
  369. // WORKAROUND for bug in BCB XE2-XE6 VCL
  370. // Fixes conversion from UTF-8, when read buffer ends in the middle of UTF-8 char
  371. static unsigned long __stdcall StreamLoad(DWORD_PTR Cookie, unsigned char * Buff, long Read, long * WasRead)
  372. {
  373. TStreamLoadInfo * LoadInfo = reinterpret_cast<TStreamLoadInfo *>(Cookie);
  374. unsigned long Result =
  375. LoadInfo->RichEdit->StreamLoad(LoadInfo->StreamInfo, Buff, Read, *WasRead) ? 0 : 1;
  376. return Result;
  377. }
  378. //---------------------------------------------------------------------------
  379. void __fastcall TEditorRichEdit::EMStreamIn(TMessage & Message)
  380. {
  381. TEditStream * EditStream = reinterpret_cast<TEditStream *>(Message.LParam);
  382. EditStream->pfnCallback = &::StreamLoad;
  383. TStreamLoadInfo LoadInfo;
  384. LoadInfo.StreamInfo = reinterpret_cast<TRichEditStreamInfo *>(EditStream->dwCookie);
  385. LoadInfo.RichEdit = this;
  386. EditStream->dwCookie = reinterpret_cast<DWORD_PTR>(&LoadInfo);
  387. TRichEdit::Dispatch(&Message);
  388. }
  389. //---------------------------------------------------------------------------
  390. void TEditorRichEdit::WMMouseWheel(TMessage & Message)
  391. {
  392. unsigned int ScrollLines = 0;
  393. if (WinConfiguration->Editor.DisableSmoothScroll &&
  394. SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &ScrollLines, 0) &&
  395. (ScrollLines != 0))
  396. {
  397. int Delta = GET_WHEEL_DELTA_WPARAM(Message.WParam);
  398. bool Up = (Delta > 0);
  399. if (ScrollLines == WHEEL_PAGESCROLL)
  400. {
  401. SendMessage(Handle, WM_VSCROLL, Up ? SB_PAGEUP : SB_PAGEDOWN, 0);
  402. }
  403. else
  404. {
  405. int LinesToScroll = (abs(Delta) / WHEEL_DELTA) * ScrollLines;
  406. for (int Index = 0; Index < LinesToScroll; Index++)
  407. {
  408. SendMessage(Handle, WM_VSCROLL, Up ? SB_LINEUP : SB_LINEDOWN, 0);
  409. }
  410. }
  411. }
  412. else
  413. {
  414. TRichEdit::Dispatch(&Message);
  415. }
  416. }
  417. //---------------------------------------------------------------------------
  418. void TEditorRichEdit::WMMouseActivate(TWMMouseActivate & Message)
  419. {
  420. // https://stackoverflow.com/q/20180213/850848
  421. if ((Message.MouseMsg == WM_LBUTTONDOWN) && (GetFocus() != Handle))
  422. {
  423. SetFocus();
  424. }
  425. TRichEdit::Dispatch(&Message);
  426. }
  427. //---------------------------------------------------------------------------
  428. void __fastcall TEditorRichEdit::Dispatch(void * Message)
  429. {
  430. TMessage * M = static_cast<TMessage *>(Message);
  431. switch (M->Msg)
  432. {
  433. case WM_PASTE:
  434. WMPaste();
  435. break;
  436. case EM_STREAMIN:
  437. EMStreamIn(*M);
  438. break;
  439. case WM_MOUSEWHEEL:
  440. WMMouseWheel(*M);
  441. break;
  442. case WM_MOUSEACTIVATE:
  443. WMMouseActivate(*reinterpret_cast<TWMMouseActivate *>(M));
  444. break;
  445. default:
  446. TRichEdit::Dispatch(Message);
  447. break;
  448. }
  449. }
  450. //---------------------------------------------------------------------------
  451. bool __fastcall TEditorRichEdit::GetCanRedo()
  452. {
  453. return (SendMessage(Handle, EM_CANREDO, 0, 0) != 0);
  454. }
  455. //---------------------------------------------------------------------------
  456. void __fastcall TEditorRichEdit::SetTabSize(unsigned int TabSize)
  457. {
  458. DebugAssert(TabSize > 0);
  459. HDC DC = GetDC(Handle);
  460. SaveDC(DC);
  461. SetMapMode(DC, MM_TEXT);
  462. SelectObject(DC, Font->Handle);
  463. int LogPixelsX = GetDeviceCaps(DC, LOGPIXELSX);
  464. SIZE Size;
  465. GetTextExtentPoint(DC, UnicodeString::StringOfChar(L'X', TabSize).c_str(),
  466. TabSize, &Size);
  467. RestoreDC(DC, -1);
  468. ReleaseDC(Handle, DC);
  469. unsigned int TabTwips = MulDiv(Size.cx, 1440, LogPixelsX);
  470. // save selection
  471. CHARRANGE CharRange;
  472. SendMessage(Handle, EM_EXGETSEL, 0, (LPARAM)&CharRange);
  473. CHARRANGE CharRangeAll;
  474. CharRangeAll.cpMin = 0;
  475. CharRangeAll.cpMax = -1;
  476. SendMessage(Handle, EM_EXSETSEL, 0, (LPARAM)&CharRangeAll);
  477. PARAFORMAT2 ParaFormat;
  478. ParaFormat.cbSize = sizeof(ParaFormat);
  479. ParaFormat.dwMask = PFM_TABSTOPS;
  480. ParaFormat.cTabCount = MAX_TAB_STOPS;
  481. for (int i = 0; i < ParaFormat.cTabCount; i++)
  482. {
  483. ParaFormat.rgxTabs[i] = (i + 1) * TabTwips;
  484. }
  485. SendMessage(Handle, EM_SETPARAFORMAT, 0, (LPARAM)&ParaFormat);
  486. // restore selection
  487. SendMessage(Handle, EM_EXSETSEL, 0, (LPARAM)&CharRange);
  488. }
  489. //---------------------------------------------------------------------------
  490. bool __stdcall TEditorRichEdit::StreamLoad(
  491. TRichEditStreamInfo * StreamInfo, unsigned char * Buff, long Read, long & WasRead)
  492. {
  493. WasRead = 0;
  494. // VCLCOPY StreamLoad
  495. bool Result;
  496. try
  497. {
  498. if (StreamInfo->Converter != NULL)
  499. {
  500. TBytes Buffer;
  501. Buffer.Length = Read + 1;
  502. Read = Read / 2;
  503. if ((Read % 2) > 0)
  504. {
  505. Read--;
  506. }
  507. WasRead = StreamInfo->Converter->ConvertReadStream(StreamInfo->Stream, Buffer, Read);
  508. if (WasRead > 0)
  509. {
  510. Buffer[WasRead] = 0;
  511. if (Buffer[WasRead - 1] == 13)
  512. {
  513. Buffer[WasRead - 1] = 0;
  514. WasRead--;
  515. }
  516. int StartIndex = 0;
  517. // Convert from desired Encoding to Unicode
  518. if (StreamInfo->PlainText)
  519. {
  520. if (StreamInfo->Encoding == NULL)
  521. {
  522. Buffer = TEncoding::Convert(TEncoding::Default, TEncoding::Unicode, Buffer, 0, WasRead);
  523. WasRead = Buffer.Length;
  524. }
  525. else
  526. {
  527. if (!TEncoding::Unicode->Equals(StreamInfo->Encoding))
  528. {
  529. int MaxTries = StreamInfo->Encoding->GetMaxByteCount(1);
  530. while ((WasRead > 0) &&
  531. (StreamInfo->Encoding->GetCharCount(Buffer, 0, WasRead) == 0))
  532. {
  533. WasRead--;
  534. StreamInfo->Stream->Seek(-1, soFromCurrent);
  535. MaxTries--;
  536. if ((MaxTries == 0) || (WasRead == 0))
  537. {
  538. FStreamLoadEncodingError = true;
  539. Abort();
  540. }
  541. }
  542. Buffer = TEncoding::Convert(StreamInfo->Encoding, TEncoding::Unicode, Buffer, 0, WasRead);
  543. WasRead = Buffer.Length;
  544. }
  545. // If Unicode preamble is present, set StartIndex to skip over it
  546. TBytes Preamble = TEncoding::Unicode->GetPreamble();
  547. if (DebugAlwaysTrue(Preamble.Length == 2) &&
  548. (WasRead >= 2) && (Buffer[0] == Preamble[0]) && (Buffer[1] == Preamble[1]))
  549. {
  550. StartIndex = 2;
  551. // beware that this is also called from CreateWnd with some
  552. // dummy contents that always have BOM, so FLoadedWithPreamble
  553. // is true, unless overriden by LoadFromStream
  554. FLoadedWithPreamble = true;
  555. }
  556. }
  557. }
  558. WasRead = AdjustLineBreaks(Buff, Buffer, StartIndex, WasRead);
  559. }
  560. }
  561. Result = true;
  562. }
  563. catch (EEncodingError & E)
  564. {
  565. FStreamLoadError = true;
  566. FStreamLoadEncodingError = true;
  567. Result = false;
  568. }
  569. catch (Exception & E)
  570. {
  571. FStreamLoadError = true;
  572. Result = false;
  573. }
  574. return Result;
  575. }
  576. //---------------------------------------------------------------------------
  577. bool __fastcall TEditorRichEdit::LoadFromStream(TStream * Stream, TEncoding * Encoding, bool & EncodingError)
  578. {
  579. FStreamLoadEncodingError = false;
  580. FStreamLoadError = false;
  581. FLoadedWithPreamble = false;
  582. Lines->LoadFromStream(Stream, Encoding);
  583. if (FStreamLoadError)
  584. {
  585. EncodingError = FStreamLoadEncodingError;
  586. }
  587. return !FStreamLoadError;
  588. }
  589. //---------------------------------------------------------------------------
  590. void __fastcall TEditorRichEdit::KeyDown(Word & Key, TShiftState Shift)
  591. {
  592. if ((// Block Center/Left/Justify alignment (Right alignment is overriden by the Reload command)
  593. (Key == L'E') || (Key == L'L') || (Key == L'J') ||
  594. // Line spacing
  595. (Key == L'1') || (Key == L'2') || (Key == L'5')
  596. ) &&
  597. Shift.Contains(ssCtrl) && !Shift.Contains(ssAlt) && !Shift.Contains(ssShift))
  598. {
  599. Key = 0;
  600. }
  601. // Fiddle bullet style
  602. if ((Key == L'L') && Shift.Contains(ssCtrl) && Shift.Contains(ssShift) && !Shift.Contains(ssAlt))
  603. {
  604. Key = 0;
  605. }
  606. // Superscript/Subscript (depending on the ssShift => +/=)
  607. if ((Key == VK_OEM_PLUS) && Shift.Contains(ssCtrl) && !Shift.Contains(ssAlt))
  608. {
  609. Key = 0;
  610. }
  611. TRichEdit::KeyDown(Key, Shift);
  612. }
  613. //---------------------------------------------------------------------------
  614. class TFindDialogEx : public TFindDialog
  615. {
  616. public:
  617. __fastcall virtual TFindDialogEx(TComponent * AOwner) : TFindDialog(AOwner)
  618. {
  619. FHelpMsg = RegisterWindowMessage(HELPMSGSTRING);
  620. }
  621. protected:
  622. unsigned int FHelpMsg;
  623. virtual bool __fastcall MessageHook(TMessage & Msg)
  624. {
  625. bool Result = false;
  626. if (Msg.Msg == FHelpMsg)
  627. {
  628. Application->HelpKeyword(HELP_EDITOR_FIND);
  629. Result = true;
  630. }
  631. if (!Result)
  632. {
  633. Result = TFindDialog::MessageHook(Msg);
  634. }
  635. return Result;
  636. }
  637. };
  638. //---------------------------------------------------------------------------
  639. class TReplaceDialogEx : public TReplaceDialog
  640. {
  641. public:
  642. __fastcall virtual TReplaceDialogEx(TComponent * AOwner) : TReplaceDialog(AOwner)
  643. {
  644. FHelpMsg = RegisterWindowMessage(HELPMSGSTRING);
  645. }
  646. protected:
  647. unsigned int FHelpMsg;
  648. virtual bool __fastcall MessageHook(TMessage & Msg)
  649. {
  650. bool Result = false;
  651. if (Msg.Msg == FHelpMsg)
  652. {
  653. Application->HelpKeyword(HELP_EDITOR_REPLACE);
  654. Result = true;
  655. }
  656. if (!Result)
  657. {
  658. Result = TReplaceDialog::MessageHook(Msg);
  659. }
  660. return Result;
  661. }
  662. };
  663. //---------------------------------------------------------------------------
  664. unsigned int TEditorForm::FInstances = 0;
  665. //---------------------------------------------------------------------------
  666. __fastcall TEditorForm::TEditorForm(TComponent* Owner)
  667. : TForm(Owner)
  668. {
  669. FAnsiEncoding = TEncoding::Default;
  670. if (!FAnsiEncoding->IsSingleByte)
  671. {
  672. // We need the GetCharCount to fail for multibyte Ansi encoding (e.g. Japanese Shift-JIS CP592) like the
  673. // TUTF8Encoding does, see the TUTF8Encoding.Create.
  674. // We could use this for single-byte encodings too without any harm probably.
  675. // But for now, try to limit an impact of this change.
  676. // Based on TEncoding.GetANSI.
  677. FAnsiEncoding = new TMBCSEncoding(GetACP(), MB_ERR_INVALID_CHARS, 0);
  678. }
  679. EditorMemo = new TEditorRichEdit(this);
  680. EditorMemo->Parent = this;
  681. EditorMemo->Align = alClient;
  682. EditorMemo->HideSelection = false;
  683. EditorMemo->PlainText = true;
  684. EditorMemo->PopupMenu = EditorPopup;
  685. EditorMemo->ScrollBars = ssBoth;
  686. EditorMemo->WantTabs = true;
  687. EditorMemo->OnChange = EditorMemoChange;
  688. EditorMemo->OnKeyUp = EditorMemoKeyUp;
  689. EditorMemo->OnMouseUp = EditorMemoMouseUp;
  690. // By default the TEditAction's reflect state of the currently focused edit.
  691. // Even if the edit is on a different window.
  692. // This way we explicitly bind them to our editor.
  693. for (int Index = 0; Index < EditorActions->ActionCount; Index++)
  694. {
  695. TEditAction * EditAction = dynamic_cast<TEditAction *>(EditorActions->Actions[Index]);
  696. if (EditAction != NULL)
  697. {
  698. EditAction->Control = EditorMemo;
  699. }
  700. }
  701. FParentForm = NULL;
  702. FCaretPos = TPoint(-1, -1);
  703. FLastFindDialog = NULL;
  704. FCloseAnnounced = false;
  705. ApplyConfiguration();
  706. FFindDialog = new TFindDialogEx(this);
  707. FFindDialog->OnFind = FindDialogFind;
  708. FReplaceDialog = new TReplaceDialogEx(this);
  709. FReplaceDialog->OnFind = FindDialogFind;
  710. FReplaceDialog->OnReplace = FindDialogFind;
  711. FEncoding = NULL;
  712. FSaving = false;
  713. FStandaloneEditor = false;
  714. FClosePending = false;
  715. FReloading = false;
  716. FInternalEditorEncodingOverride = -1;
  717. SetSubmenu(ColorItem, true);
  718. InitCodePage();
  719. SelectScaledImageList(EditorImages);
  720. UseSystemSettings(this);
  721. UseDesktopFont(StatusBar);
  722. FixFormIcons(this);
  723. }
  724. //---------------------------------------------------------------------------
  725. __fastcall TEditorForm::~TEditorForm()
  726. {
  727. DebugAssert(FInstances > 0);
  728. FInstances--;
  729. if (FInstance == 0)
  730. {
  731. UnicodeString WindowParams = StoreForm(this);
  732. // this is particularly to prevent saving the form state
  733. // for the first time, keeping default positioning by a system
  734. if (!FWindowParams.IsEmpty() && (FWindowParams != WindowParams))
  735. {
  736. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  737. EditorConfiguration.WindowParams = StoreForm(this);
  738. WinConfiguration->Editor = EditorConfiguration;
  739. }
  740. }
  741. // see FormClose for explanation
  742. if (!FCloseAnnounced)
  743. {
  744. BackupSave();
  745. DoWindowClose(true);
  746. }
  747. if (FAnsiEncoding != TEncoding::Default)
  748. {
  749. delete FAnsiEncoding;
  750. FAnsiEncoding = NULL;
  751. }
  752. if (FStandaloneEditor)
  753. {
  754. TerminateApplication();
  755. }
  756. }
  757. //---------------------------------------------------------------------------
  758. UnicodeString __fastcall TEditorForm::GetCodePageName(TEncoding * Encoding)
  759. {
  760. if (Encoding == TEncoding::UTF8)
  761. {
  762. return LoadStr(UTF8_NAME);
  763. }
  764. else
  765. {
  766. return DefaultEncodingName();
  767. }
  768. }
  769. //---------------------------------------------------------------------------
  770. void __fastcall TEditorForm::InitCodePage()
  771. {
  772. DefaultEncodingAction->Caption = DefaultEncodingName();
  773. DefaultEncodingAction->Hint = FORMAT(DefaultEncodingAction->Hint, (DefaultEncodingName()));
  774. }
  775. //---------------------------------------------------------------------------
  776. void __fastcall TEditorForm::SetFileName(const UnicodeString value)
  777. {
  778. if (value != FFileName)
  779. {
  780. FFileName = value;
  781. if (Visible)
  782. {
  783. LoadFile();
  784. }
  785. }
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TEditorForm::EditorActionsUpdate(TBasicAction *Action,
  789. bool &Handled)
  790. {
  791. Handled = true;
  792. if (Action == SaveAction)
  793. {
  794. SaveAction->Enabled = IsFileModified();
  795. }
  796. else if (Action == SaveAllAction2)
  797. {
  798. bool Enabled = !EditorMemo->ReadOnly && !FStandaloneEditor;
  799. if (Enabled)
  800. {
  801. Enabled = IsFileModified();
  802. // optimization
  803. if (!Enabled)
  804. {
  805. FOnAnyModified(this, Enabled);
  806. }
  807. }
  808. SaveAllAction2->Enabled = Enabled;
  809. }
  810. else if (Action == ReplaceAction)
  811. {
  812. ReplaceAction->Enabled = !EditorMemo->ReadOnly;
  813. }
  814. else if (Action == FindNextAction)
  815. {
  816. FindNextAction->Enabled =
  817. FLastFindDialog != NULL || !FFindDialog->FindText.IsEmpty();
  818. }
  819. else if (Action == EditRedo)
  820. {
  821. EditRedo->Enabled = EditorMemo->CanRedo;
  822. }
  823. else if (Action == PreferencesAction ||
  824. Action == FindAction || Action == ReplaceAction || Action == GoToLineAction ||
  825. Action == HelpAction || Action == ColorAction)
  826. {
  827. ((TAction *)Action)->Enabled = true;
  828. }
  829. else if (Action == ReloadAction)
  830. {
  831. ReloadAction->Enabled = !FReloading && !NewFile;
  832. }
  833. else if (Action == DefaultEncodingAction)
  834. {
  835. DefaultEncodingAction->Enabled = true;
  836. DefaultEncodingAction->Checked = (FEncoding == FAnsiEncoding);
  837. }
  838. else if (Action == UTF8EncodingAction)
  839. {
  840. UTF8EncodingAction->Enabled = true;
  841. UTF8EncodingAction->Checked = (FEncoding == TEncoding::UTF8);
  842. }
  843. else
  844. {
  845. Handled = false;
  846. }
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TEditorForm::SaveToFile()
  850. {
  851. std::unique_ptr<TStream> Stream(
  852. new TPreambleFilteringFileStream(
  853. ApiPath(FFileName), fmCreate, FEncoding, EditorMemo->LoadedWithPreamble));
  854. EditorMemo->Lines->SaveToStream(Stream.get(), FEncoding);
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TEditorForm::SaveFile()
  858. {
  859. // Test is needed for "Save all" and is redundant for "Save"
  860. if (IsFileModified())
  861. {
  862. DebugAssert(!FFileName.IsEmpty());
  863. FSaving = true;
  864. UpdateControls(); // It does not redraw the status bar anyway
  865. bool Direct = (FOnFileChanged == NULL);
  866. try
  867. {
  868. SaveToFile();
  869. if (!Direct)
  870. {
  871. FOnFileChanged(this);
  872. }
  873. EditorMemo->Modified = false;
  874. NewFile = false;
  875. }
  876. __finally
  877. {
  878. if (Direct)
  879. {
  880. FSaving = false;
  881. }
  882. UpdateControls();
  883. }
  884. }
  885. }
  886. //---------------------------------------------------------------------------
  887. bool __fastcall TEditorForm::IsFileModified()
  888. {
  889. return EditorMemo->Modified;
  890. }
  891. //---------------------------------------------------------------------------
  892. void __fastcall TEditorForm::EditorActionsExecute(TBasicAction *Action,
  893. bool &Handled)
  894. {
  895. Handled = true;
  896. if (Action == SaveAction)
  897. {
  898. SaveFile();
  899. }
  900. else if (Action == SaveAllAction2)
  901. {
  902. OnSaveAll(this);
  903. }
  904. else if (Action == PreferencesAction)
  905. {
  906. DoPreferencesDialog(pmEditorInternal);
  907. }
  908. else if (Action == ReloadAction)
  909. {
  910. Reload();
  911. }
  912. else if (Action == FindAction || Action == ReplaceAction)
  913. {
  914. StartFind(Action == FindAction);
  915. }
  916. else if (Action == FindNextAction)
  917. {
  918. if (!FLastFindDialog)
  919. {
  920. FLastFindDialog = FFindDialog;
  921. }
  922. Find();
  923. }
  924. else if (Action == GoToLineAction)
  925. {
  926. GoToLine();
  927. }
  928. else if (Action == EditRedo)
  929. {
  930. EditorMemo->Redo();
  931. }
  932. else if (Action == HelpAction)
  933. {
  934. FormHelp(this);
  935. }
  936. else if (Action == DefaultEncodingAction)
  937. {
  938. ChangeEncoding(FAnsiEncoding);
  939. }
  940. else if (Action == UTF8EncodingAction)
  941. {
  942. ChangeEncoding(TEncoding::UTF8);
  943. }
  944. else if (Action == ColorAction)
  945. {
  946. if (DebugAlwaysTrue(Action->ActionComponent != NULL))
  947. {
  948. CreateEditorBackgroundColorMenu(Action->ActionComponent, BackgroundColor,
  949. SetBackgroundColor);
  950. }
  951. }
  952. else
  953. {
  954. Handled = false;
  955. }
  956. }
  957. //---------------------------------------------------------------------------
  958. void __fastcall TEditorForm::BackupSave()
  959. {
  960. if (IsFileModified())
  961. {
  962. int Uniq = 0;
  963. while (true)
  964. {
  965. UnicodeString FileName = FFileName + L".bak" + (Uniq == 0 ? UnicodeString() : IntToStr(Uniq));
  966. UnicodeString ApiFileName = ApiPath(FileName);
  967. if (!FileExists(ApiFileName))
  968. {
  969. EditorMemo->Lines->SaveToFile(ApiFileName, FEncoding);
  970. break;
  971. }
  972. Uniq++;
  973. }
  974. }
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall TEditorForm::ChangeEncoding(TEncoding * Encoding)
  978. {
  979. if (FEncoding != Encoding)
  980. {
  981. if (!IsFileModified() ||
  982. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_ENCODING)), qtConfirmation,
  983. qaOK | qaCancel) != qaCancel))
  984. {
  985. TEncoding * PrevEncoding = FEncoding;
  986. try
  987. {
  988. FEncoding = Encoding;
  989. LoadFile();
  990. }
  991. catch(...)
  992. {
  993. // try to restore
  994. FEncoding = PrevEncoding;
  995. LoadFile();
  996. throw;
  997. }
  998. }
  999. }
  1000. }
  1001. //---------------------------------------------------------------------------
  1002. void __fastcall TEditorForm::FormCloseQuery(TObject * /*Sender*/,
  1003. bool &CanClose)
  1004. {
  1005. if (IsFileModified())
  1006. {
  1007. SetFocus();
  1008. UnicodeString Message = MainInstructions(LoadStr(SAVE_CHANGES));
  1009. unsigned int Answer = MessageDialog(Message, qtConfirmation,
  1010. qaYes | qaNo | qaCancel);
  1011. CanClose = (Answer != qaCancel);
  1012. if (Answer == qaYes)
  1013. {
  1014. SaveAction->Execute();
  1015. if (FStandaloneEditor)
  1016. {
  1017. CanClose = false;
  1018. FClosePending = true;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. void __fastcall TEditorForm::ApplyConfiguration()
  1025. {
  1026. Color = GetBtnFaceColor();
  1027. bool PrevModified = IsFileModified();
  1028. DebugAssert(Configuration);
  1029. EditorMemo->SetFormat(WinConfiguration->Editor.Font,
  1030. WinConfiguration->Editor.FontColor,
  1031. WinConfiguration->Editor.TabSize,
  1032. WinConfiguration->Editor.WordWrap);
  1033. UpdateBackgroundColor();
  1034. EditorMemo->Modified = PrevModified;
  1035. EditorMemo->ClearUndo();
  1036. Enabled = !WinConfiguration->LockedInterface;
  1037. UpdateControls();
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. void __fastcall TEditorForm::FileUploadComplete()
  1041. {
  1042. DebugAssert(FSaving);
  1043. FSaving = false;
  1044. UpdateControls();
  1045. if (FClosePending && DebugAlwaysTrue(FStandaloneEditor))
  1046. {
  1047. Close();
  1048. }
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TEditorForm::UpdateControls()
  1052. {
  1053. // To disable saving, e.g. in encryption mode (no queue support) - both OnFileChanged and OnSaveAll are NULL.
  1054. // But internal editors have (OnFileChanged == NULL), but OnSaveAll set, so we use OnSaveAll for dicision
  1055. EditorMemo->ReadOnly = (OnSaveAll == NULL);
  1056. TPoint ACaretPos = EditorMemo->CaretPos;
  1057. if (ACaretPos.x != FCaretPos.x || ACaretPos.y != FCaretPos.y)
  1058. {
  1059. FCaretPos = ACaretPos;
  1060. int Count = EditorMemo->Lines->Count;
  1061. StatusBar->Panels->Items[0]->Caption = FMTLOAD(EDITOR_LINE_STATUS,
  1062. ((int)FCaretPos.y+1, Count));
  1063. int Column = 0;
  1064. UnicodeString Character;
  1065. if (FCaretPos.y >= 0 && FCaretPos.y < EditorMemo->Lines->Count)
  1066. {
  1067. UnicodeString Line = EditorMemo->Lines->Strings[FCaretPos.y];
  1068. int TabSize = WinConfiguration->Editor.TabSize;
  1069. for (int Index = 1; Index <= FCaretPos.x + 1; Index++)
  1070. {
  1071. if ((Index - 1 >= 1) && (Index - 1 <= Line.Length()) && (Line[Index - 1] == L'\t') &&
  1072. (TabSize > 0)) // sanity check
  1073. {
  1074. Column = (((Column / TabSize) + 1) * TabSize) + 1;
  1075. }
  1076. else
  1077. {
  1078. Column++;
  1079. }
  1080. }
  1081. if (FCaretPos.x+1 <= Line.Length())
  1082. {
  1083. int Code;
  1084. wchar_t Ch = Line[FCaretPos.x + 1];
  1085. if (FEncoding == FAnsiEncoding)
  1086. {
  1087. char Buf[10];
  1088. BOOL UsedDefaultChar = FALSE;
  1089. int Conversion =
  1090. WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, &Ch, 1,
  1091. Buf, sizeof(Buf), NULL, &UsedDefaultChar);
  1092. // actually with multibyte encoding it may be > 1,
  1093. if ((Conversion == 1) && !UsedDefaultChar)
  1094. {
  1095. Code = static_cast<int>(static_cast<unsigned char>(Buf[0]));
  1096. }
  1097. else
  1098. {
  1099. Code = -1;
  1100. }
  1101. }
  1102. else
  1103. {
  1104. Code = static_cast<int>(Ch);
  1105. }
  1106. if (Code >= 0)
  1107. {
  1108. Character = FMTLOAD(EDITOR_CHARACTER_STATUS2, (Code, Code));
  1109. }
  1110. }
  1111. }
  1112. StatusBar->Panels->Items[1]->Caption =
  1113. (Column > 0) ? FMTLOAD(EDITOR_COLUMN_STATUS, (Column)) : UnicodeString();
  1114. StatusBar->Panels->Items[2]->Caption = Character;
  1115. }
  1116. StatusBar->Panels->Items[3]->Caption = FMTLOAD(EDITOR_ENCODING_STATUS, (FEncodingName));
  1117. UnicodeString Status;
  1118. if (EditorMemo->ReadOnly)
  1119. {
  1120. Status = LoadStr(EDITOR_READONLY);
  1121. }
  1122. else if (FSaving)
  1123. {
  1124. Status = LoadStr(EDITOR_SAVING);
  1125. }
  1126. else if (NewFile)
  1127. {
  1128. Status = LoadStr(EDITOR_NEW);
  1129. }
  1130. else if (IsFileModified())
  1131. {
  1132. Status = LoadStr(EDITOR_MODIFIED);
  1133. }
  1134. StatusBar->Panels->Items[4]->Caption = Status;
  1135. EditorActions->UpdateAction(SaveAction);
  1136. Encoding->Enabled = !NewFile;
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. void __fastcall TEditorForm::EditorMemoMouseUp(TObject * /*Sender*/,
  1140. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  1141. {
  1142. UpdateControls();
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TEditorForm::EditorMemoKeyUp(TObject * /*Sender*/,
  1146. WORD & /*Key*/, TShiftState /*Shift*/)
  1147. {
  1148. UpdateControls();
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. void __fastcall TEditorForm::EditorMemoChange(TObject * /*Sender*/)
  1152. {
  1153. UpdateControls();
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TEditorForm::FindDialogFind(TObject * /*Sender*/)
  1157. {
  1158. Find();
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. void __fastcall TEditorForm::Find()
  1162. {
  1163. int NewPos;
  1164. int Replacements = 0;
  1165. do
  1166. {
  1167. DebugAssert(FLastFindDialog);
  1168. TSearchTypes SearchTypes;
  1169. // length condition is there to improve performance when large
  1170. // block is selected in editor
  1171. if (FLastFindDialog == FReplaceDialog &&
  1172. (FReplaceDialog->Options.Contains(frReplace) ||
  1173. FReplaceDialog->Options.Contains(frReplaceAll)) &&
  1174. FReplaceDialog->FindText.Length() == EditorMemo->SelLength &&
  1175. AnsiSameText(FReplaceDialog->FindText, EditorMemo->SelText))
  1176. {
  1177. EditorMemo->SelText = FReplaceDialog->ReplaceText;
  1178. Replacements++;
  1179. }
  1180. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1181. EditorConfiguration.FindText = FLastFindDialog->FindText;
  1182. EditorConfiguration.ReplaceText = FReplaceDialog->ReplaceText;
  1183. EditorConfiguration.FindMatchCase = FLastFindDialog->Options.Contains(frMatchCase);
  1184. EditorConfiguration.FindWholeWord = FLastFindDialog->Options.Contains(frWholeWord);
  1185. EditorConfiguration.FindDown = FLastFindDialog->Options.Contains(frDown);
  1186. WinConfiguration->Editor = EditorConfiguration;
  1187. if (EditorConfiguration.FindMatchCase)
  1188. {
  1189. SearchTypes << stMatchCase;
  1190. }
  1191. if (EditorConfiguration.FindWholeWord)
  1192. {
  1193. SearchTypes << stWholeWord;
  1194. }
  1195. NewPos = EditorMemo->FindText(EditorConfiguration.FindText,
  1196. EditorMemo->SelLength ? EditorMemo->SelStart+1 : EditorMemo->SelStart,
  1197. EditorMemo->Text.Length(), SearchTypes, EditorConfiguration.FindDown);
  1198. if (NewPos >= 0)
  1199. {
  1200. EditorMemo->SelStart = NewPos;
  1201. EditorMemo->SelLength = EditorConfiguration.FindText.Length();
  1202. }
  1203. if (FLastFindDialog->Handle)
  1204. {
  1205. PositionFindDialog(true);
  1206. }
  1207. if (NewPos < 0)
  1208. {
  1209. if ((Replacements == 0) || FReplaceDialog->Options.Contains(frReplaceAll))
  1210. {
  1211. // now Screen->ActiveForm can be NULL when other form was meanwhile
  1212. // activated and then focus was returned back to "find" dialog
  1213. // (non VCL form)
  1214. if (Screen->ActiveForm != this)
  1215. {
  1216. SetFocus();
  1217. FLastFindDialog->Execute();
  1218. }
  1219. if (Replacements == 0)
  1220. {
  1221. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_FIND_END, (EditorConfiguration.FindText)));
  1222. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1223. }
  1224. else if (FReplaceDialog->Options.Contains(frReplaceAll))
  1225. {
  1226. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_REPLACE_END, (Replacements)));
  1227. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1228. }
  1229. }
  1230. }
  1231. }
  1232. while (NewPos >= 0 && FLastFindDialog == FReplaceDialog &&
  1233. FReplaceDialog->Options.Contains(frReplaceAll));
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. void __fastcall TEditorForm::FormShow(TObject * /*Sender*/)
  1237. {
  1238. if (DebugAlwaysTrue(FParentForm != NULL))
  1239. {
  1240. // Forms should be at the same monitor
  1241. DebugAssert(PixelsPerInch == FParentForm->PixelsPerInch);
  1242. Width = MulDiv(FParentForm->BoundsRect.Width(), PixelsPerInch, FParentForm->PixelsPerInch);
  1243. Height = MulDiv(FParentForm->BoundsRect.Height(), PixelsPerInch, FParentForm->PixelsPerInch);
  1244. }
  1245. CutFormToDesktop(this);
  1246. DebugAssert(FWindowParams.IsEmpty());
  1247. if (FWindowParams.IsEmpty())
  1248. {
  1249. FWindowParams = StoreForm(this);
  1250. }
  1251. }
  1252. //---------------------------------------------------------------------------
  1253. // VCLCOPY ComCtrls.pas
  1254. bool __fastcall TEditorForm::ContainsPreamble(TStream * Stream, const TBytes & Signature)
  1255. {
  1256. bool Result;
  1257. TBytes Buffer;
  1258. int LBufLen;
  1259. int LSignatureLen = Signature.Length;
  1260. __int64 LPosition = Stream->Position;
  1261. try
  1262. {
  1263. Buffer.Length = LSignatureLen;
  1264. LBufLen = Stream->Read(&Buffer[0], LSignatureLen);
  1265. }
  1266. __finally
  1267. {
  1268. Stream->Position = LPosition;
  1269. }
  1270. if (LBufLen == LSignatureLen)
  1271. {
  1272. Result = true;
  1273. for (int I = 1; I <= LSignatureLen; I++)
  1274. {
  1275. if (Buffer[I - 1] != Signature[I - 1])
  1276. {
  1277. Result = false;
  1278. break;
  1279. }
  1280. }
  1281. }
  1282. else
  1283. {
  1284. Result = false;
  1285. }
  1286. return Result;
  1287. }
  1288. //---------------------------------------------------------------------------
  1289. void __fastcall TEditorForm::LoadFromFile(bool PrimaryEncoding)
  1290. {
  1291. TStream * Stream = new TFileStream(ApiPath(FFileName), fmOpenRead | fmShareDenyWrite);
  1292. try
  1293. {
  1294. bool CanTrySecondary;
  1295. if (FEncoding == NULL)
  1296. {
  1297. int Encoding;
  1298. if (ContainsPreamble(Stream, TEncoding::UTF8->GetPreamble()))
  1299. {
  1300. Encoding = CP_UTF8;
  1301. CanTrySecondary = false;
  1302. }
  1303. else
  1304. {
  1305. if (InternalEditorEncodingOverride >= 0)
  1306. {
  1307. Encoding = InternalEditorEncodingOverride;
  1308. }
  1309. else
  1310. {
  1311. Encoding = WinConfiguration->Editor.Encoding;
  1312. }
  1313. CanTrySecondary = true;
  1314. }
  1315. switch (Encoding)
  1316. {
  1317. case CP_UTF8:
  1318. FEncoding = PrimaryEncoding ? TEncoding::UTF8 : FAnsiEncoding;
  1319. break;
  1320. default:
  1321. CanTrySecondary = false;
  1322. DebugFail();
  1323. // fallthru
  1324. case CP_ACP:
  1325. FEncoding = PrimaryEncoding ? FAnsiEncoding : TEncoding::UTF8;
  1326. break;
  1327. }
  1328. }
  1329. else
  1330. {
  1331. CanTrySecondary = false;
  1332. }
  1333. FEncodingName = GetCodePageName(FEncoding);
  1334. bool EncodingError;
  1335. if (!EditorMemo->LoadFromStream(Stream, FEncoding, EncodingError))
  1336. {
  1337. if (EncodingError)
  1338. {
  1339. UnicodeString Message = FMTLOAD(EDITOR_ENCODING_ERROR, (FFileName, FEncodingName));
  1340. if (PrimaryEncoding && CanTrySecondary)
  1341. {
  1342. TEncoding * EncodingBackup = FEncoding;
  1343. UnicodeString EncodingNameBackup = FEncodingName;
  1344. try
  1345. {
  1346. FEncoding = NULL;
  1347. LoadFromFile(false);
  1348. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1349. if (EditorConfiguration.WarnOnEncodingFallback)
  1350. {
  1351. // by now the FEncodingName is the secondary encoding
  1352. Message = Message + L" " + FMTLOAD(EDITOR_ENCODING_REVERTED, (FEncodingName));
  1353. TMessageParams Params(mpNeverAskAgainCheck);
  1354. unsigned int Answer =
  1355. MessageDialog(MainInstructions(Message), qtInformation, qaOK, HELP_NONE, &Params);
  1356. if (Answer == qaNeverAskAgain)
  1357. {
  1358. EditorConfiguration.WarnOnEncodingFallback = false;
  1359. WinConfiguration->Editor = EditorConfiguration;
  1360. }
  1361. }
  1362. }
  1363. catch(...)
  1364. {
  1365. // restored values are never used anyway, as this can get here only
  1366. // when opening editor and this is fatal error preventing the editor from opening
  1367. FEncoding = EncodingBackup;
  1368. FEncodingName = EncodingNameBackup;
  1369. throw Exception(Message);
  1370. }
  1371. }
  1372. else
  1373. {
  1374. throw Exception(Message);
  1375. }
  1376. }
  1377. else
  1378. {
  1379. throw Exception(MainInstructions(FMTLOAD(EDITOR_LOAD_ERROR, (FFileName))));
  1380. }
  1381. }
  1382. }
  1383. __finally
  1384. {
  1385. delete Stream;
  1386. }
  1387. SendMessage(EditorMemo->Handle, EM_EXLIMITTEXT, 0, 0x7FFFFFF0);
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. void __fastcall TEditorForm::CheckFileSize()
  1391. {
  1392. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1393. TWin32FileAttributeData FileAttributeData;
  1394. if (GetFileAttributesEx(ApiPath(FFileName).c_str(), GetFileExInfoStandard, &FileAttributeData))
  1395. {
  1396. const __int64 MaxSize = 100 * 1024 * 1024;
  1397. __int64 Size =
  1398. (static_cast<__int64>(FileAttributeData.nFileSizeHigh) << 32) +
  1399. FileAttributeData.nFileSizeLow;
  1400. if (Size > MaxSize)
  1401. {
  1402. if (EditorConfiguration.WarnOrLargeFileSize)
  1403. {
  1404. TMessageParams Params(mpNeverAskAgainCheck);
  1405. unsigned int Answer =
  1406. MoreMessageDialog(
  1407. FMTLOAD(INTERNAL_EDITOR_LARGE_FILE2, (FormatBytes(Size))), NULL,
  1408. qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  1409. switch (Answer)
  1410. {
  1411. case qaOK:
  1412. // noop;
  1413. break;
  1414. case qaCancel:
  1415. Abort();
  1416. break;
  1417. case qaNeverAskAgain:
  1418. EditorConfiguration.WarnOrLargeFileSize = false;
  1419. WinConfiguration->Editor = EditorConfiguration;
  1420. break;
  1421. default:
  1422. DebugFail();
  1423. }
  1424. }
  1425. // Those are actually nearly all internal exceptions we ever practically get
  1426. IgnoreException(typeid(EOutOfMemory));
  1427. IgnoreException(typeid(EAccessViolation));
  1428. IgnoreException(typeid(EExternalException));
  1429. }
  1430. }
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. void __fastcall TEditorForm::LoadFile()
  1434. {
  1435. CheckFileSize();
  1436. HandleNeeded();
  1437. LoadFromFile(true);
  1438. EditorMemo->ResetFormat();
  1439. EditorMemo->Modified = false;
  1440. FCaretPos.x = -1;
  1441. // this is important particularly after reload
  1442. UpdateControls();
  1443. }
  1444. //---------------------------------------------------------------------------
  1445. bool __fastcall TEditorForm::CursorInUpperPart()
  1446. {
  1447. HFONT OldFont;
  1448. HDC DC;
  1449. TTextMetric TM;
  1450. TRect Rect;
  1451. DC = GetDC(EditorMemo->Handle);
  1452. OldFont = (HFONT)SelectObject(DC, EditorMemo->Font->Handle);
  1453. try
  1454. {
  1455. GetTextMetrics(DC, &TM);
  1456. EditorMemo->Perform(EM_GETRECT, 0, ((int)&Rect));
  1457. }
  1458. __finally
  1459. {
  1460. SelectObject(DC, OldFont);
  1461. ReleaseDC(EditorMemo->Handle, DC);
  1462. }
  1463. int VisibleLines = (Rect.Bottom - Rect.Top) / (TM.tmHeight + TM.tmExternalLeading);
  1464. int FirstLine = SendMessage(EditorMemo->Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
  1465. TPoint CaretPos = EditorMemo->CaretPos;
  1466. return (CaretPos.y - FirstLine) < VisibleLines / 2;
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. void __fastcall TEditorForm::PositionFindDialog(bool VerticalOnly)
  1470. {
  1471. DebugAssert(FLastFindDialog);
  1472. if (!VerticalOnly)
  1473. {
  1474. FLastFindDialog->Left = Left + EditorMemo->Left + EditorMemo->Width / 2 - ScaleByTextHeight(this, 100);
  1475. }
  1476. FLastFindDialog->Top = Top + EditorMemo->Top + (EditorMemo->Height / 4) +
  1477. (CursorInUpperPart() ? (EditorMemo->Height / 2) : 0) - ScaleByTextHeight(this, 40);
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. void __fastcall TEditorForm::StartFind(bool Find)
  1481. {
  1482. UnicodeString Text = EditorMemo->SelText;
  1483. TFindOptions Options;
  1484. Options << frShowHelp;
  1485. if (Text.IsEmpty())
  1486. {
  1487. Text = WinConfiguration->Editor.FindText;
  1488. }
  1489. TFindDialog * Dialog = Find ? FFindDialog : FReplaceDialog;
  1490. if (FLastFindDialog && Dialog != FLastFindDialog && FLastFindDialog->Handle)
  1491. {
  1492. FLastFindDialog->CloseDialog();
  1493. }
  1494. FLastFindDialog = Dialog;
  1495. if (!Text.IsEmpty())
  1496. {
  1497. FLastFindDialog->FindText = Text;
  1498. }
  1499. FReplaceDialog->ReplaceText = WinConfiguration->Editor.ReplaceText;
  1500. if (WinConfiguration->Editor.FindMatchCase)
  1501. {
  1502. Options << frMatchCase;
  1503. }
  1504. if (WinConfiguration->Editor.FindWholeWord)
  1505. {
  1506. Options << frWholeWord;
  1507. }
  1508. if (WinConfiguration->Editor.FindDown)
  1509. {
  1510. Options << frDown;
  1511. }
  1512. FLastFindDialog->Options = Options;
  1513. if (!FLastFindDialog->Handle)
  1514. {
  1515. PositionFindDialog(false);
  1516. }
  1517. FLastFindDialog->Execute();
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. void __fastcall TEditorForm::GoToLine()
  1521. {
  1522. UnicodeString Str;
  1523. if (InputDialog(LoadStr(EDITOR_GO_TO_LINE), LoadStr(EDITOR_LINE_NUMBER), Str))
  1524. {
  1525. int Line = StrToIntDef(Str, -1);
  1526. if (Line <= 0 || Line > EditorMemo->Lines->Count)
  1527. {
  1528. throw Exception(MainInstructions(LoadStr(EDITOR_INVALID_LINE)));
  1529. }
  1530. else
  1531. {
  1532. EditorMemo->CaretPos = TPoint(0, Line-1);
  1533. }
  1534. }
  1535. }
  1536. //---------------------------------------------------------------------------
  1537. void __fastcall TEditorForm::FormClose(TObject * /*Sender*/,
  1538. TCloseAction & Action)
  1539. {
  1540. // Preferably announce closure here as this is called from within TForm::Close(),
  1541. // so the annoucement will be synchronous (and editor manager thus
  1542. // will consider the form to be really closed and will not block
  1543. // application closure).
  1544. // However FormClose is not called when form is closed due to
  1545. // application exit, so there is last resort call from destructor.
  1546. DoWindowClose(false);
  1547. FCloseAnnounced = true;
  1548. Action = caFree;
  1549. }
  1550. //---------------------------------------------------------------------------
  1551. void __fastcall TEditorForm::DoWindowClose(bool Forced)
  1552. {
  1553. if (FOnWindowClose != NULL)
  1554. {
  1555. try
  1556. {
  1557. FOnWindowClose(this, Forced);
  1558. }
  1559. catch(Exception & E)
  1560. {
  1561. ShowExtendedException(&E);
  1562. }
  1563. }
  1564. }
  1565. //---------------------------------------------------------------------------
  1566. void __fastcall TEditorForm::CreateParams(TCreateParams & Params)
  1567. {
  1568. // this is called for the first time from parent's constructor.
  1569. // FFormRestored is set to false implicitly
  1570. if (!FFormRestored)
  1571. {
  1572. FInstance = FInstances;
  1573. FInstances++;
  1574. FFormRestored = true;
  1575. UnicodeString WindowParams = WinConfiguration->Editor.WindowParams;
  1576. if ((FInstance == 0) && !WindowParams.IsEmpty())
  1577. {
  1578. RestoreForm(WindowParams, this);
  1579. }
  1580. }
  1581. TForm::CreateParams(Params);
  1582. Params.WndParent = GetDesktopWindow();
  1583. }
  1584. //---------------------------------------------------------------------------
  1585. void __fastcall TEditorForm::Reload()
  1586. {
  1587. TAutoFlag ReloadingFlag(FReloading);
  1588. if (!IsFileModified() ||
  1589. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_RELOAD)), qtConfirmation,
  1590. qaOK | qaCancel) != qaCancel))
  1591. {
  1592. if (FOnFileReload)
  1593. {
  1594. FOnFileReload(this);
  1595. }
  1596. LoadFile();
  1597. }
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. void __fastcall TEditorForm::FormKeyDown(TObject * /*Sender*/, WORD & Key, TShiftState Shift)
  1601. {
  1602. if (((Key == VK_ESCAPE) || (Key == VK_F10)) && Shift.Empty())
  1603. {
  1604. Key = 0;
  1605. Close();
  1606. }
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall TEditorForm::SetBackgroundColor(TColor Color)
  1610. {
  1611. if (BackgroundColor != Color)
  1612. {
  1613. FBackgroundColor = Color;
  1614. UpdateBackgroundColor();
  1615. }
  1616. }
  1617. //---------------------------------------------------------------------------
  1618. void __fastcall TEditorForm::UpdateBackgroundColor()
  1619. {
  1620. TColor Color = FBackgroundColor;
  1621. if (Color == 0)
  1622. {
  1623. // double default, first our preferred default, then system default
  1624. Color = GetWindowColor(WinConfiguration->Editor.BackgroundColor);
  1625. }
  1626. ColorItem->Color = Color;
  1627. if (EditorMemo->Color != Color)
  1628. {
  1629. EditorMemo->Color = Color;
  1630. EditorMemo->ApplyFont();
  1631. // does not seem to have any effect (nor is needed), but just in case
  1632. ForceColorChange(EditorMemo);
  1633. }
  1634. }
  1635. //---------------------------------------------------------------------------