Editor.cpp 49 KB

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