Editor.cpp 51 KB

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