Editor.cpp 47 KB

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