1
0

Editor.cpp 43 KB

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