Editor.cpp 49 KB

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