Editor.cpp 46 KB

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