Editor.cpp 51 KB

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