[solved--so far]Scrollbox -- why are controls not drawn in the order created? lazarus / 31-LCL ---------------------------------------------------------------------- indydev · 2024-07-16 23:06 I have a Lazarus client that interacts with several different AI models. Questions and Responses are placed on TPanels in a TScrollbox. Loading sessions that have more than 4 TPanels begin to be displayed out of order (different from how they are created and assigned to the scrollbox), though not always.  The more TPanels the greater the chance of this "out of order" display. (See attachments: second one is the out of order display). Is the drawing method for TScrollbox threaded? Is there a way for me to force the drawing order of the TPanels? ---------------------------------------------------------------------- Martin_fr · 2024-07-16 23:16 How to you create the panels? Do you set the "Top" by hand? Or do you alTop? Or...? One way may be to add them with AnchorSides. Then you can specify to which panel they should anchor (setting AnchorSide.Control). Another may be to set the parent up to do "ChildSizing". And the one panel per row. Then they will be kept in the order in which they were created (I don't know how well that works with a scrollbox / or if you need an extra layer...) ---------------------------------------------------------------------- indydev · 2024-07-16 23:32 Ok. Yes I calculate the Top, by the bottom of the previous control. I'll look into using Anchors. ---------------------------------------------------------------------- indydev · 2024-07-17 17:07 No improvements to this issue after trying several different ways to get at it. However, I am able to isolate more precisely when this happens. First some code to show what I tried (not all my attempts): 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 // TDiscssionPanel is an extension of TPanel and is in my Discussion unit.constructor TDiscussionPanel.Create(AOwner: TComponent; DText: string; DTop: integer);begin  inherited Create(AOwner);  Self.Parent := AOwner as TWinControl;  Self.Top := DTop;    // added this if block after posting about the problem in this forum but no change in results.   if Parent.ControlCount > 1 then  begin    Self.AnchorSide[akTop].Control := Parent.Controls[Parent.ControlCount-2]; //assign sibling    Self.AnchorSide[akTop].Side := asrBottom;  //anchor top side to bottom of sibling  end;   Self.Align := alTop;   // some settings (Panel background colors etc.) removed for conciseness. end:  The DiscussionPanel Constructor method is called from the main form unit: 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.CreateTxtDisplay(AText: string);var  newDiscussionPanel:TDiscussionPanel;  newTop: Integer;begin  if Scrollbox1.ControlCount = 0 then newTop := 0     else newTop := Scrollbox1.Controls[Scrollbox1.ControlCount-1].Top +                  Scrollbox1.Controls[Scrollbox1.ControlCount-1].Height;  try    // Create a new Discussion Panel    newDiscussionPanel := TDiscussionPanel.Create(Scrollbox1, Atext, newTop);  except    on E: Exception do    begin      newDiscussionPanel.Free;      raise;    end;  end;end;  Other attempts included adding a "wait" flag to the TScrollbox in my (already existing) helper unit and setting it on when a call to create a TDisucssionPanel is made and not calling another create method until it is off.  ...but, when do you turn it off? Turning it off at the end of the CreateTxtDisplay procedure didn't change anything. Turning it off at the end of the TDiscussionPanel.Create method itself, didn't change anything. Turning it off in the OnPaint method of the TDiscussionPanel created an infinite loop. With all of that said, this problem ONLY occurs on loading a session that has more than 4 panels AND when they do not fit in the ScrollBox display window.  If I make the Form full screen, I can get more panels fitting in the ScrollBox. If they all fit this issue does not occur. If I shrink the Form and reload, the problem reccurs. If the Panels load fine, no problems occur on redraws of the ScrollBox from resizing, changing visibility etc. Adding Panels during a session doesn't create any problems (but they are added one at a time so not surprising). Edit: In my previous response I indicated that I didn't set any alignment. Although I calculate the Top of the panel myself, I did already set the alignment. Removing my calculation makes the situation worse--they never load in order (Top to bottom, but some mishmash of bottom to top). ---------------------------------------------------------------------- wp · 2024-07-17 17:30 See attached mini project which works for me (tested on Windows and Linux). But note: you will run into a "Position overflow error" when the total height of all panels exceeds the SmallInt maximum (32767) - when you add "many" panels this limit is reached faster than expected... ---------------------------------------------------------------------- indydev · 2024-07-17 17:54 Maybe my description doesn't describe better what is happening. See the attached images.  My panels are loading from a database and each panel needs to convert Markdown text (of varying complexity) into the appropriate display. Your example works because you are adding one panel at a time (by a button), and your panels have nothing in them. My panels work fine in that situation as well. Edit: I can see how my description could be misleading. When I load a session, I call into a database and grab the Markdown, a loop calls the CreateTxtDisplay procedure until all the messages from the session are loaded. Each panel has to add the converted Markdown Text (done prior to creating the Discussion Panel) into the Display. Thus the Panels can get pretty complicated. ---------------------------------------------------------------------- wp · 2024-07-17 18:20 A modified version of the demo in which random text is added to the panel along with an icon, and in which multiple panels can be added - panels are added in order. ---------------------------------------------------------------------- VisualLab · 2024-07-17 22:02 Quote from: indydev on July 17, 2024, 01:06:58 amI have a Lazarus client that interacts with several different AI models. Questions and Responses are placed on TPanels in a TScrollbox. Loading sessions that have more than 4 TPanels begin to be displayed out of order (different from how they are created and assigned to the scrollbox), though not always.  The more TPanels the greater the chance of this "out of order" display. (See attachments: second one is the out of order display). Is the drawing method for TScrollbox threaded? Is there a way for me to force the drawing order of the TPanels? If there are a lot of these panels, the program will load RAM and CPU quite heavily (TPanel is a class derived from TWinControl, which is quite extensive). In the screenshot shown, you can see that each section contains a frame with text and a small simple raster graphic. Maybe a better solution would be to create a simple class derived from TCustomControl that would draw subsequent sections, one below the other. The difficult part would be writing the code to handle vertical scrolling of the content. ---------------------------------------------------------------------- indydev · 2024-07-17 22:03 Thank you for your example. After playing with your example, cutting out part of my code and inserting yours, here is what I found. Without calculating the top of the panel the panels always display from the bottom to the top. I don't know why that is. It does not matter if I always set Top to 0 or to High(SmallInt), the panels display from the bottom up. If I use your example outside of my code, it displays top to bottom. If I calculate the top (i.e. use DTop) and use your example code (cutting out my display calculations etc.) I get the result you see in your example.  But this tends to confirm my position that the calculations are taking too long, causing the drawing to happen out of order. My previous posting of the code stripped out what I thought would be unnecessary. Here is the full code block in all of its ugliness: 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 constructor TDiscussionPanel.Create(AOwner: TComponent; DText, KyWord: string;  DTop, MLeft, MWidth, SgNum: Integer; CodeBlock, Q, Err: Boolean; const Pics: TBmpRecord);const  border = 8;begin  inherited Create(AOwner);  Self.Parent := AOwner as TWinControl;  Self.Align := alTop;  Self.Top := DTop; //High(SmallInt);    BevelOuter := bvNone;  if Q then Color := TColor($00544644) else Color := TColor($00413534);  ParentBackground := False;  ParentColor := False;  FIsQuestion := Q; FUsePics := Pics.Use;  FPanelNum := Parent.ControlCount - 1;  FSegNum := SgNum;   case KyWord of       'EQ':begin              BlockType := btEquation;              CreateEquation;            end;    'TABLE':begin              BlockType := btTable;              FisCodeBlock := FALSE;              CreateTable(MLeft, MWidth, DText);            end;   'StdTxt':begin              BlockType := btText;              CreateDialogue(MLeft, MWidth, DText);            end;       else begin            BlockType := btCode;            FCodeKeyword := KyWord;            FIsCodeBlock := CodeBlock;          CreateCodeBlock(MLeft, MWidth, Q, DText);       end;   end;   FError := Err;   // Create and configure the agent picture  if UsePics then begin    AssignPics(Pics);    Self.OnPaint:=@PaintHandler;  end else Self.OnPaint:=@PaintHandler2;   Self.OnResize:=@Resize;  Self.OnClick:=@SelfClick;  Self.OnMouseMove:=@SelfMouseMove;  Self.OnMouseDown:=@SelfMouseDown;  Self.OnMouseUp:=@SelfMouseUp;end; Each block calls another method constructor based on the content needed to be displayed (which includes a highly customized TRichMemo control). While it doesn't seem slow when I run it, there is a significant amount of processing going on. At this point I don't expect anyone to 'Debug' my code, as it gets extensive. I believe I am stressing the display process. The problem I have does not always appear, but it appears more than 50% of the time, and it only appears upon loading the session messages into the ScrollBox.  I will continue to work on it until I either solve it or have something more concrete to question. Thanks to Martin_fr and wp for responding. Edit: I posted before seeing your response VisualLab. Iterative coding is a death nail   Will consider your advice. ---------------------------------------------------------------------- indydev · 2024-07-17 22:08 Quote from: VisualLab on July 18, 2024, 12:02:18 amThe difficult part would be writing the code to handle vertical scrolling of the content. ...yeah, need to figure out how that would be done? ---------------------------------------------------------------------- Martin_fr · 2024-07-17 23:09 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  Self.Align := alTop;  Self.Top := DTop; //High(SmallInt); Have you tried swapping those 2 lines? Having multiple alTop is always a bit dangerous. Afaik/IIRC, They are sorted by whatever "top" position they have before the alTop overrides the position, but then I don't know, if the next one is sorted according to the new Top of the already aligned one.... So you may have to set value to Top that are further out than expected. The other thing to do is to do a DisableAllAutosing on the parent container before setting them. Otherwise, if you do more than one, they will keep adjusting while you still are adjusting them => and that ain't no good. Though I wonder, when you used/tried AnchorSide.Control... Did you remove the alTop then? Because if you didn't, then the alTop may take precedence. Otherwise the AnchorSide would force position (you then need to set the parent control as AnchorSide for Left/Right to have the width being done. Having seen you access parent.controls[parent.controlcount-1] => Just the obvious remainder: You don't use any "BringToFront" or similar on the panels? Because afaik that changes there order in the list of Controls. (But again, not sure) ---------------------------------------------------------------------- Martin_fr · 2024-07-17 23:14 Not necessary related to your issue, but how many such sub-panels are you talking about? Because if it is in the hundreds, you might get Windows to freak out. I did once a test with a plain form (non LCL, directly created via Windows API, so everything was Windows API only). I did put around 300 or 400 buttons or panels on that form.  And at some point Windows froze... It' long aga, but IIRC it froze completely (my entire Desktop) for maybe 10 secs. (That was Windows 10, not sure if other Versions do that do, or if it is still like that at all)... I don't recall the exact details, but Windows does have limits... ---------------------------------------------------------------------- Martin_fr · 2024-07-17 23:32 Just one more word on the auto-sizing (including align and all else)... And it also depends on the parent having "AutoSize = True" or not. Autosizing, aligning, positioning, .... are all always done immediately. You change the parent => autosize, you change the Top or Height => Autosize (of all others that may depend), you change anchors, or align .... Unless you use DisableAutoSizing. So when you have QuoteCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   Self.Parent := AOwner as TWinControl;  Self.Align := alTop;  Self.Top := DTop; //High(SmallInt); And say the Parent has "AutoSize = True" Setting the parent, will set Top/Left = 0 => because an autosizing parent makes space... Setting alTop, then makes this the topmost alTop (because Top=0). Actually it could also be the 2nd alTop from the top, as 2 controls would have "Top := 0". The other panels will got down "Self.Top = high(smallint)" should however work.... Good question. Though: assuming it is "visible = true". Not sure what happens if it is hidden. Might be skipped. Though, again, I am not sure what happens with "top := " if align is already set. Yet, if you set it before it depends on the Parent.Autosize. Beware, above is from distant memory. I probably got some details wrong. But it may be giving some ideas at what to pay attention.... ---------------------------------------------------------------------- indydev · 2024-07-18 01:17 Wooh hoo! Tentative solution for now.  Thank you Martin_fr for asking questions. I just kept messing with it. If I remove Align:=alTop; altogether, set Left := 0;, set Width:=Parent.Width; and just handle the width adjustment in the @onPaint method I haven't been able to get the issue to arise after many attempts. As for # of DiscussionPanels, I don't know how many a user may generate. The longest I have seen is about 100, but most sessions  are around 50 or less. I may have to put some code in to split sessions up when they get really long. As for controls in the Panels themselves, it is usually a RichMemo control, but could also include a button and a label if it needs a code window, or a table. The image on the left is just a stretchDraw on the Panel itself. So probably up to 4 controls on a panel.