TForm Create problems lazarus / 31-LCL ---------------------------------------------------------------------- mtanner · 2017-11-04 14:59 I have an app with a number of non-autocreate forms. I have a puzzling bug which I cannot seem to make headway on, so I am looking for guesses/pointers/clues on what to look for. So I have a form defined as TabcForm, and in my app I do var ABC:TabcForm. ... ShowMessage('trace 1'); ABC:=TabcForm.Create(Main);  { where Main is the main window of the app) ShowMessage('trace 2'); procedure TabcForm.FormCreate(Sender); begin     ShowMessage('trace 3'); .. For some forms this works fine, but for others I get "trace 1", but not "trace 2" or "trace 3". I have other forms in the app for which this method works, and another app in which it works all the time. Obvioulsy I have tried to find what differences there are between the forms, but cannot find anything. So any inspired guesses, or suggestions on where to look, gratefullt received. The code is too large to put on here. ---------------------------------------------------------------------- FTurtle · 2017-11-04 15:56 Is there something between these two lines: ? 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 ABC:=TabcForm.Create(Main);  { where Main is the main window of the app)ShowMessage('trace 2');  Go to Events tab and ensure that "FormCreate" in "OnCreate". P.S. I hope wrong comment is only at forum. ---------------------------------------------------------------------- Thaddy · 2017-11-04 16:04 Same as I think: Create forms with owner ---------------------------------------------------------------------- mtanner · 2017-11-04 17:09 I should have explained better.   The FormCreate event is in the "correct" place. The code fragment above it is somewhere else. Basically think of there being a button on the Main form with associated code that tries to create the form with the code fragment. I've done everything I can think of to find out what is going wrong - at the moment I'm building a test form, very simple, that gets created as above. This works ok, so I'm thinking of obscure bugs in the code that does the application functions within the created form, and gradually putting code in the test form tp check out the linkages between the forms and various data structures in my app. Experience suggest it will eventually turn out to be something really stupid or obscure on my part, but it's taking much longer than usual to track this think down.. I have to confess I'm still on XP - in process of moving everything to later Windows, but still using XP because I'm converting stiff from Delphi6/TeeChart for which I need XP. So I suppose that does raise the possibility of Lazarus/FPC being incompatible with XP, though it's working fine with a lot of other very similar code. And then why would the Create fail on some forms but not others? For the record I'm using Lazarus #1.6.4, FPC 3.0.2, SVN 54278. ---------------------------------------------------------------------- FTurtle · 2017-11-04 17:27 1. Lazarus has not any problem with Windows XP. 2. Use debugger. Set breakpoint on line "ABC:=TabcForm.Create(Main);" and go thru code via F7/F8. ---------------------------------------------------------------------- Blaazen · 2017-11-04 17:31 Forms should be created with CreateNew: 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 ABC:=TabcForm.CreateNew(Main); ---------------------------------------------------------------------- FTurtle · 2017-11-04 18:02 Quote from: Blaazen on November 04, 2017, 06:31:22 pmForms should be created with CreateNew: 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 ABC:=TabcForm.CreateNew(Main); Only in case of form created by clean code without designer. ---------------------------------------------------------------------- jamie · 2017-11-04 21:56 Are you freeing previous instants of the form before re-using same instant variable?  I guess you could implement the Close Event and set it to caFree to make sure but still its possible you can over creating?  have you tried HeapTrc (heap Trace)? that is in the project options under debug.  When you exit your app, it should report all memory blocks reclaimed.  If not, you are not freeing your forms and possibly over creating. ---------------------------------------------------------------------- mtanner · 2017-11-05 08:03 Thanks for those comments. Would appreciate some clarification on CreateNew vs Create. My understanding is that CreateNew is required for forms not designed in the form designer. Presumably CreateNew builds resources for the form. My forms are all designed in the form designer and have a lfm file. I then take them out of auto-create and delete the declaration of the form variable that Lazarus adds. I don't think it is over-creating. I get the problem of first create of the problem form(s) after starting the application. I will check the heap trace, but my program structure for creating/deleting files has worked for quite a while, so I think it's ok. I had a look at the lpi file for any clues. The form that gives me trouble is in unit number 199. Made we wonder if there is any significance or practical limit to the number of units in a Lazarus app. ---------------------------------------------------------------------- FTurtle · 2017-11-05 11:28 Quote from: mtanner on November 05, 2017, 09:03:11 amWould appreciate some clarification on CreateNew vs Create. My understanding is that CreateNew is required for forms not designed in the form designer. Yes, right. QuotePresumably CreateNew builds resources for the form. Not exactly in that way. In pas file for form made in designer you can see line: 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 {$R *.lfm} This line puts you lfm file to resources. When you call Create, constructor try to find in resources this file and create appropriate components. If this file not in resoures you will get error. CreateNew not trying to find any resources and just create empty form and all components will created only by your code. QuoteMy forms are all designed in the form designer and have a lfm file. I then take them out of auto-create and delete the declaration of the form variable that Lazarus adds. It is a good approach. QuoteI had a look at the lpi file for any clues. The form that gives me trouble is in unit number 199. Made we wonder if there is any significance or practical limit to the number of units in a Lazarus app. I didn't hear about such limits. ---------------------------------------------------------------------- mtanner · 2017-11-06 21:20 I am still struggkibg with this problem, If I use CreateNew instead of create then the form does get created and I can display it. Of course all the controls are missing from it, so it's not a solution, just a clue. Does this mean the somehow the lfm file is screwed up? How can I check an lfm vile for validity? I am also getting a little confused over form names. I thought that each window in an application had to have a unique name, so I have been assigning unique names when I create the forms. But I see there are posts saying do not change the form name except in the Designer. I need to create multiple instances of the same form. I'd appreciate clarification. I did remove the assignment of unique names, just leaving the Designer-assigned name. Windows did not complain but the main problem persists. ---------------------------------------------------------------------- howardpc · 2017-11-06 22:09 You basically have two choices: Create forms which have .lfm resources with Application.CreateForm()Create resourceless forms with CreateNew()Option 1 is the normal RAD route. Lazarus creates all your forms for you (via Application.CreateForm() calls which it adds in the .lpr), and the Designer creates .lfm resources for all such automatically created forms (i.e. both for the default Form1, and for any further forms you generate via File->New Form). You can tweak this option via the Project Options's Forms page which lets you specify which forms will be auto-created. If you have a lot of forms, you might not want or need all of them created at start-up, and so you can create some of them by manual calls to Application.Createform() only at the time you need them. Lazarus generates and manages each .lfm file corresponding to its form unit file as you drop controls on forms and move them/delete them etc. This management all happens automatically in the background, and the .lfm is always kept in sync with the form unit file (unless you edit the .lfm outside the IDE and break the synchronisation). Option 2 lets you create any form (with the possible exception of the main form) entirely in code, with no .lfm resource at all associated with such dynamically created forms. This is a far more verbose option, since you have to duplicate creation of all the controls you want on your form, and setting all their properties, parentage and positioning entirely in code (you are basically duplicating manually what Lazarus does for you automatically  when it reads a form .lfm file as the template for the form's subcomponent creation and placement). Although in theory you have a further option to create forms via calls to e.g. TForm2.Create(), it is not a route I would recommend since you do not seem to understand fully the complexities of form creation and form resource management. Using Application.CreateForm() together with form resource management via .lfms is a much safer option for you, since then all your forms are managed by the Application, and you will not have to worry about when or how to free your forms. The Application instance will take care of it for you. And the IDE will ensure your .lfm files are always valid. ---------------------------------------------------------------------- Mike.Cornflake · 2017-11-06 23:22 Quote from: mtanner on November 04, 2017, 03:59:59 pmShowMessage('trace 1'); ... ABC:=TabcForm.Create(Main);  { where Main is the main window of the app) ShowMessage('trace 2'); procedure TabcForm.FormCreate(Sender); begin     ShowMessage('trace 3'); .. Only reason I can think that you never saw "Trace 2" is that an exception was raised.  Do you have debug info on?  Maybe you're suppressing the exception, but not handling the consequences correctly (Try Except).  With Debug Off, you're not even seeing the exception in the debugger.  I know, I know.  Seems highly unlikely.  The truth is I'm clutching at straws, no real idea why you're not seeing "trace 2". One reason I can think that you are not seeing "Trace 3" is that the FormCreate event hook has dropped off.  Check in the Object Inspector, ensure that the FormCreate event is still hooked to the FormCreate procedure Are you using Form Inheritance?  I've had a few irritatingly erratic issues with the FormCreate and FormDestroy events dropping off when I use Form Inheritance.  In my case I'm bending a few rules, using a form in a shared Package as the base of my descended forms which are in the project.  Given the IDE does not support this (File - New... does not list forms in Packages), I've not raised this as an issue. The workaround I've adopted is to use good old fashioned Constructors and Destructors instead of events.  They're still there for TForm, but are not public.  Up in Protected from memory. So, if you're using Form Inheritance and bending the same rules I am, try switching to using Constructor Create/Destructor Destroy instead of the FormCreate/FormDestroy events.... Oh, I also see FormCreate and FormDestroy drop out when I use TFrames, and again I've reverted to using Constructor/Destructors there.  Again, I'm using Form Inheritance with my frames, and my base frame is in that same shared package... But I'm at a loss why you're not seeing 'trace 2' ---------------------------------------------------------------------- engkin · 2017-11-07 01:13 Guessing! Are you creating these forms inside some event of another form where this event will be called during its creation, like OnCreate or OnAfterConstruction... etc. for instance? TForm.Create lands in: 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 TCustomForm.Create(AOwner: TComponent);begin  GlobalNameSpace.BeginWrite;  try    CreateNew(AOwner, 1); // this calls BeginFormUpdate, which is ended in AfterConstruction...  finally    GlobalNameSpace.EndWrite;  end;end;  GlobalNameSpace.BeginWrite will wait until the previous object call GlobalNameSpace.EndWrite which will not happen. This explains why using CreateNew did work and did not seem to have this problem. CreateNew does not call GlobalNameSpace.BeginWrite. ---------------------------------------------------------------------- FTurtle · 2017-11-07 04:37 Quote from: mtanner on November 06, 2017, 10:20:55 pmHow can I check an lfm vile for validity? Main menu/Tools/Check LFM File in Editor. Quote from: mtanner on November 06, 2017, 10:20:55 pmI am also getting a little confused over form names. I thought that each window in an application had to have a unique name, so I have been assigning unique names when I create the forms. But I see there are posts saying do not change the form name except in the Designer. I need to create multiple instances of the same form. I'd appreciate clarification. You should not touch Name at runtime. LCL will do it on its own. When you will create new instanses of TabcForm, names automatically will be changed to: abcForm, abcForm_1, abcForm_2, ... Quote from: mtanner on November 06, 2017, 10:20:55 pmI did remove the assignment of unique names, just leaving the Designer-assigned name. Windows did not complain but the main problem persists. It is good time to stop generate theories and do one of two (or both) things: 1. Show more code. 2. Use debugger and go thru code step-by-step. How to do it: 1. Set breakpoints in interesting places. For this click on gutter. You will get red line. Set first breakpoint on "ShowMessage('trace 1');" 2. Run program and press necessary buttons. 3. Program will paused on breakpoint. Next executing line will pointed by green arrow. 4. Go thru code with or without entering to procedures via F7/F8. ---------------------------------------------------------------------- mtanner · 2017-11-07 07:38 Lots here for me to digest, thanks for all this. I do understand the role of lfm files, and I never edit them, hardly ever look at them. I have, as suggested, tried "Check LFM file in editor", and it seems ok, giving the message "Classes and properties exist. Values were not checked". I hve been using a prpogram structire that creates files dynamically for some time with no problems. Forms are desighed in Desoigner, taken out of auto-create, form variable deleted. Then when the form is needed iut it created by Tabc.Create(Main).  The form may, at some other point in the app, get deleted.  Note I have been using TabcForm.Create(Main) and not CreateForm. What is the difference, apart from syntax and first CreatreForm window becoming main form? I have other forms, apart from the one giving this problem, that get created in exactly the same way (99% same actual code, obviously calling a different formclass.Create). These other forms behave the way I want, with no problems. There was one thing I did regarding the LFM file for the problem form that may be relevant.  This is a big app, with many different forms. For each form there is the PAS and LFM files, plus some application PAS files concerned with application calculations, drawing a chart, and arranging controls on the form. I decided to put all the files for the problem form in a sub-folder. So I created a sub-folder, then moved (Windows Explorer) the files to the sub-folder. I then removed the files from the app (since the app would still be expecting them in the main folder) and added them (from the sub-folder) to the app. I cannot be sure if this exactly coincided with the appearance of the problem, but it was around that time. I have since reversed this to put all the files back in the main folder for the app. I would have thought that *.lfm in the forms PAS file would pick up the LFM as long as it was in the same folder, but maybe there is more to it? I shall review all the advice so far, await repliesd regarding  CreateForm vs Create and sub-folders. Then my plan is to rebuild the problem form, under another name, copying across the controls. My thinking is that this will give me a "clean" LFM file. ---------------------------------------------------------------------- mtanner · 2017-11-07 07:57 Just a snipped. Application.CreateForm(TabcForm,AbcForm); produces the same behavior as AbcForm:=TabcForm.Create(Main); ---------------------------------------------------------------------- mtanner · 2017-11-07 08:17 Another snippet. The forms are created in the OnClick methods for either TSpeedButtons or TMenuItems. I don't think it's accurate to say I am guessing. I am comparing code that does not work with code that works. The first statement that is different between work/fail code is the Create being for different forms, and that is the statement in which the program hangs. There is also the evidence that the problem form used to work, and (in the famously unbelievable words of programmers everywhere) I do not think I've changed the code for the problem form. I have tried putting a break-point on the Create, and yes it breaks there, but then I cannot display anything useful. Debugger is on. I admit to being ignorant about Lazarus debugging facilities. My experience is that I have very few problems with the "infrastructure" of forms and event handling. My apps are rather complicated scientific/engineering apps, very mathematical. They also tend to be highly iterative, so any debugger-like tracing typically produces tsunamis of breaks/data, because my bugs tend to be hundreds or thousands of iterations into the same (very long) loops of code for an optimisation or simulation algorithm, so I need to hand-craft debugging, usually with If ... ShowMessage.  Not elegant, but effective for me. So I am definitely an amateur when it comes to trying to get useful stuff out of breakpoints. ---------------------------------------------------------------------- mtanner · 2017-11-07 08:33 To howardpc. Your comments are very interesting. I would certainly agree that designing a form with the Designer and using LFM files is the best way, and I thought I was doing that. I've written a lot of stuff in Delphi, and I think only once did I (successfully) build a form from scratch via code, creating all the controls. Something to do only when there is a compelling reason, which is hardly ever in my experience. ( I thinbk it was to display warnings from within a DLL). I've been using Form2:=TForm2.Create() for ages, with no problems. I am not even sure now why I started using this, and not Application.FormCreate Possibly I though that, if TForm2 is a "sub- form" to TForm1, making sense ony while TForm1 exists (and ShowModal not being appropriate), then by coding Form2:=TForm2.Create(Form1) then Form2 would get cleaned up automatically when Form1 was deleted. Otherwise Form2 might hang around until the application was terminated. ---------------------------------------------------------------------- FTurtle · 2017-11-07 09:17 Quote from: mtanner on November 07, 2017, 08:38:42 amWhat is the difference, apart from syntax and first CreatreForm window becoming main form? I don't see any pluses for use Application.CreateForm for coding by hands. Minuses: 1. Owner is always Application. You may need assign as Owner some particular form. 2. Application.CreateForm call virtual constructor Create(AOwner: TComponent)    You may need use other constructor. 3. Application.CreateForm may mask gross errors when using global variables.    a) Global variables better to avoid as much as it possible.    b) Better get error instantly instead long-long searching later. Quoteand sub-folders. Rule number one when begins some strange after copying, renaming, updating and etc.: Run once Build instead Compile. And always, before "some strange" will begin: You should clean folders from any old copies of souces and compiled files before compile something. I dont know how in Lazarus, but in Delphi good practice was to close all files opened in editor. Avoid situation when exist few files with same name in different directories. Avoid existing of few copies of same directory at same time. After renaming ensure that file with old name not exist. ---------------------------------------------------------------------- FTurtle · 2017-11-07 20:43 Suggestion: In line "ABC:=TabcForm.Create(Main);" do Ctrl-Click on "TabcForm" (or choose "Find declaration" in context menu). Did you've jumped in right place? ---------------------------------------------------------------------- engkin · 2017-11-08 00:10 Quote from: mtanner on November 07, 2017, 09:17:04 amI don't think it's accurate to say I am guessing. If you are responding to my post, then there is a misunderstanding. I meant that is me guessing. ---------------------------------------------------------------------- mtanner · 2017-11-09 10:52 Still strggling withg this. IUt boils done to TabcForm.Create(Main) fails (though not with all the various forms in my app) TabcForm.CreateNew(Main) works which suggest something to do with the lfm file, though I cannot find any problems with the lfm file. Current straw at which I am grasping is that I have {$mode objfpc) in some modules though not all, so am currently going through making sure all modules have {$mode objfpc}. I have also constructed a skeleton form with no controls, which creates ok. I plan to add controls to this skeleton to see what makes the create fail. ---------------------------------------------------------------------- mtanner · 2017-11-09 13:52 I have some more definite information now. For the skeleton form, with no controls, TabcFor..Ceate(Main) works ok. Still works if OI add a TTabControl to the form. When I add a TChart to the form, the Create fails. So the problem is with TChart. ---------------------------------------------------------------------- mtanner · 2017-11-09 14:16 And on checking the other forms in the app, it does appear that the ones which cause Create to fail have a TChart, and those without a TChart seem to Create ok. On the other hand, another app with the same structure, forms with TCharts do Create ok. Also I built a simple demo app, a main form and two secondary (not auto-create) forms. The main form has two buttons,which each crate one of the secondary forms. Bitg secondary forms Create ok. I put a TChartmnon one of the secondary forms, and it still both Create ok. So it looks like I am doing something to my TCharts which prevents the containing forms being Create-d ok. And in one of may apps and not the other. Again, any suggestions would be gratefully received. ---------------------------------------------------------------------- FTurtle · 2017-11-09 15:25 Which OS and version of Lazarus do you use? ---------------------------------------------------------------------- mtanner · 2017-11-09 15:59 From an earlier post: I have to confess I'm still on XP - in process of moving everything to later Windows, but still using XP because I'm converting stuff from Delphi6/TeeChart for which I need XP. So I suppose that does raise the possibility of Lazarus/FPC being incompatible with XP, though it's working fine with a lot of other very similar code. And then why would the Create fail on some forms but not others? For the record I'm using Lazarus #1.6.4, FPC 3.0.2, SVN 54278. Note that the problem app used to work ok. not sure what I've done to make it fail. And another similar app works ok. So I suspect it is some characteristic of the TCharts, or something about packages in use, maybe order of packages even. ---------------------------------------------------------------------- mtanner · 2017-11-10 14:18 I am beginning to think this problem is about strings. The unit TAChartAxisUtils has H+, so that in the declaration of TChartAxisMarkToTextEvent          String means AnsiString If I have a form unit with {$mode objfpc) and no H command then          String means shortstring and an OnMarkToText procedure declaration generated by the form designer will then be declared effectively with a shortstring parameter in which the user modified text will be returned. So presumably the TChart code will take this shortstring returned value and try and use it, effectively typecast it, into an ansistring. So an access error is unsurprising. If this analysis is correct then the problem is not one of creating the form, it is becaus I have changed the mode statement. The lesson is, I suppose, allways use $H+ at the top of form units, and be aware that TChart parameters should be assumed to be ansostrings. (I have allways used shortstrings in my apps. They are sufficient for my purposes, and don't give heap reference difficulties. Seems I no longer have that luxury of string simplicity.)