Editor.cpp 50 KB

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