Editor.cpp 52 KB

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