Editor.cpp 51 KB

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