unit UnitFrmSizeRichtext;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls;

type
  TfrmSizeRichtext = class(TForm)
    RichWidth: TRichEdit;
    Label1: TLabel;
    RichHeight: TRichEdit;
    procedure RichWidthResizeRequest(Sender: TObject; Rect: TRect);
    procedure RichHeightResizeRequest(Sender: TObject; Rect: TRect);
  private
    { Private declarations }
    frect : TRect;
    lasts : string;
    resizecount : integer;
  public
    { Public declarations }
    function SetRichtext(f : tfont; s : string) : boolean;
    property SizeRect : TRect read frect;
  end;

var
  frmSizeRichtext: TfrmSizeRichtext;

implementation

{$R *.dfm}

uses UnitFrmConfig, Math, UnitMisc;


// with scrollbars, we get the correct width
// without scrollbars, we get the correct height

function TfrmSizeRichtext.SetRichtext(f : tfont; s : string) : boolean;
var
    temp : array of ansichar;
    wd,ht : integer;
    procedure Measure(rt : TRichEdit);
    begin
        if assigned(frmconfig) then begin
            rt.width := FrmConfig.UDToolWidth.Position;
        end;

        rt.PlainText := false;
        rt.Width := FrmConfig.UDToolWidth.Position;
        rt.Height := FrmConfig.UDToolHeight.Position;

        rt.Font.Name := f.Name;
        rt.Font.size := f.size;
        rt.Text := lasts;

        rt.Font.Name := f.Name;
        rt.Font.size := f.size;
        rt.SelStart := 0;
        rt.SelLength := length(RichWidth.Text);
        rt.SelAttributes.Size := f.Size;
    end;
begin
    lasts := s;
    resizecount := 0;
    Application.ProcessMessages;


    Measure(RichWidth);
    wd := frect.width;
    Measure(RichHeight);
    ht := frect.Height;


    frect.Height := ht;
    frect.Width := wd;

    result := resizecount <> 0;
end;

procedure TfrmSizeRichtext.RichWidthResizeRequest(Sender: TObject; Rect: TRect);
begin
    inc(resizecount);
    if Assigned(FrmConfig) then begin
        frect.width := min(FrmConfig.UDToolWidth.Position, rect.Width);
//        frect.height := min(FrmConfig.UDToolHeight.Position, rect.Height);
    end;
end;


procedure TfrmSizeRichtext.RichHeightResizeRequest(Sender: TObject; Rect: TRect);
begin
    inc(resizecount);
    if Assigned(FrmConfig) then begin
//        frect.width := min(FrmConfig.UDToolWidth.Position, rect.Width);
        frect.height := min(FrmConfig.UDToolHeight.Position, rect.Height);
    end;
end;

end.
