Editor.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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. #ifndef NO_RESOURCES
  24. #pragma resource "*.dfm"
  25. #endif
  26. //---------------------------------------------------------------------------
  27. TForm * __fastcall ShowEditorForm(const UnicodeString FileName, TForm * ParentForm,
  28. TNotifyEvent OnFileChanged, TNotifyEvent OnFileReload, TFileClosedEvent OnClose,
  29. TNotifyEvent OnSaveAll, TAnyModifiedEvent OnAnyModified,
  30. const UnicodeString Caption, bool StandaloneEditor, TColor Color, int InternalEditorEncodingOverride)
  31. {
  32. TEditorForm * Dialog = new TEditorForm(Application);
  33. try
  34. {
  35. Dialog->FileName = FileName;
  36. Dialog->ParentForm = ParentForm;
  37. UnicodeString ACaption = Caption.IsEmpty() ? FileName : Caption;
  38. Dialog->Caption = ACaption + L" - " + LoadStr(EDITOR_CAPTION) + L" - " + AppName;
  39. Dialog->OnFileChanged = OnFileChanged;
  40. Dialog->OnFileReload = OnFileReload;
  41. Dialog->OnSaveAll = OnSaveAll;
  42. Dialog->OnAnyModified = OnAnyModified;
  43. Dialog->StandaloneEditor = StandaloneEditor;
  44. Dialog->BackgroundColor = Color;
  45. Dialog->InternalEditorEncodingOverride = InternalEditorEncodingOverride;
  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(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;
  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. UpdateControls();
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. bool __fastcall TEditorForm::IsFileModified()
  794. {
  795. return EditorMemo->Modified;
  796. }
  797. //---------------------------------------------------------------------------
  798. void __fastcall TEditorForm::EditorActionsExecute(TBasicAction *Action,
  799. bool &Handled)
  800. {
  801. Handled = true;
  802. if (Action == SaveAction)
  803. {
  804. SaveFile();
  805. }
  806. else if (Action == SaveAllAction2)
  807. {
  808. OnSaveAll(this);
  809. }
  810. else if (Action == PreferencesAction)
  811. {
  812. DoPreferencesDialog(pmEditorInternal);
  813. }
  814. else if (Action == ReloadAction)
  815. {
  816. Reload();
  817. }
  818. else if (Action == FindAction || Action == ReplaceAction)
  819. {
  820. StartFind(Action == FindAction);
  821. }
  822. else if (Action == FindNextAction)
  823. {
  824. if (!FLastFindDialog)
  825. {
  826. FLastFindDialog = FFindDialog;
  827. }
  828. Find();
  829. }
  830. else if (Action == GoToLineAction)
  831. {
  832. GoToLine();
  833. }
  834. else if (Action == EditRedo)
  835. {
  836. EditorMemo->Redo();
  837. }
  838. else if (Action == HelpAction)
  839. {
  840. FormHelp(this);
  841. }
  842. else if (Action == DefaultEncodingAction)
  843. {
  844. ChangeEncoding(FAnsiEncoding);
  845. }
  846. else if (Action == UTF8EncodingAction)
  847. {
  848. ChangeEncoding(TEncoding::UTF8);
  849. }
  850. else if (Action == ColorAction)
  851. {
  852. if (DebugAlwaysTrue(Action->ActionComponent != NULL))
  853. {
  854. CreateEditorBackgroundColorMenu(Action->ActionComponent, BackgroundColor,
  855. SetBackgroundColor);
  856. }
  857. }
  858. else
  859. {
  860. Handled = false;
  861. }
  862. }
  863. //---------------------------------------------------------------------------
  864. void __fastcall TEditorForm::BackupSave()
  865. {
  866. if (IsFileModified())
  867. {
  868. int Uniq = 0;
  869. while (true)
  870. {
  871. UnicodeString FileName = FFileName + L".bak" + (Uniq == 0 ? UnicodeString() : IntToStr(Uniq));
  872. UnicodeString ApiFileName = ApiPath(FileName);
  873. if (!FileExists(ApiFileName))
  874. {
  875. EditorMemo->Lines->SaveToFile(ApiFileName, FEncoding);
  876. break;
  877. }
  878. Uniq++;
  879. }
  880. }
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TEditorForm::ChangeEncoding(TEncoding * Encoding)
  884. {
  885. if (FEncoding != Encoding)
  886. {
  887. if (!IsFileModified() ||
  888. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_ENCODING)), qtConfirmation,
  889. qaOK | qaCancel) != qaCancel))
  890. {
  891. TEncoding * PrevEncoding = FEncoding;
  892. try
  893. {
  894. FEncoding = Encoding;
  895. LoadFile();
  896. }
  897. catch(...)
  898. {
  899. // try to restore
  900. FEncoding = PrevEncoding;
  901. LoadFile();
  902. throw;
  903. }
  904. }
  905. }
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TEditorForm::FormCloseQuery(TObject * /*Sender*/,
  909. bool &CanClose)
  910. {
  911. if (IsFileModified())
  912. {
  913. SetFocus();
  914. UnicodeString Message = MainInstructions(LoadStr(SAVE_CHANGES));
  915. unsigned int Answer = MessageDialog(Message, qtConfirmation,
  916. qaYes | qaNo | qaCancel);
  917. CanClose = (Answer != qaCancel);
  918. if (Answer == qaYes)
  919. {
  920. SaveAction->Execute();
  921. if (FStandaloneEditor)
  922. {
  923. CanClose = false;
  924. FClosePending = true;
  925. }
  926. }
  927. }
  928. }
  929. //---------------------------------------------------------------------------
  930. void __fastcall TEditorForm::ApplyConfiguration()
  931. {
  932. bool PrevModified = IsFileModified();
  933. DebugAssert(Configuration);
  934. EditorMemo->SetFormat(WinConfiguration->Editor.Font,
  935. WinConfiguration->Editor.FontColor,
  936. WinConfiguration->Editor.TabSize,
  937. WinConfiguration->Editor.WordWrap);
  938. UpdateBackgroundColor();
  939. EditorMemo->Modified = PrevModified;
  940. EditorMemo->ClearUndo();
  941. Enabled = !WinConfiguration->LockedInterface;
  942. UpdateControls();
  943. }
  944. //---------------------------------------------------------------------------
  945. void __fastcall TEditorForm::FileUploadComplete()
  946. {
  947. DebugAssert(FSaving);
  948. FSaving = false;
  949. UpdateControls();
  950. if (FClosePending && DebugAlwaysTrue(FStandaloneEditor))
  951. {
  952. Close();
  953. }
  954. }
  955. //---------------------------------------------------------------------------
  956. void __fastcall TEditorForm::UpdateControls()
  957. {
  958. EditorMemo->ReadOnly = (OnFileChanged == NULL);
  959. TPoint ACaretPos = EditorMemo->CaretPos;
  960. if (ACaretPos.x != FCaretPos.x || ACaretPos.y != FCaretPos.y)
  961. {
  962. FCaretPos = ACaretPos;
  963. int Count = EditorMemo->Lines->Count;
  964. StatusBar->Panels->Items[0]->Caption = FMTLOAD(EDITOR_LINE_STATUS,
  965. ((int)FCaretPos.y+1, Count));
  966. int Column = 0;
  967. UnicodeString Character;
  968. if (FCaretPos.y >= 0 && FCaretPos.y < EditorMemo->Lines->Count)
  969. {
  970. UnicodeString Line = EditorMemo->Lines->Strings[FCaretPos.y];
  971. int TabSize = WinConfiguration->Editor.TabSize;
  972. for (int Index = 1; Index <= FCaretPos.x + 1; Index++)
  973. {
  974. if ((Index - 1 >= 1) && (Index - 1 <= Line.Length()) && (Line[Index - 1] == L'\t') &&
  975. (TabSize > 0)) // sanity check
  976. {
  977. Column = (((Column / TabSize) + 1) * TabSize) + 1;
  978. }
  979. else
  980. {
  981. Column++;
  982. }
  983. }
  984. if (FCaretPos.x+1 <= Line.Length())
  985. {
  986. int Code;
  987. wchar_t Ch = Line[FCaretPos.x + 1];
  988. if (FEncoding == FAnsiEncoding)
  989. {
  990. char Buf[10];
  991. BOOL UsedDefaultChar = FALSE;
  992. int Conversion =
  993. WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, &Ch, 1,
  994. Buf, sizeof(Buf), NULL, &UsedDefaultChar);
  995. // actually with multibyte encoding it may be > 1,
  996. if ((Conversion == 1) && !UsedDefaultChar)
  997. {
  998. Code = static_cast<int>(static_cast<unsigned char>(Buf[0]));
  999. }
  1000. else
  1001. {
  1002. Code = -1;
  1003. }
  1004. }
  1005. else
  1006. {
  1007. Code = static_cast<int>(Ch);
  1008. }
  1009. if (Code >= 0)
  1010. {
  1011. Character = FMTLOAD(EDITOR_CHARACTER_STATUS2, (Code, Code));
  1012. }
  1013. }
  1014. }
  1015. StatusBar->Panels->Items[1]->Caption =
  1016. (Column > 0) ? FMTLOAD(EDITOR_COLUMN_STATUS, (Column)) : UnicodeString();
  1017. StatusBar->Panels->Items[2]->Caption = Character;
  1018. }
  1019. StatusBar->Panels->Items[3]->Caption = FMTLOAD(EDITOR_ENCODING_STATUS, (FEncodingName));
  1020. UnicodeString Status;
  1021. if (EditorMemo->ReadOnly)
  1022. {
  1023. Status = LoadStr(EDITOR_READONLY);
  1024. }
  1025. else if (FSaving)
  1026. {
  1027. Status = LoadStr(EDITOR_SAVING);
  1028. }
  1029. else if (IsFileModified())
  1030. {
  1031. Status = LoadStr(EDITOR_MODIFIED);
  1032. }
  1033. StatusBar->Panels->Items[4]->Caption = Status;
  1034. EditorActions->UpdateAction(SaveAction);
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TEditorForm::EditorMemoMouseUp(TObject * /*Sender*/,
  1038. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  1039. {
  1040. UpdateControls();
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall TEditorForm::EditorMemoKeyUp(TObject * /*Sender*/,
  1044. WORD & /*Key*/, TShiftState /*Shift*/)
  1045. {
  1046. UpdateControls();
  1047. }
  1048. //---------------------------------------------------------------------------
  1049. void __fastcall TEditorForm::EditorMemoChange(TObject * /*Sender*/)
  1050. {
  1051. UpdateControls();
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TEditorForm::FindDialogFind(TObject * /*Sender*/)
  1055. {
  1056. Find();
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TEditorForm::Find()
  1060. {
  1061. int NewPos;
  1062. int Replacements = 0;
  1063. do
  1064. {
  1065. DebugAssert(FLastFindDialog);
  1066. TSearchTypes SearchTypes;
  1067. // length condition is there to improve performance when large
  1068. // block is selected in editor
  1069. if (FLastFindDialog == FReplaceDialog &&
  1070. (FReplaceDialog->Options.Contains(frReplace) ||
  1071. FReplaceDialog->Options.Contains(frReplaceAll)) &&
  1072. FReplaceDialog->FindText.Length() == EditorMemo->SelLength &&
  1073. AnsiSameText(FReplaceDialog->FindText, EditorMemo->SelText))
  1074. {
  1075. EditorMemo->SelText = FReplaceDialog->ReplaceText;
  1076. Replacements++;
  1077. }
  1078. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1079. EditorConfiguration.FindText = FLastFindDialog->FindText;
  1080. EditorConfiguration.ReplaceText = FReplaceDialog->ReplaceText;
  1081. EditorConfiguration.FindMatchCase = FLastFindDialog->Options.Contains(frMatchCase);
  1082. EditorConfiguration.FindWholeWord = FLastFindDialog->Options.Contains(frWholeWord);
  1083. EditorConfiguration.FindDown = FLastFindDialog->Options.Contains(frDown);
  1084. WinConfiguration->Editor = EditorConfiguration;
  1085. if (EditorConfiguration.FindMatchCase)
  1086. {
  1087. SearchTypes << stMatchCase;
  1088. }
  1089. if (EditorConfiguration.FindWholeWord)
  1090. {
  1091. SearchTypes << stWholeWord;
  1092. }
  1093. NewPos = EditorMemo->FindText(EditorConfiguration.FindText,
  1094. EditorMemo->SelLength ? EditorMemo->SelStart+1 : EditorMemo->SelStart,
  1095. EditorMemo->Text.Length(), SearchTypes, EditorConfiguration.FindDown);
  1096. if (NewPos >= 0)
  1097. {
  1098. EditorMemo->SelStart = NewPos;
  1099. EditorMemo->SelLength = EditorConfiguration.FindText.Length();
  1100. }
  1101. if (FLastFindDialog->Handle)
  1102. {
  1103. PositionFindDialog(true);
  1104. }
  1105. if (NewPos < 0)
  1106. {
  1107. if ((Replacements == 0) || FReplaceDialog->Options.Contains(frReplaceAll))
  1108. {
  1109. // now Screen->ActiveForm can be NULL when other form was meanwhile
  1110. // activated and then focus was returned back to "find" dialog
  1111. // (non VCL form)
  1112. if (Screen->ActiveForm != this)
  1113. {
  1114. SetFocus();
  1115. FLastFindDialog->Execute();
  1116. }
  1117. if (Replacements == 0)
  1118. {
  1119. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_FIND_END, (EditorConfiguration.FindText)));
  1120. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1121. }
  1122. else if (FReplaceDialog->Options.Contains(frReplaceAll))
  1123. {
  1124. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_REPLACE_END, (Replacements)));
  1125. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. while (NewPos >= 0 && FLastFindDialog == FReplaceDialog &&
  1131. FReplaceDialog->Options.Contains(frReplaceAll));
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. void __fastcall TEditorForm::FormShow(TObject * /*Sender*/)
  1135. {
  1136. if (DebugAlwaysTrue(FParentForm != NULL))
  1137. {
  1138. // Forms should be at the same monitor
  1139. DebugAssert(PixelsPerInch == FParentForm->PixelsPerInch);
  1140. Width = MulDiv(FParentForm->BoundsRect.Width(), PixelsPerInch, FParentForm->PixelsPerInch);
  1141. Height = MulDiv(FParentForm->BoundsRect.Height(), PixelsPerInch, FParentForm->PixelsPerInch);
  1142. }
  1143. CutFormToDesktop(this);
  1144. DebugAssert(FWindowParams.IsEmpty());
  1145. if (FWindowParams.IsEmpty())
  1146. {
  1147. FWindowParams = StoreForm(this);
  1148. }
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. // VCLCOPY ComCtrls.pas
  1152. bool __fastcall TEditorForm::ContainsPreamble(TStream * Stream, const TBytes & Signature)
  1153. {
  1154. bool Result;
  1155. TBytes Buffer;
  1156. int LBufLen;
  1157. int LSignatureLen = Signature.Length;
  1158. __int64 LPosition = Stream->Position;
  1159. try
  1160. {
  1161. Buffer.Length = LSignatureLen;
  1162. LBufLen = Stream->Read(&Buffer[0], LSignatureLen);
  1163. }
  1164. __finally
  1165. {
  1166. Stream->Position = LPosition;
  1167. }
  1168. if (LBufLen == LSignatureLen)
  1169. {
  1170. Result = true;
  1171. for (int I = 1; I <= LSignatureLen; I++)
  1172. {
  1173. if (Buffer[I - 1] != Signature[I - 1])
  1174. {
  1175. Result = false;
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. else
  1181. {
  1182. Result = false;
  1183. }
  1184. return Result;
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. void __fastcall TEditorForm::LoadFromFile(bool PrimaryEncoding)
  1188. {
  1189. TStream * Stream = new TFileStream(ApiPath(FFileName), fmOpenRead | fmShareDenyWrite);
  1190. try
  1191. {
  1192. bool CanTrySecondary;
  1193. if (FEncoding == NULL)
  1194. {
  1195. int Encoding;
  1196. if (ContainsPreamble(Stream, TEncoding::UTF8->GetPreamble()))
  1197. {
  1198. Encoding = CP_UTF8;
  1199. CanTrySecondary = false;
  1200. }
  1201. else
  1202. {
  1203. if (InternalEditorEncodingOverride >= 0)
  1204. {
  1205. Encoding = InternalEditorEncodingOverride;
  1206. }
  1207. else
  1208. {
  1209. Encoding = WinConfiguration->Editor.Encoding;
  1210. }
  1211. CanTrySecondary = true;
  1212. }
  1213. switch (Encoding)
  1214. {
  1215. case CP_UTF8:
  1216. FEncoding = PrimaryEncoding ? TEncoding::UTF8 : FAnsiEncoding;
  1217. break;
  1218. default:
  1219. CanTrySecondary = false;
  1220. DebugFail();
  1221. // fallthru
  1222. case CP_ACP:
  1223. FEncoding = PrimaryEncoding ? FAnsiEncoding : TEncoding::UTF8;
  1224. break;
  1225. }
  1226. }
  1227. else
  1228. {
  1229. CanTrySecondary = false;
  1230. }
  1231. FEncodingName = GetCodePageName(FEncoding);
  1232. bool EncodingError;
  1233. if (!EditorMemo->LoadFromStream(Stream, FEncoding, EncodingError))
  1234. {
  1235. if (EncodingError)
  1236. {
  1237. UnicodeString Message = FMTLOAD(EDITOR_ENCODING_ERROR, (FFileName, FEncodingName));
  1238. if (PrimaryEncoding && CanTrySecondary)
  1239. {
  1240. TEncoding * EncodingBackup = FEncoding;
  1241. UnicodeString EncodingNameBackup = FEncodingName;
  1242. try
  1243. {
  1244. FEncoding = NULL;
  1245. LoadFromFile(false);
  1246. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1247. if (EditorConfiguration.WarnOnEncodingFallback)
  1248. {
  1249. // by now the FEncodingName is the secondary encoding
  1250. Message = Message + L" " + FMTLOAD(EDITOR_ENCODING_REVERTED, (FEncodingName));
  1251. TMessageParams Params(mpNeverAskAgainCheck);
  1252. unsigned int Answer =
  1253. MessageDialog(MainInstructions(Message), qtInformation, qaOK, HELP_NONE, &Params);
  1254. if (Answer == qaNeverAskAgain)
  1255. {
  1256. EditorConfiguration.WarnOnEncodingFallback = false;
  1257. WinConfiguration->Editor = EditorConfiguration;
  1258. }
  1259. }
  1260. }
  1261. catch(...)
  1262. {
  1263. // restored values are never used anyway, as this can get here only
  1264. // when opening editor and this is fatal error preventing the editor from opening
  1265. FEncoding = EncodingBackup;
  1266. FEncodingName = EncodingNameBackup;
  1267. throw Exception(Message);
  1268. }
  1269. }
  1270. else
  1271. {
  1272. throw Exception(Message);
  1273. }
  1274. }
  1275. else
  1276. {
  1277. throw Exception(MainInstructions(FMTLOAD(EDITOR_LOAD_ERROR, (FFileName))));
  1278. }
  1279. }
  1280. }
  1281. __finally
  1282. {
  1283. delete Stream;
  1284. }
  1285. SendMessage(EditorMemo->Handle, EM_EXLIMITTEXT, 0, 0x7FFFFFF0);
  1286. }
  1287. //---------------------------------------------------------------------------
  1288. void __fastcall TEditorForm::CheckFileSize()
  1289. {
  1290. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1291. TWin32FileAttributeData FileAttributeData;
  1292. if (GetFileAttributesEx(ApiPath(FFileName).c_str(), GetFileExInfoStandard, &FileAttributeData))
  1293. {
  1294. const __int64 MaxSize = 100 * 1024 * 1024;
  1295. __int64 Size =
  1296. (static_cast<__int64>(FileAttributeData.nFileSizeHigh) << 32) +
  1297. FileAttributeData.nFileSizeLow;
  1298. if (Size > MaxSize)
  1299. {
  1300. if (EditorConfiguration.WarnOrLargeFileSize)
  1301. {
  1302. TMessageParams Params(mpNeverAskAgainCheck);
  1303. unsigned int Answer =
  1304. MoreMessageDialog(
  1305. FMTLOAD(INTERNAL_EDITOR_LARGE_FILE, (FormatBytes(Size))), NULL,
  1306. qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  1307. switch (Answer)
  1308. {
  1309. case qaOK:
  1310. // noop;
  1311. break;
  1312. case qaCancel:
  1313. Abort();
  1314. break;
  1315. case qaNeverAskAgain:
  1316. EditorConfiguration.WarnOrLargeFileSize = false;
  1317. WinConfiguration->Editor = EditorConfiguration;
  1318. break;
  1319. default:
  1320. DebugFail();
  1321. }
  1322. }
  1323. IgnoreException(typeid(EOutOfMemory));
  1324. }
  1325. }
  1326. }
  1327. //---------------------------------------------------------------------------
  1328. void __fastcall TEditorForm::LoadFile()
  1329. {
  1330. CheckFileSize();
  1331. HandleNeeded();
  1332. LoadFromFile(true);
  1333. EditorMemo->ResetFormat();
  1334. EditorMemo->Modified = false;
  1335. FCaretPos.x = -1;
  1336. // this is important particularly after reload
  1337. UpdateControls();
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. bool __fastcall TEditorForm::CursorInUpperPart()
  1341. {
  1342. HFONT OldFont;
  1343. HDC DC;
  1344. TTextMetric TM;
  1345. TRect Rect;
  1346. DC = GetDC(EditorMemo->Handle);
  1347. OldFont = (HFONT)SelectObject(DC, EditorMemo->Font->Handle);
  1348. try
  1349. {
  1350. GetTextMetrics(DC, &TM);
  1351. EditorMemo->Perform(EM_GETRECT, 0, ((int)&Rect));
  1352. }
  1353. __finally
  1354. {
  1355. SelectObject(DC, OldFont);
  1356. ReleaseDC(EditorMemo->Handle, DC);
  1357. }
  1358. int VisibleLines = (Rect.Bottom - Rect.Top) / (TM.tmHeight + TM.tmExternalLeading);
  1359. int FirstLine = SendMessage(EditorMemo->Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
  1360. TPoint CaretPos = EditorMemo->CaretPos;
  1361. return (CaretPos.y - FirstLine) < VisibleLines / 2;
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TEditorForm::PositionFindDialog(bool VerticalOnly)
  1365. {
  1366. DebugAssert(FLastFindDialog);
  1367. if (!VerticalOnly)
  1368. {
  1369. FLastFindDialog->Left = Left + EditorMemo->Left + EditorMemo->Width / 2 - ScaleByTextHeight(this, 100);
  1370. }
  1371. FLastFindDialog->Top = Top + EditorMemo->Top + (EditorMemo->Height / 4) +
  1372. (CursorInUpperPart() ? (EditorMemo->Height / 2) : 0) - ScaleByTextHeight(this, 40);
  1373. }
  1374. //---------------------------------------------------------------------------
  1375. void __fastcall TEditorForm::StartFind(bool Find)
  1376. {
  1377. UnicodeString Text = EditorMemo->SelText;
  1378. TFindOptions Options;
  1379. Options << frShowHelp;
  1380. if (Text.IsEmpty())
  1381. {
  1382. Text = WinConfiguration->Editor.FindText;
  1383. }
  1384. TFindDialog * Dialog = Find ? FFindDialog : FReplaceDialog;
  1385. if (FLastFindDialog && Dialog != FLastFindDialog && FLastFindDialog->Handle)
  1386. {
  1387. FLastFindDialog->CloseDialog();
  1388. }
  1389. FLastFindDialog = Dialog;
  1390. if (!Text.IsEmpty())
  1391. {
  1392. FLastFindDialog->FindText = Text;
  1393. }
  1394. FReplaceDialog->ReplaceText = WinConfiguration->Editor.ReplaceText;
  1395. if (WinConfiguration->Editor.FindMatchCase)
  1396. {
  1397. Options << frMatchCase;
  1398. }
  1399. if (WinConfiguration->Editor.FindWholeWord)
  1400. {
  1401. Options << frWholeWord;
  1402. }
  1403. if (WinConfiguration->Editor.FindDown)
  1404. {
  1405. Options << frDown;
  1406. }
  1407. FLastFindDialog->Options = Options;
  1408. if (!FLastFindDialog->Handle)
  1409. {
  1410. PositionFindDialog(false);
  1411. }
  1412. FLastFindDialog->Execute();
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. void __fastcall TEditorForm::GoToLine()
  1416. {
  1417. UnicodeString Str;
  1418. if (InputDialog(LoadStr(EDITOR_GO_TO_LINE), LoadStr(EDITOR_LINE_NUMBER), Str))
  1419. {
  1420. int Line = StrToIntDef(Str, -1);
  1421. if (Line <= 0 || Line > EditorMemo->Lines->Count)
  1422. {
  1423. throw Exception(MainInstructions(LoadStr(EDITOR_INVALID_LINE)));
  1424. }
  1425. else
  1426. {
  1427. EditorMemo->CaretPos = TPoint(0, Line-1);
  1428. }
  1429. }
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. void __fastcall TEditorForm::FormClose(TObject * /*Sender*/,
  1433. TCloseAction & Action)
  1434. {
  1435. // Preferably announce closure here as this is called from within TForm::Close(),
  1436. // so the annoucement will be synchronous (and editor manager thus
  1437. // will consider the form to be really closed and will not block
  1438. // application closure).
  1439. // However FormClose is not called when form is closed due to
  1440. // application exit, so there is last resort call from destructor.
  1441. DoWindowClose(false);
  1442. FCloseAnnounced = true;
  1443. Action = caFree;
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. void __fastcall TEditorForm::DoWindowClose(bool Forced)
  1447. {
  1448. if (FOnWindowClose != NULL)
  1449. {
  1450. try
  1451. {
  1452. FOnWindowClose(this, Forced);
  1453. }
  1454. catch(Exception & E)
  1455. {
  1456. ShowExtendedException(&E);
  1457. }
  1458. }
  1459. }
  1460. //---------------------------------------------------------------------------
  1461. void __fastcall TEditorForm::CreateParams(TCreateParams & Params)
  1462. {
  1463. // this is called for the first time from parent's constructor.
  1464. // FFormRestored is set to false implicitly
  1465. if (!FFormRestored)
  1466. {
  1467. FInstance = FInstances;
  1468. FInstances++;
  1469. FFormRestored = true;
  1470. UnicodeString WindowParams = WinConfiguration->Editor.WindowParams;
  1471. if ((FInstance == 0) && !WindowParams.IsEmpty())
  1472. {
  1473. RestoreForm(WindowParams, this);
  1474. }
  1475. }
  1476. TForm::CreateParams(Params);
  1477. Params.WndParent = GetDesktopWindow();
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. void __fastcall TEditorForm::Reload()
  1481. {
  1482. TAutoFlag ReloadingFlag(FReloading);
  1483. if (!IsFileModified() ||
  1484. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_RELOAD)), qtConfirmation,
  1485. qaOK | qaCancel) != qaCancel))
  1486. {
  1487. if (FOnFileReload)
  1488. {
  1489. FOnFileReload(this);
  1490. }
  1491. LoadFile();
  1492. }
  1493. }
  1494. //---------------------------------------------------------------------------
  1495. void __fastcall TEditorForm::FormKeyDown(TObject * /*Sender*/, WORD & Key, TShiftState Shift)
  1496. {
  1497. if (((Key == VK_ESCAPE) || (Key == VK_F10)) && Shift.Empty())
  1498. {
  1499. Key = 0;
  1500. Close();
  1501. }
  1502. }
  1503. //---------------------------------------------------------------------------
  1504. void __fastcall TEditorForm::SetBackgroundColor(TColor Color)
  1505. {
  1506. if (BackgroundColor != Color)
  1507. {
  1508. FBackgroundColor = Color;
  1509. UpdateBackgroundColor();
  1510. }
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. void __fastcall TEditorForm::UpdateBackgroundColor()
  1514. {
  1515. TColor Color = FBackgroundColor;
  1516. if (Color == 0)
  1517. {
  1518. // double default, first our preferred default, then system default
  1519. Color = GetWindowColor(WinConfiguration->Editor.BackgroundColor);
  1520. }
  1521. ColorItem->Color = Color;
  1522. if (EditorMemo->Color != Color)
  1523. {
  1524. EditorMemo->Color = Color;
  1525. // does not seem to have any effect (nor is needed), but just in case
  1526. ForceColorChange(EditorMemo);
  1527. }
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. void __fastcall TEditorForm::CMDpiChanged(TMessage & Message)
  1531. {
  1532. bool WasModified = EditorMemo->Modified;
  1533. EditorMemo->ApplyFont();
  1534. EditorMemo->Modified = WasModified;
  1535. // we do not want this, but we want to prevent undo of the font change too, should be improved
  1536. EditorMemo->ClearUndo();
  1537. // Clear "modified" status in the status bar, invoked by font change
  1538. UpdateControls();
  1539. TForm::Dispatch(&Message);
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. void __fastcall TEditorForm::Dispatch(void * Message)
  1543. {
  1544. TMessage * M = static_cast<TMessage*>(Message);
  1545. switch (M->Msg)
  1546. {
  1547. case CM_DPICHANGED:
  1548. CMDpiChanged(*M);
  1549. break;
  1550. default:
  1551. TForm::Dispatch(Message);
  1552. break;
  1553. }
  1554. }