Editor.cpp 51 KB

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