Editor.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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. // VCLCOPY 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. // VCLCOPY 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. // VCLCOPY StreamLoad
  447. bool Result;
  448. try
  449. {
  450. if (StreamInfo->Converter != NULL)
  451. {
  452. TBytes Buffer;
  453. Buffer.Length = Read + 1;
  454. Read = Read / 2;
  455. if ((Read % 2) > 0)
  456. {
  457. Read--;
  458. }
  459. WasRead = StreamInfo->Converter->ConvertReadStream(StreamInfo->Stream, Buffer, Read);
  460. if (WasRead > 0)
  461. {
  462. Buffer[WasRead] = 0;
  463. if (Buffer[WasRead - 1] == 13)
  464. {
  465. Buffer[WasRead - 1] = 0;
  466. WasRead--;
  467. }
  468. int StartIndex = 0;
  469. // Convert from desired Encoding to Unicode
  470. if (StreamInfo->PlainText)
  471. {
  472. if (StreamInfo->Encoding == NULL)
  473. {
  474. Buffer = TEncoding::Convert(TEncoding::Default, TEncoding::Unicode, Buffer, 0, WasRead);
  475. WasRead = Buffer.Length;
  476. }
  477. else
  478. {
  479. if (!TEncoding::Unicode->Equals(StreamInfo->Encoding))
  480. {
  481. int MaxTries = StreamInfo->Encoding->GetMaxByteCount(1);
  482. while ((WasRead > 0) &&
  483. (StreamInfo->Encoding->GetCharCount(Buffer, 0, WasRead) == 0))
  484. {
  485. WasRead--;
  486. StreamInfo->Stream->Seek(-1, soFromCurrent);
  487. MaxTries--;
  488. if ((MaxTries == 0) || (WasRead == 0))
  489. {
  490. FStreamLoadEncodingError = true;
  491. Abort();
  492. }
  493. }
  494. Buffer = TEncoding::Convert(StreamInfo->Encoding, TEncoding::Unicode, Buffer, 0, WasRead);
  495. WasRead = Buffer.Length;
  496. }
  497. // If Unicode preamble is present, set StartIndex to skip over it
  498. TBytes Preamble = TEncoding::Unicode->GetPreamble();
  499. if (DebugAlwaysTrue(Preamble.Length == 2) &&
  500. (WasRead >= 2) && (Buffer[0] == Preamble[0]) && (Buffer[1] == Preamble[1]))
  501. {
  502. StartIndex = 2;
  503. // beware that this is also called from CreateWnd with some
  504. // dummy contents that always have BOM, so FLoadedWithPreamble
  505. // is true, unless overriden by LoadFromStream
  506. FLoadedWithPreamble = true;
  507. }
  508. }
  509. }
  510. WasRead = AdjustLineBreaks(Buff, Buffer, StartIndex, WasRead);
  511. }
  512. }
  513. Result = true;
  514. }
  515. catch (EEncodingError & E)
  516. {
  517. FStreamLoadError = true;
  518. FStreamLoadEncodingError = true;
  519. Result = false;
  520. }
  521. catch (Exception & E)
  522. {
  523. FStreamLoadError = true;
  524. Result = false;
  525. }
  526. return Result;
  527. }
  528. //---------------------------------------------------------------------------
  529. bool __fastcall TRichEdit20::LoadFromStream(TStream * Stream, TEncoding * Encoding, bool & EncodingError)
  530. {
  531. FStreamLoadEncodingError = false;
  532. FStreamLoadError = false;
  533. FLoadedWithPreamble = false;
  534. Lines->LoadFromStream(Stream, Encoding);
  535. if (FStreamLoadError)
  536. {
  537. EncodingError = FStreamLoadEncodingError;
  538. }
  539. return !FStreamLoadError;
  540. }
  541. //---------------------------------------------------------------------------
  542. class TFindDialogEx : public TFindDialog
  543. {
  544. public:
  545. __fastcall virtual TFindDialogEx(TComponent * AOwner) : TFindDialog(AOwner)
  546. {
  547. FHelpMsg = RegisterWindowMessage(HELPMSGSTRING);
  548. }
  549. protected:
  550. unsigned int FHelpMsg;
  551. virtual bool __fastcall MessageHook(TMessage & Msg)
  552. {
  553. bool Result = false;
  554. if (Msg.Msg == FHelpMsg)
  555. {
  556. Application->HelpKeyword(HELP_EDITOR_FIND);
  557. Result = true;
  558. }
  559. if (!Result)
  560. {
  561. Result = TFindDialog::MessageHook(Msg);
  562. }
  563. return Result;
  564. }
  565. };
  566. //---------------------------------------------------------------------------
  567. class TReplaceDialogEx : public TReplaceDialog
  568. {
  569. public:
  570. __fastcall virtual TReplaceDialogEx(TComponent * AOwner) : TReplaceDialog(AOwner)
  571. {
  572. FHelpMsg = RegisterWindowMessage(HELPMSGSTRING);
  573. }
  574. protected:
  575. unsigned int FHelpMsg;
  576. virtual bool __fastcall MessageHook(TMessage & Msg)
  577. {
  578. bool Result = false;
  579. if (Msg.Msg == FHelpMsg)
  580. {
  581. Application->HelpKeyword(HELP_EDITOR_REPLACE);
  582. Result = true;
  583. }
  584. if (!Result)
  585. {
  586. Result = TReplaceDialog::MessageHook(Msg);
  587. }
  588. return Result;
  589. }
  590. };
  591. //---------------------------------------------------------------------------
  592. unsigned int TEditorForm::FInstances = 0;
  593. //---------------------------------------------------------------------------
  594. __fastcall TEditorForm::TEditorForm(TComponent* Owner)
  595. : TForm(Owner)
  596. {
  597. FAnsiEncoding = TEncoding::Default;
  598. if (!FAnsiEncoding->IsSingleByte)
  599. {
  600. // We need the GetCharCount to fail for multibyte Ansi encoding (e.g. Japanese Shift-JIS CP592) like the
  601. // TUTF8Encoding does, see the TUTF8Encoding.Create.
  602. // We could use this for single-byte encodings too without any harm probably.
  603. // But for now, try to limit an impact of this change.
  604. // Based on TEncoding.GetANSI.
  605. FAnsiEncoding = new TMBCSEncoding(GetACP(), MB_ERR_INVALID_CHARS, 0);
  606. }
  607. EditorMemo = new TRichEdit20(this);
  608. EditorMemo->Parent = this;
  609. EditorMemo->Align = alClient;
  610. EditorMemo->HideSelection = false;
  611. EditorMemo->PlainText = true;
  612. EditorMemo->PopupMenu = EditorPopup;
  613. EditorMemo->ScrollBars = ssBoth;
  614. EditorMemo->WantTabs = true;
  615. EditorMemo->OnChange = EditorMemoChange;
  616. EditorMemo->OnKeyUp = EditorMemoKeyUp;
  617. EditorMemo->OnMouseUp = EditorMemoMouseUp;
  618. // By default the TEditAction's reflect state of the currently focused edit.
  619. // Even if the edit is on a different window.
  620. // This way we explicitly bind them to our editor.
  621. for (int Index = 0; Index < EditorActions->ActionCount; Index++)
  622. {
  623. TEditAction * EditAction = dynamic_cast<TEditAction* >(EditorActions->Actions[Index]);
  624. if (EditAction != NULL)
  625. {
  626. EditAction->Control = EditorMemo;
  627. }
  628. }
  629. FParentForm = NULL;
  630. FCaretPos = TPoint(-1, -1);
  631. FLastFindDialog = NULL;
  632. FCloseAnnounced = false;
  633. ApplyConfiguration();
  634. FFindDialog = new TFindDialogEx(this);
  635. FFindDialog->OnFind = FindDialogFind;
  636. FReplaceDialog = new TReplaceDialogEx(this);
  637. FReplaceDialog->OnFind = FindDialogFind;
  638. FReplaceDialog->OnReplace = FindDialogFind;
  639. FEncoding = NULL;
  640. FSaving = false;
  641. FStandaloneEditor = false;
  642. FClosePending = false;
  643. FReloading = false;
  644. SetSubmenu(ColorItem);
  645. InitCodePage();
  646. SelectScaledImageList(EditorImages);
  647. UseSystemSettings(this);
  648. UseDesktopFont(StatusBar);
  649. FixFormIcons(this);
  650. }
  651. //---------------------------------------------------------------------------
  652. __fastcall TEditorForm::~TEditorForm()
  653. {
  654. DebugAssert(FInstances > 0);
  655. FInstances--;
  656. if (FInstance == 0)
  657. {
  658. UnicodeString WindowParams = StoreForm(this);
  659. // this is particularly to prevent saving the form state
  660. // for the first time, keeping default positioning by a system
  661. if (!FWindowParams.IsEmpty() && (FWindowParams != WindowParams))
  662. {
  663. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  664. EditorConfiguration.WindowParams = StoreForm(this);
  665. WinConfiguration->Editor = EditorConfiguration;
  666. }
  667. }
  668. // see FormClose for explanation
  669. if (!FCloseAnnounced)
  670. {
  671. BackupSave();
  672. DoWindowClose(true);
  673. }
  674. if (FAnsiEncoding != TEncoding::Default)
  675. {
  676. delete FAnsiEncoding;
  677. FAnsiEncoding = NULL;
  678. }
  679. if (FStandaloneEditor)
  680. {
  681. TerminateApplication();
  682. }
  683. }
  684. //---------------------------------------------------------------------------
  685. UnicodeString __fastcall TEditorForm::GetCodePageName(TEncoding * Encoding)
  686. {
  687. if (Encoding == TEncoding::UTF8)
  688. {
  689. return LoadStr(UTF8_NAME);
  690. }
  691. else
  692. {
  693. return DefaultEncodingName();
  694. }
  695. }
  696. //---------------------------------------------------------------------------
  697. void __fastcall TEditorForm::InitCodePage()
  698. {
  699. DefaultEncodingAction->Caption = DefaultEncodingName();
  700. DefaultEncodingAction->Hint = FORMAT(DefaultEncodingAction->Hint, (DefaultEncodingName()));
  701. }
  702. //---------------------------------------------------------------------------
  703. void __fastcall TEditorForm::SetFileName(const UnicodeString value)
  704. {
  705. if (value != FFileName)
  706. {
  707. FFileName = value;
  708. if (Visible)
  709. {
  710. LoadFile();
  711. }
  712. }
  713. }
  714. //---------------------------------------------------------------------------
  715. void __fastcall TEditorForm::SetParentForm(TCustomForm * value)
  716. {
  717. if (FParentForm != value)
  718. {
  719. FParentForm = value;
  720. if (value)
  721. {
  722. Width = value->BoundsRect.Width();
  723. Height = value->BoundsRect.Height();
  724. }
  725. }
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TEditorForm::EditorActionsUpdate(TBasicAction *Action,
  729. bool &Handled)
  730. {
  731. Handled = true;
  732. if (Action == SaveAction)
  733. {
  734. SaveAction->Enabled = IsFileModified();
  735. }
  736. else if (Action == SaveAllAction2)
  737. {
  738. bool Enabled = !FStandaloneEditor;
  739. if (Enabled)
  740. {
  741. Enabled = IsFileModified();
  742. // optimization
  743. if (!Enabled)
  744. {
  745. FOnAnyModified(this, Enabled);
  746. }
  747. }
  748. SaveAllAction2->Enabled = Enabled;
  749. }
  750. else if (Action == FindNextAction)
  751. {
  752. FindNextAction->Enabled =
  753. FLastFindDialog != NULL || !FFindDialog->FindText.IsEmpty();
  754. }
  755. else if (Action == EditRedo)
  756. {
  757. EditRedo->Enabled = EditorMemo->CanRedo;
  758. }
  759. else if (Action == PreferencesAction ||
  760. Action == FindAction || Action == ReplaceAction || Action == GoToLineAction ||
  761. Action == HelpAction || Action == ColorAction)
  762. {
  763. ((TAction *)Action)->Enabled = true;
  764. }
  765. else if (Action == ReloadAction)
  766. {
  767. ReloadAction->Enabled = !FReloading;
  768. }
  769. else if (Action == DefaultEncodingAction)
  770. {
  771. DefaultEncodingAction->Enabled = true;
  772. DefaultEncodingAction->Checked = (FEncoding == FAnsiEncoding);
  773. }
  774. else if (Action == UTF8EncodingAction)
  775. {
  776. UTF8EncodingAction->Enabled = true;
  777. UTF8EncodingAction->Checked = (FEncoding == TEncoding::UTF8);
  778. }
  779. else
  780. {
  781. Handled = false;
  782. }
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TEditorForm::SaveToFile()
  786. {
  787. std::unique_ptr<TStream> Stream(
  788. new TPreambleFilteringFileStream(
  789. ApiPath(FFileName), fmCreate, FEncoding, EditorMemo->LoadedWithPreamble));
  790. EditorMemo->Lines->SaveToStream(Stream.get(), FEncoding);
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TEditorForm::SaveFile()
  794. {
  795. // Test is needed for "Save all" and is redundant for "Save"
  796. if (IsFileModified())
  797. {
  798. DebugAssert(!FFileName.IsEmpty());
  799. SaveToFile();
  800. if (FOnFileChanged)
  801. {
  802. FOnFileChanged(this);
  803. }
  804. FSaving = true;
  805. EditorMemo->Modified = false;
  806. UpdateControls();
  807. }
  808. }
  809. //---------------------------------------------------------------------------
  810. bool __fastcall TEditorForm::IsFileModified()
  811. {
  812. return EditorMemo->Modified;
  813. }
  814. //---------------------------------------------------------------------------
  815. void __fastcall TEditorForm::EditorActionsExecute(TBasicAction *Action,
  816. bool &Handled)
  817. {
  818. Handled = true;
  819. if (Action == SaveAction)
  820. {
  821. SaveFile();
  822. }
  823. else if (Action == SaveAllAction2)
  824. {
  825. OnSaveAll(this);
  826. }
  827. else if (Action == PreferencesAction)
  828. {
  829. DoPreferencesDialog(pmEditorInternal);
  830. }
  831. else if (Action == ReloadAction)
  832. {
  833. Reload();
  834. }
  835. else if (Action == FindAction || Action == ReplaceAction)
  836. {
  837. StartFind(Action == FindAction);
  838. }
  839. else if (Action == FindNextAction)
  840. {
  841. if (!FLastFindDialog)
  842. {
  843. FLastFindDialog = FFindDialog;
  844. }
  845. Find();
  846. }
  847. else if (Action == GoToLineAction)
  848. {
  849. GoToLine();
  850. }
  851. else if (Action == EditRedo)
  852. {
  853. EditorMemo->Redo();
  854. }
  855. else if (Action == HelpAction)
  856. {
  857. FormHelp(this);
  858. }
  859. else if (Action == DefaultEncodingAction)
  860. {
  861. ChangeEncoding(FAnsiEncoding);
  862. }
  863. else if (Action == UTF8EncodingAction)
  864. {
  865. ChangeEncoding(TEncoding::UTF8);
  866. }
  867. else if (Action == ColorAction)
  868. {
  869. if (DebugAlwaysTrue(Action->ActionComponent != NULL))
  870. {
  871. CreateEditorBackgroundColorMenu(Action->ActionComponent, BackgroundColor,
  872. SetBackgroundColor);
  873. }
  874. }
  875. else
  876. {
  877. Handled = false;
  878. }
  879. }
  880. //---------------------------------------------------------------------------
  881. void __fastcall TEditorForm::BackupSave()
  882. {
  883. if (IsFileModified())
  884. {
  885. int Uniq = 0;
  886. while (true)
  887. {
  888. UnicodeString FileName = FFileName + L".bak" + (Uniq == 0 ? UnicodeString() : IntToStr(Uniq));
  889. UnicodeString ApiFileName = ApiPath(FileName);
  890. if (!FileExists(ApiFileName))
  891. {
  892. EditorMemo->Lines->SaveToFile(ApiFileName, FEncoding);
  893. break;
  894. }
  895. Uniq++;
  896. }
  897. }
  898. }
  899. //---------------------------------------------------------------------------
  900. void __fastcall TEditorForm::ChangeEncoding(TEncoding * Encoding)
  901. {
  902. if (FEncoding != Encoding)
  903. {
  904. if (!IsFileModified() ||
  905. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_ENCODING)), qtConfirmation,
  906. qaOK | qaCancel) != qaCancel))
  907. {
  908. TEncoding * PrevEncoding = FEncoding;
  909. try
  910. {
  911. FEncoding = Encoding;
  912. LoadFile();
  913. }
  914. catch(...)
  915. {
  916. // try to restore
  917. FEncoding = PrevEncoding;
  918. LoadFile();
  919. throw;
  920. }
  921. }
  922. }
  923. }
  924. //---------------------------------------------------------------------------
  925. void __fastcall TEditorForm::FormCloseQuery(TObject * /*Sender*/,
  926. bool &CanClose)
  927. {
  928. if (IsFileModified())
  929. {
  930. SetFocus();
  931. UnicodeString Message = MainInstructions(LoadStr(SAVE_CHANGES));
  932. unsigned int Answer = MessageDialog(Message, qtConfirmation,
  933. qaYes | qaNo | qaCancel);
  934. CanClose = (Answer != qaCancel);
  935. if (Answer == qaYes)
  936. {
  937. SaveAction->Execute();
  938. if (FStandaloneEditor)
  939. {
  940. CanClose = false;
  941. FClosePending = true;
  942. }
  943. }
  944. }
  945. }
  946. //---------------------------------------------------------------------------
  947. void __fastcall TEditorForm::ApplyConfiguration()
  948. {
  949. bool PrevModified = IsFileModified();
  950. DebugAssert(Configuration);
  951. EditorMemo->SetFormat(WinConfiguration->Editor.Font,
  952. WinConfiguration->Editor.FontColor,
  953. WinConfiguration->Editor.TabSize,
  954. WinConfiguration->Editor.WordWrap);
  955. UpdateBackgroundColor();
  956. EditorMemo->Modified = PrevModified;
  957. EditorMemo->ClearUndo();
  958. Enabled = !WinConfiguration->LockedInterface;
  959. UpdateControls();
  960. }
  961. //---------------------------------------------------------------------------
  962. void __fastcall TEditorForm::FileUploadComplete()
  963. {
  964. DebugAssert(FSaving);
  965. FSaving = false;
  966. UpdateControls();
  967. if (FClosePending && DebugAlwaysTrue(FStandaloneEditor))
  968. {
  969. Close();
  970. }
  971. }
  972. //---------------------------------------------------------------------------
  973. void __fastcall TEditorForm::UpdateControls()
  974. {
  975. TPoint ACaretPos = EditorMemo->CaretPos;
  976. if (ACaretPos.x != FCaretPos.x || ACaretPos.y != FCaretPos.y)
  977. {
  978. FCaretPos = ACaretPos;
  979. int Count = EditorMemo->Lines->Count;
  980. StatusBar->Panels->Items[0]->Caption = FMTLOAD(EDITOR_LINE_STATUS,
  981. ((int)FCaretPos.y+1, Count));
  982. int Column = 0;
  983. UnicodeString Character;
  984. if (FCaretPos.y >= 0 && FCaretPos.y < EditorMemo->Lines->Count)
  985. {
  986. UnicodeString Line = EditorMemo->Lines->Strings[FCaretPos.y];
  987. int TabSize = WinConfiguration->Editor.TabSize;
  988. for (int Index = 1; Index <= FCaretPos.x + 1; Index++)
  989. {
  990. if ((Index - 1 >= 1) && (Index - 1 <= Line.Length()) && (Line[Index - 1] == L'\t') &&
  991. (TabSize > 0)) // sanity check
  992. {
  993. Column = (((Column / TabSize) + 1) * TabSize) + 1;
  994. }
  995. else
  996. {
  997. Column++;
  998. }
  999. }
  1000. if (FCaretPos.x+1 <= Line.Length())
  1001. {
  1002. int Code;
  1003. wchar_t Ch = Line[FCaretPos.x + 1];
  1004. if (FEncoding == FAnsiEncoding)
  1005. {
  1006. char Buf[10];
  1007. BOOL UsedDefaultChar = FALSE;
  1008. int Conversion =
  1009. WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, &Ch, 1,
  1010. Buf, sizeof(Buf), NULL, &UsedDefaultChar);
  1011. // actually with multibyte encoding it may be > 1,
  1012. if ((Conversion == 1) && !UsedDefaultChar)
  1013. {
  1014. Code = static_cast<int>(static_cast<unsigned char>(Buf[0]));
  1015. }
  1016. else
  1017. {
  1018. Code = -1;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. Code = static_cast<int>(Ch);
  1024. }
  1025. if (Code >= 0)
  1026. {
  1027. Character = FMTLOAD(EDITOR_CHARACTER_STATUS2, (Code, Code));
  1028. }
  1029. }
  1030. }
  1031. StatusBar->Panels->Items[1]->Caption =
  1032. (Column > 0) ? FMTLOAD(EDITOR_COLUMN_STATUS, (Column)) : UnicodeString();
  1033. StatusBar->Panels->Items[2]->Caption = Character;
  1034. }
  1035. StatusBar->Panels->Items[3]->Caption = FMTLOAD(EDITOR_ENCODING_STATUS, (FEncodingName));
  1036. StatusBar->Panels->Items[4]->Caption =
  1037. (FSaving ? LoadStr(EDITOR_SAVING) :
  1038. (IsFileModified() ? LoadStr(EDITOR_MODIFIED) : UnicodeString(L"")));
  1039. EditorActions->UpdateAction(SaveAction);
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. void __fastcall TEditorForm::EditorMemoMouseUp(TObject * /*Sender*/,
  1043. TMouseButton /*Button*/, TShiftState /*Shift*/, int /*X*/, int /*Y*/)
  1044. {
  1045. UpdateControls();
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall TEditorForm::EditorMemoKeyUp(TObject * /*Sender*/,
  1049. WORD & /*Key*/, TShiftState /*Shift*/)
  1050. {
  1051. UpdateControls();
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TEditorForm::EditorMemoChange(TObject * /*Sender*/)
  1055. {
  1056. UpdateControls();
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TEditorForm::FindDialogFind(TObject * /*Sender*/)
  1060. {
  1061. Find();
  1062. }
  1063. //---------------------------------------------------------------------------
  1064. void __fastcall TEditorForm::Find()
  1065. {
  1066. int NewPos;
  1067. int Replacements = 0;
  1068. do
  1069. {
  1070. DebugAssert(FLastFindDialog);
  1071. TSearchTypes SearchTypes;
  1072. // length condition is there to improve performance when large
  1073. // block is selected in editor
  1074. if (FLastFindDialog == FReplaceDialog &&
  1075. (FReplaceDialog->Options.Contains(frReplace) ||
  1076. FReplaceDialog->Options.Contains(frReplaceAll)) &&
  1077. FReplaceDialog->FindText.Length() == EditorMemo->SelLength &&
  1078. AnsiSameText(FReplaceDialog->FindText, EditorMemo->SelText))
  1079. {
  1080. EditorMemo->SelText = FReplaceDialog->ReplaceText;
  1081. Replacements++;
  1082. }
  1083. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1084. EditorConfiguration.FindText = FLastFindDialog->FindText;
  1085. EditorConfiguration.ReplaceText = FReplaceDialog->ReplaceText;
  1086. EditorConfiguration.FindMatchCase = FLastFindDialog->Options.Contains(frMatchCase);
  1087. EditorConfiguration.FindWholeWord = FLastFindDialog->Options.Contains(frWholeWord);
  1088. EditorConfiguration.FindDown = FLastFindDialog->Options.Contains(frDown);
  1089. WinConfiguration->Editor = EditorConfiguration;
  1090. if (EditorConfiguration.FindMatchCase)
  1091. {
  1092. SearchTypes << stMatchCase;
  1093. }
  1094. if (EditorConfiguration.FindWholeWord)
  1095. {
  1096. SearchTypes << stWholeWord;
  1097. }
  1098. NewPos = EditorMemo->FindText(EditorConfiguration.FindText,
  1099. EditorMemo->SelLength ? EditorMemo->SelStart+1 : EditorMemo->SelStart,
  1100. EditorMemo->Text.Length(), SearchTypes, EditorConfiguration.FindDown);
  1101. if (NewPos >= 0)
  1102. {
  1103. EditorMemo->SelStart = NewPos;
  1104. EditorMemo->SelLength = EditorConfiguration.FindText.Length();
  1105. }
  1106. if (FLastFindDialog->Handle)
  1107. {
  1108. PositionFindDialog(true);
  1109. }
  1110. if (NewPos < 0)
  1111. {
  1112. if ((Replacements == 0) || FReplaceDialog->Options.Contains(frReplaceAll))
  1113. {
  1114. // now Screen->ActiveForm can be NULL when other form was meanwhile
  1115. // activated and then focus was returned back to "find" dialog
  1116. // (non VCL form)
  1117. if (Screen->ActiveForm != this)
  1118. {
  1119. SetFocus();
  1120. FLastFindDialog->Execute();
  1121. }
  1122. if (Replacements == 0)
  1123. {
  1124. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_FIND_END, (EditorConfiguration.FindText)));
  1125. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1126. }
  1127. else if (FReplaceDialog->Options.Contains(frReplaceAll))
  1128. {
  1129. UnicodeString Message = MainInstructions(FMTLOAD(EDITOR_REPLACE_END, (Replacements)));
  1130. MessageDialog(Message, qtInformation, qaOK, HELP_NONE);
  1131. }
  1132. }
  1133. }
  1134. }
  1135. while (NewPos >= 0 && FLastFindDialog == FReplaceDialog &&
  1136. FReplaceDialog->Options.Contains(frReplaceAll));
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. void __fastcall TEditorForm::FormShow(TObject * /*Sender*/)
  1140. {
  1141. CutFormToDesktop(this);
  1142. DebugAssert(FWindowParams.IsEmpty());
  1143. if (FWindowParams.IsEmpty())
  1144. {
  1145. FWindowParams = StoreForm(this);
  1146. }
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. // VCLCOPY ComCtrls.pas
  1150. bool __fastcall TEditorForm::ContainsPreamble(TStream * Stream, const TBytes & Signature)
  1151. {
  1152. bool Result;
  1153. TBytes Buffer;
  1154. int LBufLen;
  1155. int LSignatureLen = Signature.Length;
  1156. __int64 LPosition = Stream->Position;
  1157. try
  1158. {
  1159. Buffer.Length = LSignatureLen;
  1160. LBufLen = Stream->Read(&Buffer[0], LSignatureLen);
  1161. }
  1162. __finally
  1163. {
  1164. Stream->Position = LPosition;
  1165. }
  1166. if (LBufLen == LSignatureLen)
  1167. {
  1168. Result = true;
  1169. for (int I = 1; I <= LSignatureLen; I++)
  1170. {
  1171. if (Buffer[I - 1] != Signature[I - 1])
  1172. {
  1173. Result = false;
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. else
  1179. {
  1180. Result = false;
  1181. }
  1182. return Result;
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TEditorForm::LoadFromFile(bool PrimaryEncoding)
  1186. {
  1187. TStream * Stream = new TFileStream(ApiPath(FFileName), fmOpenRead | fmShareDenyWrite);
  1188. try
  1189. {
  1190. bool CanTrySecondary;
  1191. if (FEncoding == NULL)
  1192. {
  1193. int Encoding;
  1194. if (ContainsPreamble(Stream, TEncoding::UTF8->GetPreamble()))
  1195. {
  1196. Encoding = CP_UTF8;
  1197. CanTrySecondary = false;
  1198. }
  1199. else
  1200. {
  1201. Encoding = WinConfiguration->Editor.Encoding;
  1202. CanTrySecondary = true;
  1203. }
  1204. switch (Encoding)
  1205. {
  1206. case CP_UTF8:
  1207. FEncoding = PrimaryEncoding ? TEncoding::UTF8 : FAnsiEncoding;
  1208. break;
  1209. default:
  1210. CanTrySecondary = false;
  1211. DebugFail();
  1212. // fallthru
  1213. case CP_ACP:
  1214. FEncoding = PrimaryEncoding ? FAnsiEncoding : TEncoding::UTF8;
  1215. break;
  1216. }
  1217. }
  1218. else
  1219. {
  1220. CanTrySecondary = false;
  1221. }
  1222. FEncodingName = GetCodePageName(FEncoding);
  1223. bool EncodingError;
  1224. if (!EditorMemo->LoadFromStream(Stream, FEncoding, EncodingError))
  1225. {
  1226. if (EncodingError)
  1227. {
  1228. UnicodeString Message = FMTLOAD(EDITOR_ENCODING_ERROR, (FFileName, FEncodingName));
  1229. if (CanTrySecondary)
  1230. {
  1231. TEncoding * EncodingBackup = FEncoding;
  1232. UnicodeString EncodingNameBackup = FEncodingName;
  1233. try
  1234. {
  1235. FEncoding = NULL;
  1236. LoadFromFile(false);
  1237. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1238. if (EditorConfiguration.WarnOnEncodingFallback)
  1239. {
  1240. // by now the FEncodingName is the secondary encoding
  1241. Message = Message + L" " + FMTLOAD(EDITOR_ENCODING_REVERTED, (FEncodingName));
  1242. TMessageParams Params(mpNeverAskAgainCheck);
  1243. unsigned int Answer =
  1244. MessageDialog(MainInstructions(Message), qtInformation, qaOK, HELP_NONE, &Params);
  1245. if (Answer == qaNeverAskAgain)
  1246. {
  1247. EditorConfiguration.WarnOnEncodingFallback = false;
  1248. WinConfiguration->Editor = EditorConfiguration;
  1249. }
  1250. }
  1251. }
  1252. catch(...)
  1253. {
  1254. // restored values are never used anyway, as this can get here only
  1255. // when opening editor and this is fatal error preventing the editor from opening
  1256. FEncoding = EncodingBackup;
  1257. FEncodingName = EncodingNameBackup;
  1258. throw Exception(Message);
  1259. }
  1260. }
  1261. else
  1262. {
  1263. throw Exception(Message);
  1264. }
  1265. }
  1266. else
  1267. {
  1268. throw Exception(MainInstructions(FMTLOAD(EDITOR_LOAD_ERROR, (FFileName))));
  1269. }
  1270. }
  1271. }
  1272. __finally
  1273. {
  1274. delete Stream;
  1275. }
  1276. SendMessage(EditorMemo->Handle, EM_EXLIMITTEXT, 0, 0x7FFFFFF0);
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. void __fastcall TEditorForm::CheckFileSize()
  1280. {
  1281. TEditorConfiguration EditorConfiguration = WinConfiguration->Editor;
  1282. TWin32FileAttributeData FileAttributeData;
  1283. if (GetFileAttributesEx(ApiPath(FFileName).c_str(), GetFileExInfoStandard, &FileAttributeData))
  1284. {
  1285. const __int64 MaxSize = 100 * 1024 * 1024;
  1286. __int64 Size =
  1287. (static_cast<__int64>(FileAttributeData.nFileSizeHigh) << 32) +
  1288. FileAttributeData.nFileSizeLow;
  1289. if (Size > MaxSize)
  1290. {
  1291. if (EditorConfiguration.WarnOrLargeFileSize)
  1292. {
  1293. TMessageParams Params(mpNeverAskAgainCheck);
  1294. unsigned int Answer =
  1295. MoreMessageDialog(
  1296. FMTLOAD(INTERNAL_EDITOR_LARGE_FILE, (FormatBytes(Size))), NULL,
  1297. qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  1298. switch (Answer)
  1299. {
  1300. case qaOK:
  1301. // noop;
  1302. break;
  1303. case qaCancel:
  1304. Abort();
  1305. break;
  1306. case qaNeverAskAgain:
  1307. EditorConfiguration.WarnOrLargeFileSize = false;
  1308. WinConfiguration->Editor = EditorConfiguration;
  1309. break;
  1310. default:
  1311. DebugFail();
  1312. }
  1313. }
  1314. IgnoreException(typeid(EOutOfMemory));
  1315. }
  1316. }
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void __fastcall TEditorForm::LoadFile()
  1320. {
  1321. CheckFileSize();
  1322. HandleNeeded();
  1323. LoadFromFile(true);
  1324. EditorMemo->ResetFormat();
  1325. EditorMemo->Modified = false;
  1326. FCaretPos.x = -1;
  1327. // this is important particularly after reload
  1328. UpdateControls();
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. bool __fastcall TEditorForm::CursorInUpperPart()
  1332. {
  1333. HFONT OldFont;
  1334. HDC DC;
  1335. TTextMetric TM;
  1336. TRect Rect;
  1337. DC = GetDC(EditorMemo->Handle);
  1338. OldFont = (HFONT)SelectObject(DC, EditorMemo->Font->Handle);
  1339. try
  1340. {
  1341. GetTextMetrics(DC, &TM);
  1342. EditorMemo->Perform(EM_GETRECT, 0, ((int)&Rect));
  1343. }
  1344. __finally
  1345. {
  1346. SelectObject(DC, OldFont);
  1347. ReleaseDC(EditorMemo->Handle, DC);
  1348. }
  1349. int VisibleLines = (Rect.Bottom - Rect.Top) / (TM.tmHeight + TM.tmExternalLeading);
  1350. int FirstLine = SendMessage(EditorMemo->Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
  1351. TPoint CaretPos = EditorMemo->CaretPos;
  1352. return (CaretPos.y - FirstLine) < VisibleLines / 2;
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TEditorForm::PositionFindDialog(bool VerticalOnly)
  1356. {
  1357. DebugAssert(FLastFindDialog);
  1358. if (!VerticalOnly)
  1359. {
  1360. FLastFindDialog->Left = Left + EditorMemo->Left + EditorMemo->Width / 2 - ScaleByTextHeight(this, 100);
  1361. }
  1362. FLastFindDialog->Top = Top + EditorMemo->Top + (EditorMemo->Height / 4) +
  1363. (CursorInUpperPart() ? (EditorMemo->Height / 2) : 0) - ScaleByTextHeight(this, 40);
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. void __fastcall TEditorForm::StartFind(bool Find)
  1367. {
  1368. UnicodeString Text = EditorMemo->SelText;
  1369. TFindOptions Options;
  1370. Options << frShowHelp;
  1371. if (Text.IsEmpty())
  1372. {
  1373. Text = WinConfiguration->Editor.FindText;
  1374. }
  1375. TFindDialog * Dialog = Find ? FFindDialog : FReplaceDialog;
  1376. if (FLastFindDialog && Dialog != FLastFindDialog && FLastFindDialog->Handle)
  1377. {
  1378. FLastFindDialog->CloseDialog();
  1379. }
  1380. FLastFindDialog = Dialog;
  1381. if (!Text.IsEmpty())
  1382. {
  1383. FLastFindDialog->FindText = Text;
  1384. }
  1385. FReplaceDialog->ReplaceText = WinConfiguration->Editor.ReplaceText;
  1386. if (WinConfiguration->Editor.FindMatchCase)
  1387. {
  1388. Options << frMatchCase;
  1389. }
  1390. if (WinConfiguration->Editor.FindWholeWord)
  1391. {
  1392. Options << frWholeWord;
  1393. }
  1394. if (WinConfiguration->Editor.FindDown)
  1395. {
  1396. Options << frDown;
  1397. }
  1398. FLastFindDialog->Options = Options;
  1399. if (!FLastFindDialog->Handle)
  1400. {
  1401. PositionFindDialog(false);
  1402. }
  1403. FLastFindDialog->Execute();
  1404. }
  1405. //---------------------------------------------------------------------------
  1406. void __fastcall TEditorForm::GoToLine()
  1407. {
  1408. UnicodeString Str;
  1409. if (InputDialog(LoadStr(EDITOR_GO_TO_LINE), LoadStr(EDITOR_LINE_NUMBER), Str))
  1410. {
  1411. int Line = StrToIntDef(Str, -1);
  1412. if (Line <= 0 || Line > EditorMemo->Lines->Count)
  1413. {
  1414. throw Exception(MainInstructions(LoadStr(EDITOR_INVALID_LINE)));
  1415. }
  1416. else
  1417. {
  1418. EditorMemo->CaretPos = TPoint(0, Line-1);
  1419. }
  1420. }
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TEditorForm::FormClose(TObject * /*Sender*/,
  1424. TCloseAction & Action)
  1425. {
  1426. // Preferably announce closure here as this is called from within TForm::Close(),
  1427. // so the annoucement will be synchronous (and editor manager thus
  1428. // will consider the form to be really closed and will not block
  1429. // application closure).
  1430. // However FormClose is not called when form is closed due to
  1431. // application exit, so there is last resort call from destructor.
  1432. DoWindowClose(false);
  1433. FCloseAnnounced = true;
  1434. Action = caFree;
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. void __fastcall TEditorForm::DoWindowClose(bool Forced)
  1438. {
  1439. if (FOnWindowClose != NULL)
  1440. {
  1441. try
  1442. {
  1443. FOnWindowClose(this, Forced);
  1444. }
  1445. catch(Exception & E)
  1446. {
  1447. ShowExtendedException(&E);
  1448. }
  1449. }
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. void __fastcall TEditorForm::CreateParams(TCreateParams & Params)
  1453. {
  1454. // this is called for the first time from parent's constructor.
  1455. // FFormRestored is set to false implicitly
  1456. if (!FFormRestored)
  1457. {
  1458. FInstance = FInstances;
  1459. FInstances++;
  1460. FFormRestored = true;
  1461. UnicodeString WindowParams = WinConfiguration->Editor.WindowParams;
  1462. if ((FInstance == 0) && !WindowParams.IsEmpty())
  1463. {
  1464. RestoreForm(WindowParams, this);
  1465. }
  1466. }
  1467. TForm::CreateParams(Params);
  1468. Params.WndParent = GetDesktopWindow();
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. void __fastcall TEditorForm::Reload()
  1472. {
  1473. TAutoFlag ReloadingFlag(FReloading);
  1474. if (!IsFileModified() ||
  1475. (MessageDialog(MainInstructions(LoadStr(EDITOR_MODIFIED_RELOAD)), qtConfirmation,
  1476. qaOK | qaCancel) != qaCancel))
  1477. {
  1478. if (FOnFileReload)
  1479. {
  1480. FOnFileReload(this);
  1481. }
  1482. LoadFile();
  1483. }
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. void __fastcall TEditorForm::FormKeyDown(TObject * /*Sender*/, WORD & Key, TShiftState Shift)
  1487. {
  1488. if (((Key == VK_ESCAPE) || (Key == VK_F10)) && Shift.Empty())
  1489. {
  1490. Key = 0;
  1491. Close();
  1492. }
  1493. }
  1494. //---------------------------------------------------------------------------
  1495. void __fastcall TEditorForm::SetBackgroundColor(TColor Color)
  1496. {
  1497. if (BackgroundColor != Color)
  1498. {
  1499. FBackgroundColor = Color;
  1500. UpdateBackgroundColor();
  1501. }
  1502. }
  1503. //---------------------------------------------------------------------------
  1504. void __fastcall TEditorForm::UpdateBackgroundColor()
  1505. {
  1506. TColor Color = FBackgroundColor;
  1507. if (Color == 0)
  1508. {
  1509. // double default, first our preferred default, then system default
  1510. Color = GetWindowColor(WinConfiguration->Editor.BackgroundColor);
  1511. }
  1512. ColorItem->Color = Color;
  1513. if (EditorMemo->Color != Color)
  1514. {
  1515. EditorMemo->Color = Color;
  1516. // does not seem to have any effect (nor is needed), but just in case
  1517. ForceColorChange(EditorMemo);
  1518. }
  1519. }
  1520. //---------------------------------------------------------------------------