Editor.cpp 51 KB

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