SOLVED! Virtual listview; validity of "Item" in "Edited" when Selection changed lazarus / 31-LCL ---------------------------------------------------------------------- d7_2_laz · 2022-04-11 12:50 Windows (10 x64), virtual listview, nultiselect.   Lazarrus 2.2, but probably earlier too. First side note: i found the observation a bit curios until i found a workaround. So i only would like to ask if it is normal. Wouldn't like to make an issue of it. Second: imo it has absolutely nothing to do with the bunch of issues around virtual listview / multiselect as recently discussed. If i remember right it had already been with 2.0.12. If appears more to be related to the order of message processing (set focus, kill foucs). Scenario: the inplace editor is open for a selected iten. Now, by click, select another item. "Item" within "Edited" now will point to the newly selected item, and not to the item just being edited. "Item" appears to be hijacked (with strange results if one relies on it. Test project attached. My question is only for understanding: is it known and is it by design? ---------------------------------------------------------------------- wp · 2022-04-11 15:00 I tested the issue with Delphi, and there the edited text always goes into the previously selected, edited item. I cannot imagine that this behaviour is intentional. You should report it as a bug (not sure if someone will pick it up, though). ---------------------------------------------------------------------- d7_2_laz · 2022-04-11 16:56 Yes, it was not with Delphi (7 in my case).  With Laz. i noticed since a longer time sporadically, strange phenomena when editing and change selection, so i did a closer look now and found it at least worthy to communicate. Happy enough that the really urgent thing(s) had been recently addressed i wouldn't like to annoy again with other issues near by (if desired i could to it of course). A workaround does exist (using a remembered item index). ---------------------------------------------------------------------- wp · 2022-04-11 18:04 It's not annoying. But if you don't report it, the risk that a bug reported in a forum post will be forgotten is quite high. ---------------------------------------------------------------------- d7_2_laz · 2022-04-12 08:56 Probably you are right wp, and it's better to register it for to make it known. Btw it differs from the behaviour of a regular listview, as: without any further code (as default action), when the editor is open and another item is clicked, - the regular listview commits the changed contents,  and selects the clicked item. The "edited" Item still points to the previous one -- ok. - the virtual listview discards the changed contents, and selects the clicked item (but the "edited" Item  points to the clicked one too  -- wrong). That may appear to be very unspectular and to be only a matter of personal flavour (which is better..). Until one starts (withiin "Edited") to do something meaningful with "Item" and has to notice that he's working with a wrong object ... So: https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/39708 ---------------------------------------------------------------------- wp · 2022-04-12 10:26 It helps for me to end editing before the listview reacts on re- gaining focus again from the editor. For this, I added the 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           // editing          if FEditor.Visible then            HideEditor; to TCustomListview.CNNotify, case LVN_ITEMCHANGED, after "if (nm^.uChanged = LVIF_STATE)". 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 ...    LVN_ITEMCHANGED:    begin      if nm^.iItem < 0 then        Item := nil      else        Item := Items[nm^.iItem];      //DebugLn('TCustomListView.CNNotify Count=',dbgs(Items.Count),' nm^.iItem=',dbgs(nm^.iItem),' destroying=',dbgs(lifDestroying in Item.FFlags));      if (Item <> nil) and (not OwnerData) and (lifDestroying in Item.FFlags) then      begin        if Item=FFocused then          FFocused:=nil;        if Item=FSelected then          InvalidateSelected;      end else      begin        if (nm^.uChanged = LVIF_STATE) then        begin          // checkbox          if Checkboxes then            DoItemChecked(Item);                    // editing          if FEditor.Visible then            HideEditor;         // focus          if (nm^.uOldState and LVIS_FOCUSED) <> (nm^.uNewState and LVIS_FOCUSED) then          begin            ...[/code[ ---------------------------------------------------------------------- d7_2_laz · 2022-04-12 11:40 Not quite sure yet .. Yes, the test project does behave correct now. Tried within the app, i got an access violation. Whcih could be solved: there was also a reference to "Selected" within the Edited callback, and it pointed to Nil.  Could be bypassed, basically no problem. Within the test project, Selected is _not_ nil (would need to dig deep why this difference, i'm using a custom inplace editor here). "Selected" points to the currently edited = previous selected item. Which is correct from the point of view of the "Edited" context. But maybe not what we would expect from the listview's overall point of view. I'd formulate the question as follows: wichin the scenario described, what do we want where "Selected" should point to now, and is it guaranteed that it has a valid contents? You might take a look applying the following line within the test project, Edited callback:      Memo1.Lines.Add('Edited: selected Item caption now is   -->  ' + ListView1.Selected.Caption); ---------------------------------------------------------------------- wp · 2022-04-12 14:06 There's certainly some ambiguity... I checked with Delphi: it fires the events in the same order as Lazarus: OnEditing - OnEdited - OnSelectItem(edited item, Selected=false) - OnSelectItem(new item, Selected=true) The only difference is that Delphi has Item=nil in the OnEditing/OnEdited events - which definitely is a bug. In fact, even Lazarus had it like this, but I had fixed this very recently in commit 9aa8b52 (April 4). You probably do not have this because this would explain your crash. ---------------------------------------------------------------------- d7_2_laz · 2022-04-12 16:41 Due to the latter issues i tested with 2.2 (containing your former prototype patch) as well as with "2.3.0" (as lazgit extract (lazarus- main.zip) from 4. Apr. plus your patches on top. Testing each time with having done full cleanup & build. And now it's somehow strange. Whereas the test project does behave ok, i get problems to transfer to the application (using the builitin listview editor here, for this test). Within the application, "item" is still the right one in "Editing". But in "Edited" i get again the next selected item, instead of the previous edited item.  I don't know why yet und need to dig, but it make take some time to find out what went wrong. Sorry for that delay! Regarding the "Selected" within "Edited": if you don't see a major problem here, it's ok for me so far. ---------------------------------------------------------------------- wp · 2022-04-12 17:33 Comitted the code shown above so that we have a common code base. ---------------------------------------------------------------------- d7_2_laz · 2022-04-12 18:34 wp thank you! For now as first quick check i verified that my (2.3.0)  customlistview.inc. Then i traced a bit up from the newly inserted HideEditor statement ... the next step executed would be Upda]"]>BlockedltiSelList. So, purely occasional, i got an idea: Yesterday i did set the "MultiSelect"  in my demo project (attached in initial post) to "false".  Only for to assure that the original issue described really has nothing specific to do with MultiSelect. Just for test now i did re-set to MultiSelect true again   -> test project does fail resp,. behaviour not fixed.  You tested against MultiSelect true too? ---------------------------------------------------------------------- wp · 2022-04-12 21:02 Ah... Maybe the solution is to follow Delphi again which does not enter edit mode at all once multiple items are selected, and this is kind of logical because it is not very clear which one of the selected items will be edited. Or maybe even all? This can be achieved by replacing TCustomListView.CanEdit by this code: 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 TCustomListView.CanEdit(Item: TListItem): Boolean;begin  Result := not (OwnerData and MultiSelect and (SelCount > 1));  if Result and Assigned(FOnEditing) then    FOnEditing(Self, Item, Result);end;This disables editing in virtual mode when more than 1 item is selected. I am aware this is inconsistent since editing of multisel items is possible in normal mode. But I don't see a way how the same behaviour could be achieved for virtual mode... At least this work-around would be less destructive than the current situation. I also tried to check how editing of secondary columns is affected, but it seems that they cannot be edited at all. Or am I missing some parameter? ---------------------------------------------------------------------- d7_2_laz · 2022-04-13 08:10 Oh .... it was meant much more trivial. Not thought here about a real multi-renaming scenario.  But i noticed that when simply setting the MultiSelect property to true, the patch did not work for my demo project (as attached at beginning of this article). _But_: now i had to notice that this is not true with your demo project That works. Yours behave correct, mine not. So i tried to narrow it down step by step where the crucial difference might be located. After some tests i thought i found the answer. Setting,  additionally, "RowSelect" to true, made my demo project work ok too. The opposite does not apply: setting RowSelect to false demo in your project does not prevent it to work. Confusing. I have no final clue now about the different behaviour of both projects regarding the patch. Unfortunately i need to do a break until later the day. ---------------------------------------------------------------------- d7_2_laz · 2022-04-13 11:04 During all that testing, i did a simple error, ouch. Here the correction: wp, in your test project (virtual_listview_editing), if you set MultiSelect to true, but set RowSelect to false, then the patch will not come into effect, right? (If yest, then the patch depends on "RowSelect", and that's not very satisfying) ---------------------------------------------------------------------- wp · 2022-04-13 12:28 Here's a new version of the test project, now extended by MultiSelect and RowSelect options and multiple columns, and I cannot see that anything is wrong with the Listview in current Laz-main. ---------------------------------------------------------------------- d7_2_laz · 2022-04-13 14:39 For to go sure. i just recreated my laz-git 2.3 environment (before i couldn't; compilation abort due to missing  unit SimpleWebSrvController, now there had been related changes, as i did see). Just i could rebuild based on zip download from here: https://gitlab.com/freepascal.org/lazarus/lazarus Ok, if i activate MultiSelect, but _not_  RowSelect), i think the patch will not get active. Doing the steps (virtual listview): Click onto  item 2 and press F2. Enter "Item 2 new".  During the inplace editor is still open, click on item 4 Expected:   Item 2 shows the caption "item 2 new".  Item 4 simply is selected. What i see: Item 2 shows the caption "Item 2".  Item 4 shows the caption "Item 2 new".   // <=== the same as without patch Now doing the same steps with "RowSelect" activated. It behaves as expected. You have a differenz result? Then something basically went wrong with my environment. ---------------------------------------------------------------------- wp · 2022-04-13 15:45 I thought I had checked this... Here's one more patch in addition to the others, except for CanEdit which can be restored: 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 TCustomListView.HideEditor;var  S: String;begin  S := FEditor.Text;  if FEditor.Item <> nil then  begin                          // add the yellow lines    if MultiSelect and OwnerData then      DoEndEdit(Items[FSelectedIdx], S)    else      DoEndEdit(FEditor.Item, S);  end;  FEditor.Item := nil;  FEditor.Visible := False;  FEditor.SetBounds(0, 0, 0, 0);end; // Replace current code by thisfunction TCustomListView.CanEdit(Item: TListItem): Boolean;begin  Result := True;  if Assigned(FOnEditing) then    FOnEditing(Self, Item, Result);end; Not committed, yet. ---------------------------------------------------------------------- d7_2_laz · 2022-04-13 16:36 Bingo! I think that's it!  That exactly does the job, on test project level as well as on application level (plus when using a TCustomListViewEditor here).  It's excellent !! ---------------------------------------------------------------------- wp · 2022-04-13 17:57 OK, committed then. ---------------------------------------------------------------------- d7_2_laz · 2022-04-13 18:34 Thousand thanks wp for your efforts to improve the listview again! ---------------------------------------------------------------------- d7_2_laz · 2022-04-15 14:41 After a couple of days using the patch i did encounter a very small, but not nice, remaining lack with the patch. That's life .. It's just the reciprocal scenario. Not changing a selection. But for the same selected item doing a repeated rename of it. One could imagine a use case like: rename an item (what might imply a somehow time consuming work , resp. waiting for an OS response when renaming a file). After that, a corrective action might happen: click onto the item, F2, change the value, press . After two or three cycles of such action the following might happen: the selection resp. the focus is lost, the inplace editor might have closed unintendedly. Additionally on application level I noticed: the listview itself sometimes appeard to have lost the focus …. And pressing an "F2" found itself to open the editor for a node of a treeview attached. One can see that somehow when using the test project as of reply #14, doing: - set property "MultiSelect" to true.  Apply something like a "sleep(100)” within "ListView1Edited" for to simulate time consuming action. - Now do a couple of times very fast:  click onto the item; press F2; change the value; do mouse click onto the item;  again press F2 etc.   I’m seeing now in a reproducable way the selection and or focus go lost. – I think it’s related to HideEditor that might work too greedy in some situations. Within customlistview.inc,  I refer to this call of HideEditor:           // editing           if FEditor.Visible then             HideEditor; Maybe it should be applied more restrictive. For to come into effect only for situations where it is needed for.  Probably not for the situation where the selection hadn't been changed. So I did try a couple of things like:           if FEditor.Visible then              if ( (  (nm^.iItem<>-1) And (FSelectedIdx<>-1) ) And (nm^.iItem <> FSelectedIdx)  ) then                HideEditor;           I did experiment with a lot of various combinations here. But none of those attempts had been very robust so far for to be considered reliable. ---------------------------------------------------------------------- wp · 2022-04-15 17:49 As usual I cannot reproduce... Please post your version of that test project modified such that the error occurs. You do give a description but there are still some possibilities how to implement it exactly (e.g. where to put the Sleep(100)). Also, please edit your message and remove the typos because the important parts are hard to understand. If you feel that the HideEditor in CNNotify is too aggressive move or copy it to other places, e.g. inside the "// focus" or "// select" parts, and test again. ---------------------------------------------------------------------- d7_2_laz · 2022-04-15 19:41 For to explain a bit why i did write this: it's like so often: you see something strange and wonder. After some time it might occur again, and one begins to search. Im my case I got aware when I dis notice that after doing “F2” the editor of the current node of a treeview opened(*). My feeling had been, oh, you did run into a defocusing problem (*) Oh yes too much typos. I'll try to avoid this and did an edit. The project as used for the test is attached. Also already tried to move the placing of "if ... then HideEditor" but had no success yet, but i'll continue. Important for the test is the sequence (done very fast):  for the same item: do mouse click onto the item, press "F2", edit the value, press   … and the same again a couple of times (the Click is a redundant action, but it might happen though).   -  “F2” alone does not raise problems At least you should see that the editor might close unintendedly. (*) Besides: I already had noticed such in my first attempts (some time before I opened this topic), where I tried to intercept the WMKillFocus of a TCustomListViewEditor and did here:    If somecondition then begin       DoExit;      // inherited; ---------------------------------------------------------------------- wp · 2022-04-15 21:33 OK, I could see now a few times that the selected item moved to the top after editing the third item. Is this the problem? But seeing your modification of the OnEdited event I think that this in issue in this event handler rather than of the TListView. You put the Sleep (the "long operation") BEFORE the assignment of the new string to the FList user structure. Since the Listview does not contain the data in virtual mode the data are kept in some kind of user structure; in case of the demo, this is the StringList FList. This is where the OnData event gets the displayed strings from. And the OnEdited handler must move the edited string back into this list. If you do a lengthy calculation before this step there's a risk that the selection may be moved to another item before that. Please put the calculation (the Sleep) AFTER FList[Item.Index] := S + subitems, and check again. (Sorry I did not think that this might be an issue when I set up the demo and put the logging code before the assignment of the new string). ---------------------------------------------------------------------- d7_2_laz · 2022-04-16 08:03 Hello wp, yes. i see this point. The reason behind why i placed, within the “Edited” event handler, the "sleep" ("lengthy operation") before the assignment to the data structure, is, that in the real use case behind it represents a file i/o which might fail (“file cannot be renamed” as it is read-only etc.). And so one doesn't want to write potentially obsolete data to the structure.  Wait for OS's response first, then write to the data .. Ok, one could write the data first, and revert afterwards if needed, that is feasible of course. However: the placement imo does not really hinder the patch to work in the main respect. Ie. when editing item_3 and clicking onto item_5 during this action  - the patch does this job fine. But: whereever the "sleep" is placed (and that happens even completely independent from this "sleep", you might remove it):  a second or third Click + F2 + edit will make the item editor disappear (close) unintendedly, just during an attempt to edit. What you additionally did see (that the selection moved to the top), appeared within my app in that way, that the focus went to another control (treeview) and via F2 the current node's editor opened. Obviously focus? selection? are lost and user interaction routed to somewhere else. I regret that i saw this side-effect so late. Hhhmm ... .  Maybe one can find a combination of various conditions for to make the HideEditor only happen when really needed and else not. But that could end up to make customlistview.inc coding partially non- intuitive and hard to maintain. The more as additional layers might occur which can influence. I’m thinking here of an app option “sort after rename” which uses ColClick which internally does an HideEditor again, showing up other effects again. Meanwhile i'm a bit doubting if it is very reasonable to take all those various situations into account which can occur in special situations. Maybe it’s better here to let it up to the programmer to find a specific solution for a specific context. Ie., for this topic. on app level it's possible, by using a remembered index of the item that is currently edited. That would fully serve all needs, but would work  only without the HideEditor call. Sigh. I'm pretty unsure what's the best manner here. What do you think? But I had to learn the hard way that one might easily enter treacherous terrain. ---------------------------------------------------------------------- wp · 2022-04-16 09:51 Some pessimistic notes: Some LCL components, in particular those with heavy interaction with the many widgetsets, have become extremely complicated. Assuming that nobody understands their inner workings in every detail, and knowing that a perfection of 100% cannot be achieved, it follows that every bug fix very likely will introduce an issue somewhere else... I'm not even sure whether adding HideEditor in the first fix of this series is correct. It does not address the root cause of the issue, namely that virtual mode cannot handle the case that another item is selected while being in edit mode. Although this is not delphi- compatible it seems that the ListView is constructed to work this way - see the behaviour in normal mode. So, ending edit mode by calling HideEditor "out of the row", may introduce other issues... ---------------------------------------------------------------------- d7_2_laz · 2022-04-16 10:30 Yes wp, i ended up to see it just in the same way. Nevertheless i see it positive in so far that helped to gain more awareness about this potential field of issues. I’d propose as a compromise simply to revert the two-liner (if … then HideEditor) and to leave it to the application specifically to deal with, which is easily possible (using a remembered item index). ---------------------------------------------------------------------- wp · 2022-04-16 22:55 I am hesitant to revert the "HideEditor" because I think the probability that a user of the virtual listview traps into the "edit the wrong line" bug (the initial concern) is much greater than the current issue with some delay in the OnEdited event. But now I found a bug which is even more severe and it happens even in the old version (before introducing "HideEditor"), even in Laz 1.8.4: Just select an item in the virtual listview and press any key (e.g. "a") - the selection jumps to the first item (Windows only). Another problem is that the behaviour is different depending on whether ListView.Selected is called in the OnEdited handler or not. What a mess! ATM, I cannot recommend using the TListview in virtual mode to anybody. ---------------------------------------------------------------------- d7_2_laz · 2022-04-17 08:18 Yes,. i already noticed that too.  Previously (i assumed a special keyboard navigation routine would be needed to be written attached to the keypress (*)), and now again actually, as you told the your selection jumped to the top of the list. My interpretation had been: ok. one thinks he's still in the editor, but in fact the editor already did close underneath, and so the key did apply to the listview, not the editor. (*) Checked against my old app (Delphi 7) how that did behave (without special coding): typing a character, it did stay on the currently selected item. If none selected, it does nothing. I'd doubt that there is a builtin mechanism here About "Selected" within "Edited" i've no clear picture yet, but i did wonder a bit why (in your demo) OnSelectItem had been called twice, the first with Selected nil resp. itemindex -1. (that's probably just the nm^.iItem = -1 see below). No real opinion yet. Meanwhile .. the matter didn't let me rest... I took a closer look at the "end editing" process and values and maybe there is a less aggressive / more specific solution that does cover the logics discussed. If you should have the time to after Easter, could you give it a short look and try? // Does relate to: https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/39708 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       // end editing      if IsEditing then        if (nm^.iItem = -1) And (FSelectedIdx<>-1) then  // specifically when item outside the editor clicked          if Not ((FFocused <> nil) And FFocused.Selected) then  // but prevent known side effect (defocusing at repeated /click/edit with Click on the same item)               HideEditor; I did already test, with special regard to the side effect, with the application some time and it did meet the expectation. I think it’s at least much more better than before If you find it promising and worthy, I would subject it to a more extensive test here. Generally, i did struggle with the virtual listview since a longer time, as you probably remember, but meanwhile i felt that the main hurdles had been resolved. There are more use cases and so more hurdles though. ---------------------------------------------------------------------- wp · 2022-04-17 11:06 Thank you. This modification works better, although it does look like a real workaround now . Seriously: Shouldn't we add an "If OwnerData" because normal mode has been working fine all the time, and this way we would restrict the range of possible side-effects? I will commit it after a few more tests. I cannot see an effect any more when ListView.Selected is called from the OnEdited handler. Still something is going on with selection. Because, when I select an item in the virtual listview, press F2, the editor box appears, flahes away, and immediately comes back. This is very clearly seen in Win 11 where the edit has a thick bright blue underline. And the "jump to first" issue is still there. Simply select any virtual listview item down the list, press any (standard) key, no edit involved, and see the selection jump to the first item. Very probably this is unrelated to the current issues because it has been there for a long time. ---------------------------------------------------------------------- d7_2_laz · 2022-04-17 13:39 Once again thousane thanks for your attention wp! - Shouldn't we add an "If OwnerData" -> Does make sense of course. -  "if (IsEditing and OwnerData)"  ? - Modification works better ->  It's certainly better than before (although presumingly not perfect), but i'd propose too to set it on a "hold until fully tested" for to be aware of any further deviations - No more effect when ListView.Selected is called from the OnEdited -> i supposed this, but it's fine to hear that it really helps here - "Jump to first" issue -> i believe it's a really different thing. Without further digging i'd assume that something like FindCaption  could be implemented Keyprss or KeyDown. Basically it think it's not much different to D7, which seems to do a "stay at current selected".  - I think it's not a bug but a not yet implemnted feature. And an implementation might not necessarily be easy (what, when typing a sequence of characters. likr "bbb"; implement the belonging sub- iteration too ? How to behave on a reversed sort order? How, if th sort order is not given by column 0, but by column 4?  Follow such sort orders, or simply find the next match downwards?   - Pess F2, the editor box appears, flahes away, and immediately comes back   -> I cannot see it here (your demo, Win 10, unfortunately i have no access to a Win 11). Is it specifically due to the "HideEditor" patch, or due to it's mdification?  Or did it occur independent from those already before? ---------------------------------------------------------------------- wp · 2022-04-17 16:13 Quote from: d7_2_laz on April 17, 2022, 03:39:36 pm- "Jump to first" issue -> i believe it's a really different thing. Without further digging i'd assume that something like FindCaption  could be implemented Keyprss or KeyDown. Basically it think it's not much different to D7, which seems to do a "stay at current selected".  - I think it's not a bug but a not yet implemnted feature. I don't think so. I would consider a built-in automatic incremental search feature to be very annoying. And Linux and mac don't have it, and normal mode neither. There is a KeyDown method which opens the editor and calls the inherited method when the key is not F2. But diving into the inherited KeyDown I am soon lost in the myriads of system messages. Beyond that, I did not see anything catching the key press. So why does the Listview select the first item? I can fix the issue by killing all "normal" keys in that KeyDown method, but this certainly is too large an impact on user code. I filed a bug report so that the issue is not forgotten (https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/39715).   Quote from: d7_2_laz on April 17, 2022, 03:39:36 pm- Pess F2, the editor box appears, flahes away, and immediately comes back   -> I cannot see it here (your demo, Win 10, unfortunately i have no access to a Win 11). Is it specifically due to the "HideEditor" patch, or due to it's mdification?  Or did it occur independent from those already before? I see it also when I compile with Laz 1.8.4. Thus, it has nothing to do with the recent modifications. ---------------------------------------------------------------------- d7_2_laz · 2022-04-18 13:45 About the "jump to top", yes i think too it's earlier than CNNotify, within the message loop. CNNotify itself will behave correct. It will receive a twofold LVN_ITEMCHANGED, the first, on the currently selected item, with iItem -1 (for deselection), and a second with iItem 0, and it is not clear, why 0 (might it be orphaned from an earlier initialization of the data structure?). Even if one tries, purely experimental, to intercept the latter (and for the first call that's not possible), the selection will jump to top. On the one hand, the question appears to be, why this doubled LVN_ITEMCHANGED is sent here (for the regular listview it is not). On the other hand: CNNotify doesn’t play a role here, it may be exited directly at the beginning and nothing changes (jumps to top). It happens earlier, right. Back to the modification of the patch. I tried it out a couple of times, and my experience is: the side-effect (= unintended closure of edit box when doing fast and repeatedly a Click / F2 / edit on the same item) in rare cases still did occur, but significantly less often. And: the very irritating effect, that with F2 the editor does open within another control (tree node), as the listview passed the focus to another control. never did happen again since having applied the patch modification. So far I was satisfied, but not fully, and asked myself, if it’s possible to intercept the remaining few deviants too. With this little addition they appear to be removed: 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           // end editing          if (IsEditing And OwnerData) then            if (nm^.iItem = -1) And (FSelectedIdx<>-1) then  // Specifically when item outside the editor clicked               if Not ((FFocused <> nil) And FFocused.Selected) then   // but prevent known side effect (defocusing at repeated /click/edit with Click on the same item)                if FSelectedIdx <> FFocused.Index then    // Eliminate remaining deviations                     HideEditor; The syntax can be more compacted of course, but I kept it as it is for better readability. ---------------------------------------------------------------------- d7_2_laz · 2022-04-19 12:31 Occasionally encounted situations where the item editor still did close unintendedly. This is a real beast. Meanwhile i'm missing ideas how to reliably intercept this. The problem is, that on item change there are each slices of deselections sent within (nm^.iItem = -1) that make it very hard, maybe impossible, to find the right hook to decide, when the editor needs to be closed and when it must not be closed. With other words: what's missing is a persistent variable that could be used to store the information about the index of the item that just is edited. (That's just the strategy of the workaround that i mentioned initially), Something like FEditedItemIndex. For instance, if i misuse - just for test - the Listview's "Tag" for to store - within Editing - the index of the item that is edited, then it would be faiirly easy enough to do later a simple compare of this variable with nm^.iItem for to decide if HideEditor has to be done because the indices differ. Easy, understandable and reliable. Every idea would be very welcome. ---------------------------------------------------------------------- wp · 2022-04-19 13:35 There's no reason why an "FEditedIdx" should not be introduced... I had attempted it myself but was lead into more desaster. But maybe I gave up too early. ---------------------------------------------------------------------- d7_2_laz · 2022-04-19 20:02 Sadly, the assumption was too optimistic, the principle is not fully transferable. Because the comparison of the indices needs to be done when nm^.iItem -1 is passed to CNNotify, otherwise, when HideEditor is done after selection is updated,  it's too late (EndEdit will point to the wrong item). But at that stage (when iItem is -1) one cannot reliably determine which will be the upcoming next index). So it seems to be the same vice versa, a dilemma. So perhaps  it's the best to stay at the version as from replay #32, as it is not fully perfect, but mostly does the job well. ---------------------------------------------------------------------- d7_2_laz · 2022-04-24 13:03 Observation on this topic: the remaining irregularities probably are related to the position of the mouse cursor. Example (using the demo project) When doing fast: Click / F2 / edit modify value /   ... repeatedly a couple of times eg. on the same item 3 (index 3), then it may happen that sometimes the mouse did move away a bit from the item 3 when pressing F2. And then: FSelectedIdx is: 3;   FSelected.Index, FFocused.Index, FEditor.Item.Index are, all uniquely identical here:  4, or 5, or .. Having inspected those values directly before HideEditor is called. And the logic does what it has been told to do (HideEditor). Because it does not have the right information available. I wouldn't have expected that. That, at the click, Selected & Co. do behave as being controlled by the mouse position. With the demo project having applied the workaround as above: Try: on item 3, press F2 and simultaneously move the mouse a little bit down, and you'll see it easily. The editor will be closed immediately (HideEditor called) although it shouldn't. That should not happen. It should be possible to move the mouse outside of the boundaries of the item when pressing F2, it's a normal gesture. The challenge here is to determine - within CNNotify/LVN_ITEMCHANGED, and here: when nm^.iItem is -1, not later - which item had been clicked. And not being falsified by mouse movements later. Had tried to to a test which remembers the item index when WM_LBUTTONDOWN is called, but had to learn that sometimes this is called later than CNNotify itself. This thing appears to be very recalcitrant. Maybe somebody has a clever idea. ---------------------------------------------------------------------- d7_2_laz · 2022-04-26 08:13 I had been still trying to find the appropriate coordinates for to decide when HideEditor should be called and when not. The last appearing caveat had been:  when moving the cursor outside the item's bounds whilst pressing F2, the coordinates are going wrong. It's a different issue, but exactly the same situation that is described here (here: concerning StartDrag). https://delphi.cjcsoft.net/viewthread.php?tid=49546 Quote"Windows sends a WM_LBUTTONDOWN message to the application, with the current cursor coordinates. In the meantime, you move the cursor to a different location. Windows interrupts the running of your application to update the position of the cursor. VCL still didn't finish processing your events." I had already tried before to solve the issue described recently by remembering the cursor position (or the item index) at WndProc / WM_LBUTTONDOWN. Unfortunately: the problem is that CNNotify sometimes arrives earlier than WM_LBUTTONDOWN. and so the relevant info arrived too late. At least using my subclassed WndProc here. So i hadn't pursue it. But after having read that article, i retried I did a restart by using a little modification within win32wscustomlistview: // win32wscustomlistview, ListViewProc: 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 // There is already a nice to use "ListItem" retrieved, so it wouldn't cost additional overhead for to apply a simple assignment:        if Msg = WM_LBUTTONDOWN then           if ListItem = nil then             ListView.Tag := -1           else             ListView.Tag := PtrInt(ListItem.Index);   // Only for proof-of-concept. Should be better something like: FClickedItemIdx or similar// Wanted to have a real variable for that, like (whatever it is named):         //FClickedItemIdx := ListItem.Index; Here, "ListView.Tag" is only used as a placeholder persistent storage just for testing, as there is no available variable yet..  It should be a F-Variable of course. And when using this information within customlistview.inc, the result is just i would have expected: straightforward and no side-effects! Does work flawlessly: // customlistview.inc: 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       // end editing      if (IsEditing And OwnerData) then        if (nm^.iItem = -1) And (FSelectedIdx<>-1) then            if Integer(Self.Tag) <>  FSelectedIdx then           // Would be nice to have something like that instead::  if FClickedItemIdx <> FSelectedIdx then                HideEditor; That's it. As it should be. No more unexpected closurese of the editor. Easy to understand. What do you think?? ---------------------------------------------------------------------- wp · 2022-04-26 08:35 Can you send me a patch relative to the current version in "main"? This thread contains many ideas for possible changes, and it's too easy to do something wrong when applying them from the description and code fragments. Never use the Tag of a component for internal purposes. It is reserved for the user. ---------------------------------------------------------------------- d7_2_laz · 2022-04-26 11:02 The tag was misused for testing purposes only as a placeholder, until there would be a basic positive feedback about the approach itself. A variable should be to be applied of course, probably within comctrls.pp. i think. I did that now. Just efetched the recent files related (comctrls.pp, win32wscustomlistview.inc, customlistview.inc) as of today from here: https://gitlab.com/freepascal.org/lazarus/lazarus/-/tree/main/lcl (Remark besides: could it be that a recent patch from you about TCustomListView.CanEdit is not yet in there ??) As i don't know the gitlab's instruments i created three patch-like diff-files generated locally with the help of WinMerge. wp, what do you think of the fix proposal? ---------------------------------------------------------------------- d7_2_laz · 2022-04-26 12:00 Late idea: within win32wscustomlistview, it wouldn't be bad to apply it to WM_RBUTTONDOWN as well..     if ( (Msg = WM_LBUTTONDOWN) or (Msg = WM_RBUTTONDOWN) )  then ---------------------------------------------------------------------- wp · 2022-04-26 15:40 Hmmm... You introduce a FClickedIdx and make a public property out of it. This means it can be set/read for all purposes. But it gets its regular value only in the win32 widget. And the reaction on the value of FClickedIdx is in common code again. My stomach tells me that this concept calls for trouble... I'd have a better feeling if we could keep all that FClickedIdx thing inside the widgetset. Here's how I would implement your idea: In win32wscustomlistview.inc there is a data record ListViewWindProcInfo which provides some intermediate storage of message data. Its elements are populated in the ListViewParentMsgHandler and the ListViewProc procedure - the latter one is the one in which you intercept the WM_LBUTTONDOWN message. So, why don't we add ClickedIdx element to that record and write the ListItem.Index to that element rather than to a new, globally available ClickedIdx property of the listview? 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 var  ListViewWindProcInfo: record    ActiveListView: TCustomListView;    NoMouseUp: Boolean;    ClickedIdx: Integer;         // <------ wp: added  end; function ListViewProc(Window: HWnd; Msg: UInt; WParam: Windows.WParam;    LParam: Windows.LParam): LResult; stdcall;...begin  case Msg of  ...    WM_LBUTTONDOWN, WM_RBUTTONDOWN:      begin        WindowInfo := GetWin32WindowInfo(Window);        ListView := TListView(WindowInfo^.WinControl);        ListItem := ListView.GetItemAt(GET_X_LPARAM(LParam), GET_Y_LPARAM(LParam));        { wp: next lines replace your code }        if (Msg = WM_LBUTTONDOWN) or (Msg = WM_RBUTTONDOWN) then          if ListItem = nil then          ListViewWindProcInfo.ClickedIdx := -1          else            ListViewWindProcInfo.ClickedIdx := ListItem.Index;  ... Now, how do we get this ListViewWindProcInfo.ClickIdx into the listview? We could add a widgetset method MustHideEditor() which returns true when that ClickedIdx is different from the SelectedIdx passed as a parameter: In Win32WSComCtrls: 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 type    TWin32WSCustomListView = class(TWSCustomListView)      ...    public    ...      class function MustHideEditor(const ALV: TCustomListView; ASelectedIdx: Integer): Boolean; override;  // <--- wp: add    end; and in win32wscustomlistview.inc: 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 class function TWin32WSCustomListView.MustHideEditor(const ALV: TCustomListview;   // <--- wp: add this method  ASelectedIdx: Integer): Boolean;begin  result := ASelectedIdx <> ListViewWindProcInfo.ClickedIdx;end; We also must define the method in the ancestor, TWSCustomListView, where it simply can return false to be ignored by all non-windows widgetsets: In WSComCtrls.pas: (folder widgets) 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 type  TWSCustomListView = class(TWSWinControl)  ...  public  ...    class function MustHideEditor(const ALV: TCustomListView; ASelectedIdx: Integer): Boolean; virtual;  // <--- wp: add  end; class function TWSCustomListView.MustHideEditor(const ALV: TCustomListView;   // wp: add this method  ASelectedIdx: Integer): Boolean;begin  Result := false;end; Now almost done... What's left is to call the new MustHideEditor method. This happens in TCustomListView.CNNotify at the place where you compare the ClickedIdx property with the SelectedIdx: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i           // end editing          if (IsEditing and OwnerData) then           if (nm^.iItem = -1) And (FSelectedIdx<>-1) then             if TWSCustomListViewClass(WidgetSetClass).MustHideEditor(self, FSelectedIdx) then   // <--- wp: replace your code by this line             HideEditor; As far as I can see, this is working. But I would appreciate if you could test this as well before I commit it (of course, I'll commit it nevertheless if you have difficulties following my description). ---------------------------------------------------------------------- wp · 2022-04-26 15:58 Quote from: d7_2_laz on April 26, 2022, 01:02:41 pm(Remark besides: could it be that a recent patch from you about TCustomListView.CanEdit is not yet in there ??) IIRC, the CanEdit modification became obsolete after a later modification in HideEditor itself. ---------------------------------------------------------------------- d7_2_laz · 2022-04-26 19:09 >>   I'd have a better feeling if we could keep all that FClickedIdx thing inside the widgetset. Yes, right .. it had really not been planned by me to see this variable as public (it simply had turned out that, as private, it was not known within ListViewProc). So my full support of your concern and the idea behind the more protective approach. For testing i replayed the well-known problematic scenarios again (demo project and app) and found it did behave just as expected. Couldn't find anything strange so far. For to go sure i'll repeat some tests tomorrow, but i believe this strange thing should be fully covered now. Congratulations for your implementation, wp! (i'd never had foound that). ---------------------------------------------------------------------- wp · 2022-04-26 20:26 The strange thing here is that the more straight-forward idea of reading the clicked index in the MouseDown method does not work because the listview seems to send the LVN_ITEMCHANGED message first, and the mouse messages come later! Mysterious Windows! ---------------------------------------------------------------------- d7_2_laz · 2022-04-27 08:09 Yes, and so no surprise that it had been so hard to find a way out the the issue we did speak about. Because within CNNotify we didn't have yet the relevant (click-)information available here, whereas the variables involved appeared to be infected by subsequent cursor positions instead. Not at all an easy situation for Lazarus resp. LCL to deal with. But i feel it gets more stabilzed step by step, so i'm optimistic. Btw about the recent patches: no news are good news here .. it's still working fine! Hopefully we don't need next time an user accessible ClickedIdx for a different scenario. So i agree with the encapsulation but have a bit mixed feeling though. ---------------------------------------------------------------------- wp · 2022-04-27 08:44 Committed the new version (https://gitlab.com/freepascal.org/lazarus/l azarus/-/commit/c0c30424debbd95c58fc9e8b98293dba55292d12); I can always revert it if something very severe appears. What is left for me is the annoying issue in virtual mode that selection jumps to the first item when a non-special key is pressed incidentally (https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/39715). One possible work-around could be to kill all non-special key presses in the ListView's KeyDown method. Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TCustomListView.KeyDown(var Key: Word; Shift: TShiftState);const  ALLOWED_VIRTUALMODE_KEYS = [VK_F2, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN,    VK_HOME, VK_END, VK_PRIOR, VK_NEXT, VK_INSERT, VK_DELETE, VK_ESCAPE];begin  if OwnerData and not (Key in ALLOWED_VIRTUALMODE_KEYS) then    Key := 0;    if not ReadOnly and (Key = VK_F2) and (Shift = []) then  begin    ShowEditor;    Key := 0;  end else    inherited KeyDown(Key, Shift);end;I don't like it, though, because this is a Windows-only issue and therefore should be fixed in the win32 widgetset. [EDIT] Here's a more widgetset-conformal solution. In lcl/interfaces/win32/win32wscustomlistview.inc, add to function ListViewProc (of course, do not modify procedure TCustomListView.KeyDown): 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 ListViewProc(...);begin  case Msg of    ...    WM_CHAR:      begin      // Prevent jumping to first item when a key is pressed in virtual mode        // Issue #39715        WindowInfo := GetWin32WindowInfo(Window);        ListView := TListView(WindowInfo^.WinControl);        if ListView.OwnerData then      begin          Result := 0;          exit;        end;      end;  ... ---------------------------------------------------------------------- d7_2_laz · 2022-04-27 11:02 That's interesting, i also had tried that Key:= 0, limited by conditions, too but didn't like it either (but mostly because with this reactice correction the positive reason- why would be still unidentified.  But i had no idea yet where to search in the hierarchy. Presumingly item- resp. selected- index is set or preinitialized with zero somewhere)  I tried the widgetset change and it does suppress the jump-to- beginning, but i don't understand yet how it works regarding the conditions  (in combination with Shift, Ctrl, ..  a char is allowed).  Currently i encounter the following caveat:  - "builtin"-keystrokes resp. common combination like Ctrl-a, Ctrl-x .... do still work  - user defined keystrokes like eg. Ctrl-s  are broken (i mean, if i define on app level that when pressing Ctrl and  "s" on an item, something specific should be done, it won't work now) I'm a bit unsure about this difference. Shouldn't all combinations with Shift, Ctrl, .. and char passed through? ---------------------------------------------------------------------- d7_2_laz · 2022-04-27 16:32 As there apparently a special rule might only concern the control key (to be verified), maybe something like this, for to alloe Ctrl  + 'char' ? 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     WM_CHAR:      ......        if ListView.OwnerData then          if (GetKeyState(VK_CONTROL) >-1) then          begin            Result := 0;            exit;          end; ---------------------------------------------------------------------- wp · 2022-04-27 18:13 Yes, seems to be better, at least. BTW, the state of the CTRL key can be extracted from the lparam of the message: https://docs.microsoft.com/en-us/windows/win32/inputdev/wm- char