Editor.cpp 49 KB

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