Editor.cpp 51 KB

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