Editor.cpp 47 KB

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