[SOLVED] TRichMemo and text colour lazarus / 31-LCL ---------------------------------------------------------------------- MarkMLl · 2024-05-20 15:18 I know that this is a bit of an FAQ, but I'm trying to strip things down to the bare minimum without any frills. I have a TRichMemo set read-only, and am adding logging-style text to the end of its Lines property. All added text will be an entire paragraph followed by a blank line, I will never be adding a partial line or attempting to append to an existing one. In order to conserve resources and maximise performance, I am periodically deleting entire lines from the start of the Lines property. The user can scroll the display, but not manipulate the content. What is the most-straightforward way of saying, at the point in the code where lines are being added, "set the colour to clSomething" such that the colour stays with the text even though lines above it are being deleted? MarkMLl ---------------------------------------------------------------------- MarkMLl · 2024-05-23 08:00 On Linux this works without further correction for the number of lines etc.: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function CurtailedAppend(lines: TStrings; const line: ansistring; var caret: TPoint;                blockText: boolean= false; limit: integer= CurtailLimit; slop: integer= -1): integer; begin  result := 0;  lines.Append(line)end { CurtailedAppend } ; ... (* Output a single line.*)procedure TFrameInfield.PaneAppend(const line: ansistring; colour: TColor= clDefault); const  hasBeenVisible: boolean= false;     (* Static variable                      *) var  caret: TPoint;  lengthBeforeAppend, deletedByAppend: integer; begin  lengthBeforeAppend := Length(RichMemoInfield.Lines.Text);  deletedByAppend := CurtailedAppend(RichMemoInfield.Lines, line, caret, true);  lengthBeforeAppend -= deletedByAppend; (* CurtailedAppend() returns the number of characters deleted (is any) from the *)(* start of the TMemo or TRichMemo. This is used to adjust the start point of *)(* the range to be coloured.                                                  *)   if colour <> clDefault then // https://wiki.freepascal .org/RichMemo#Append_mixed_color_text_at_the_end_of_the_RichMemo// This will go wrong if any lines were deleted. {SetRangeColor(Length(Lines.Text) - Length(Lines[Lines.Count - 1]) - Lines.Count - 1, Length(Lines[Lines.Count - 1]), clBlue);}   RichMemoInfield.SetRangeColor(lengthBeforeAppend, Length(line), colour); end { TFrameInfield.PaneAppend } ;  I've stripped down CurtailedAppend() there to only append a single line, under normal circumstances it would ensure that the total number of lines was less than some maximum by deleting stuff from the start and would make sure that the most-recent text remained visible. CurtailedAppend() is tested thoroughly with a TMemo. With a TRichMemo appending text with a defined colour works OK, but it deletion is allowed something goes wrong with the colouration a few lines above the insertion point. I'll provide more detail once I've stripped stuff down to a bare-bones test app. MarkMLl ---------------------------------------------------------------------- KodeZwerg · 2024-05-23 09:11 I guess I did not really understand what you try to do, adding colored lines into a richmemo, readonly, remove from time to time some lines by not change colors for other lines. Okay, all above can be simple done with those helpers: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.AddRichText(const ARichMemo: TRichMemo; const AText: string; const AFont: TFont; const ABackgroundColor: TColor);var  StartPos, EndPos: Integer;  FontParams: TFontParams;begin  StartPos := ARichMemo.SelStart;  EndPos := StartPos + Length(AText);   FontParams.Color := AFont.Color;  FontParams.HasBkClr := True;  FontParams.BkColor := ABackgroundColor;  FontParams.Name := AFont.Name;  FontParams.Size := AFont.Size;  FontParams.Style := AFont.Style;  FontParams.VScriptPos := vpNormal;   ARichMemo.Lines.BeginUpdate;  ARichMemo.SelText := AText;  ARichMemo.SelStart := StartPos;  ARichMemo.SelLength := EndPos - StartPos;  ARichMemo.SetTextAttributes(StartPos, EndPos - StartPos, FontParams);  ARichMemo.SelStart := EndPos;  ARichMemo.Lines.EndUpdate;end; procedure TForm1.AddRichBreak(const ARichMemo: TRichMemo);begin  ARichMemo.Lines.BeginUpdate;  ARichMemo.SelText := LineEnding;  ARichMemo.SelStart := ARichMemo.SelStart + Length(ARichMemo.SelText);  ARichMemo.Lines.EndUpdate;end; procedure TForm1.DelRichLine(const ARichMemo: TRichMemo; const ALineNumber: Integer);begin  if ALineNumber >= ARichMemo.Lines.Count then    Exit;  ARichMemo.Lines.BeginUpdate;  ARichMemo.Lines.Delete(ALineNumber);  ARichMemo.Lines.EndUpdate;end; use "AddRichText()" to add text at wherever the caret is. use "AddRichBreak()" to add a CRLF/linebreak wherever the caret is. use "DelRichLine()" to delete a line, index 0 based for line #1. Does that help? ---------------------------------------------------------------------- cdbc · 2024-05-23 09:43 Hi I think Mark is trying to maintain a colored 'viewport', (scrolling as I understand it)... I, for one, am following his progress  Regards Benny ---------------------------------------------------------------------- paweld · 2024-05-23 11:01 @MarkMLI: Or maybe a listbox + HTML is enough for you? see @wp's example in this thread: https://forum.lazarus.freepascal.org/index.php /topic,55971.msg416110.html#msg416110 ---------------------------------------------------------------------- MarkMLl · 2024-05-24 07:04 Quote from: cdbc on May 23, 2024, 11:43:00 amHi I think Mark is trying to maintain a colored 'viewport', (scrolling as I understand it)... I, for one, am following his progress  Regards Benny No, I'm trying to append coloured text that stays coloured from that point onwards (i.e. "henceforth") irrespective of scrolling etc. In effect, it's a "default for all new text" rather than the existing "default for everything". From what I can see, there is no provision to do that. However my code that appends and then colours does appear to work- /unless/ there is subsequent deletion from the start of the text as shown in the partial screenshot of alternating-colour blocks with a colour change after deletion has started. I'll append a demo program in a day or so when I've had time to chop things down a bit. MarkMLl ---------------------------------------------------------------------- KodeZwerg · 2024-05-24 08:25 Quote from: MarkMLl on May 24, 2024, 09:04:49 amNo, I'm trying to append coloured text that stays coloured from that point onwards (i.e. "henceforth") irrespective of scrolling etc. In effect, it's a "default for all new text" rather than the existing "default for everything".Sweet, I've understood your initial post Quote from: MarkMLl on May 24, 2024, 09:04:49 amFrom what I can see, there is no provision to do that.Sure there is, I've posted the methods that do exact what you want.  Maybe exchange the "string" with a better suiting one, eg TStrings/TStringList etc ... ---------------------------------------------------------------------- MarkMLl · 2024-05-24 09:46 Quote from: KodeZwerg on May 24, 2024, 10:25:05 amSure there is, I've posted the methods that do exact what you want.  Maybe exchange the "string" with a better suiting one, eg TStrings/TStringList etc ... Not in there /as/ /standard/ then. I'll check that out when I have time, thanks. MarkMLl ---------------------------------------------------------------------- MarkMLl · 2024-06-01 07:39 Quote from: MarkMLl on May 24, 2024, 11:46:56 amNot in there /as/ /standard/ then. I'll check that out when I have time, thanks. So what do I have to do to get that example to actually generate output? AddRichText() appears to be having no effect whatsoever. Test program attached. MarkMLl ---------------------------------------------------------------------- MarkMLl · 2024-06-01 19:07 I've tracked down my problem: when I was deleting a line at the start of the memo I was adding  Length(Lines[0])  to the number of characters I was reporting deleted, when I should have been adding  Length(Lines[0]) + 1  to allow for an internal EOL marker. The fact that an entire line was appearing with the wrong colour was an unfortunate coincidence. I've now got a single function which handles length management of either a TMemo or TRichMemo, with the final line kept in view which is what would be expected for debugging etc. output: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const  CurtailLimit= 256;                    (* Default limit and slop             *)  CurtailSlop= 32;                      (* This is a fraction since +ve         *) var  CurtailedMemoFteTimeout: integer= 90; (* Seconds                              *)  (* This is typically used to keep the total number of lines in a TMemo etc.  below some limit, so that the resources it consumes do not start to impose a  bottleneck; this should also be called regularly (say every minute) without a  lines parameter to update an internal counter. The return value is the number  of characters deleted, including line-ends.   If the blockText parameter is false then deletion is of individual lines at  the start of the memo, otherwise it continues until it reaches a blank line  assumed to indicate the end of a block or paragraph which is also deleted. If  hasBeenVisible is false no attempt is made to save and restore the caret  position, avoiding the penalty of handling an internal exception if text is  being sent to a form known to be hidden.   If the slop parameter is +ve then it indicates the fraction by which the size  is allowed to "hunt" around the limit; +1 is a special case indicating that  there should be no deletion. If the slop parameter is -ve then it is a number  of lines rather than a fraction; -1 is a special case indicating a default.*)function CurtailedAppend(const memo: TCustomMemo; const line: ansistring= #$7f;                blockText: boolean= false; hasBeenVisible: boolean= true;                limit: longword= CurtailLimit; slop: integer= -1): integer; {$define USE_TAG_FOR_TIMEOUT } const  ZeroPt: TPoint= (X: 0; Y: 0); var  caret: TPoint;  trimmedLines, halfSlop: integer;  forceToEnd: boolean= false; {$ifdef USE_TAG_FOR_TIMEOUT }   procedure setTimer(t: longword);   begin    if t = 0 then      memo.Tag := 0                     (* Zero/nil is valid                  *)    else      memo.Tag := ptruint(t << 1) or 1  (* Otherwise must not look like pointer *)  end { setTimer } ;    function getTimer(): longword;   begin    result := longword(memo.Tag >> 1)  end { getTimer } ; {$else                      } (* Do not declare a static variable for the force-to-end timer if this will be  *)(* called in the context of more than one memo.                                 *) //  timer: qword= 0;                      (* Static variable                      *)    procedure setTimer(t: longword);   begin  {$if declared(timer) }    timer := t  {$endif              }  end { setTimer } ;    function getTimer(): longword;   begin  {$if declared(timer) }    result := timer  {$else               }    result := 0  {$endif            }  end { getTimer } ; {$endif                     } begin  result := 0;  memo.Lines.BeginUpdate;  try (* Save caret position on entry, with special provision for a hidden pane to    *)(* avoid a "GetCaretPos called without handle" error.                           *)     if hasBeenVisible then      try        caret := memo.CaretPos    except        caret := zeroPt      end    else      caret := zeroPt; (* Initialise the slop and/or limit where not explicitly specified. Slop values *)(* of -1 and +1 are chosen to indicate the default and no-deletion cases since  *)(* (-1 div 2) lines is zero and (limit / +1) would result in no retained output *)(* which makes these parameter values redundant.                                *)     case Sign(slop) of      -1: if slop = -1 then            halfSlop := (limit div CurtailSlop) div 2          else            halfSlop := -slop div 2;    (* Slop was number of lines             *)       0: halfSlop := 0;       1: halfSlop := (limit div slop) div 2 (* Slop was denominator            *)     end; (* If the cursor (as distinct from scrollbar) has been placed at some position  *)(* other that the end of the displayed text then there will not be an automatic *)(* jump to the end as soon as more output arrives. However this is subject to a *)(* timeout so that if the operator is not actively investigating older messages *)(* the memo reverts to a state where it is the newer ones that are displayed.   *)     trimmedLines := memo.Lines.Count;   (* Visible for debugging                *)    forceToEnd := not (caret.Y < trimmedLines - 1);    if (not forceToEnd) and (getTimer() = 0) then      setTimer(UnixNow);    trimmedLines := 0;    try (* If the line contains (only) a character then this is a dummy operation *)(* (typically invoked by a timer) with the intention of reverting to the end if *)(* the timeout has expired. In practice, don't delete any lines from the start  *)(* if the user has scrolled up and is trying to read stuff.                     *)       if line <> #$7f then begin        if getTimer() = 0 then begin          if (slop <> 1) and (memo.Lines.Count > limit + halfSlop) then begin            while memo.Lines.Count > limit - halfSlop do begin              result += memo.Lines[0].Length + 1;              memo.Lines.Delete(0);            trimmedLines += 1;              if caret.Y > 0 then                caret.Y -= 1            end; (* If that's left us on a non-blank line then advance to the next blank line,   *)(* then one more to get rid of that as well.                                    *)             if blockText then begin              while (memo.Lines.Count > 0) and (memo.Lines[0] <> '') do begin                result += memo.Lines[0].Length + 1;                memo.Lines.Delete(0);              trimmedLines += 1;                if caret.Y > 0 then                caret.Y -= 1              end;              if (memo.Lines.Count > 0) and (memo.Lines[0] = '') then begin              result += memo.Lines[0].Length + 1;                memo.Lines.Delete(0);                trimmedLines += 1;              if caret.Y > 0 then                  caret.Y -= 1              end          end          end        end; (* Scrolling etc. behaviour above and in finally block below largely cribbed    *)(* from WatchP0x via PSTalk.                                                    *)         memo.Lines.Append(line)      end    finally      if forceToEnd or (UnixNow() - getTimer() > CurtailedMemoFteTimeout) then begin        if memo.Lines.Count > 0 then begin          caret.Y := memo.Lines.Count - 1;          caret.X := 0        end;        setTimer(0)      end    end; (* Restore caret position on exit, with special provision for a hidden pane to  *)(* avoid the overhead of a "GetCaretPos called without handle" exception.       *)     if hasBeenVisible then      try        memo.CaretPos := caret      except      end  finally    memo.Lines.EndUpdate  endend { CurtailedAppend } ;  For a TMemo it can be called like this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i (* Output a single line.*)procedure TFrameOutfield.PaneAppend(const line: ansistring); begin  CurtailedAppend(MemoOutfield, line, true)end { TFrameOutfield.PaneAppend } ;  while the code for a TRichMemo is only slightly more complex: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i (* Output a single line.*)procedure TFrameInfield.PaneAppend(const line: ansistring; colour: TColor= clDefault); var  existingTextLength: integer; begin  existingTextLength := Length(RichMemoInfield.Lines.Text);  existingTextLength -= CurtailedAppend(RichMemoInfield, line, true); (* CurtailedAppend() returns the number of characters deleted (if any) from the *)(* start of the TMemo or TRichMemo. This is used to adjust the start point of *)(* the range to be coloured.                                                  *)   if colour <> clDefault then    RichMemoInfield.SetRangeColor(existingTextLength, Length(line), colour)end { TFrameInfield.PaneAppend } ;  Performance is sufficiently good that I've not investigated appending a block as a single operation. It should be easy enough with CurtailedAppend() called only for the final line, with suitable consideration of the length parameter (the example above doesn't colour the EOL, which might slow line addition down but OTOH might speed deletion up). Hoping that is useful to somebody. MarkMLl ---------------------------------------------------------------------- cdbc · 2024-06-02 00:48 Hi Nice, good on you Mark. QuoteHoping that is useful to somebody.It is, Thanks  Regards Benny ---------------------------------------------------------------------- MarkMLl · 2024-06-05 07:19 I've edited that example function I provided with a couple more internal error checks, and to use the memo's .Tag property for a seconds timeout so that if the user has scrolled (and set the cursor) to look at an older message it will revert to displaying newly- appended messages after 2:30. That originally used a static variable (initialised constant), but that's obviously NBG if multiple memos are being used. MarkMLl ---------------------------------------------------------------------- cdbc · 2024-06-05 08:07 Hi Nifty little solution, Me Likey  Regards Benny ---------------------------------------------------------------------- MarkMLl · 2024-06-07 11:07 Quote from: cdbc on June 05, 2024, 10:07:49 amHi Nifty little solution, Me Likey  Regards Benny It appears that system colours like clGrayText can't be used in this context, although that might depend on the widget set. I've added a term to force the tag's LSB to 1 which will reduce the risk it could be confused with a reference to an object. MarkMLl ---------------------------------------------------------------------- CM630 · 2024-12-13 07:18 I tried to modify AddRichText. I have an issue with ABackgroundColour = clDefault - I cannot get the actual colour of the RichMemo. The ARichMemo.Colour returns clDefault. I tried with Brush, etc, I still do not get the actual background colour of the RichMemo. Any ideas? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure AddRichText(ARichMemo: TRichMemo; const AText: string; const AForegroundColour: TColor = clDefault; const ABackgroundColour: TColor = clDefault);var  StartPos, EndPos: Integer;  FontParams: TFontParams;begin  StartPos := ARichMemo.SelStart;  EndPos := StartPos + Length(AText);    FontParams.Color := AForegroundColour;  FontParams.HasBkClr := True;  if ABackgroundColour = clDefault    then FontParams.BkColor := clWhite //I do not know how to handle this    else FontParams.BkColor := ABackgroundColour;  FontParams.Name := Graphics.GetFontData(ARichMemo.Font.Handle).Name;  FontParams.Size := Round((- Graphics.GetFontData(ARichMemo.Font.Handle).Height * 72 / ARichMemo.Font.PixelsPerInch));  FontParams.Style := Graphics.GetFontData(ARichMemo.Font.Handle).Style;  FontParams.VScriptPos := vpNormal;  ... end; ---------------------------------------------------------------------- MarkMLl · 2024-12-13 12:56 Quote from: CM630 on December 13, 2024, 08:18:36 amI tried to modify AddRichText. I have an issue with ABackgroundColour = clDefault - I cannot get the actual colour of the RichMemo. The ARichMemo.Colour returns clDefault. I tried with Brush, etc, I still do not get the actual background colour of the RichMemo. Any ideas? I don't think this is really related to the remainder of this thread, other than that Quote...that might depend on the widget set. I suggest starting a separate thread, with a title that specifically asks how to recover the /actual/ colour of something identified as one of the "specials", i.e. clDefault etc. However my own suspicion is that this will be heavily dependent on the widget set, including obviously the extent to which a control is implemented by an underlying widget rather than being lovingly handcrafted. MarkMLl