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