Editor.cpp 49 KB

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