[Solved] Shell controls sorting rule (CompareText vs. AnsiCompareText) lazarus / 31-LCL ---------------------------------------------------------------------- d7_2_laz · 2022-11-25 13:52 I think about for certain use cases to use more the Shell Controls instead of self written  stuff. Because it's easy, slim and fast to use without much overhead. Nowadays even with builtin system icons ... Actually i stumble across two things though. One is this small one: Regarding folders as well as files, differently from common used file explorers / windows items beginning with underbar ("_") are sorted at the end, not at the beginning: I noticed that because i'm using the underscore oftenly to bring some items in a certain attention: __savedVersions _tempStuff Work1 I'd suggest that the comps follow the established sorting rules, eg. shown by Windows explorer, or others. On the other hand: for the shell listview i assume that using the OnCompare callback resp. some customsort rules possibly could customize that on app level- But: the shell treeview does not expose such an OnCompare, right?? It seems to use "CompareText" and this returns: CompareText ('a', 'b')    -1  (negative value) 'a' is smaller thand 'b' CompareText ('_', 'b')    30  (positive value) '_' is greater than 'a' Rrenark: AnsiCompareText instead would deliver the desired result. I don't know if it can ssen as a good solution.  but at least it does met the expectation (i tried it with the ShellViewEx demo that was contributed times ago within the forum (fantasic demo!). That uses self-coded "GetFiles" (virtual paradigm, OwnerData) for to gain speed. And it exposes a sort routine that i could adapt and test. However, AnsiCompareText seems to slowdown the process here, as i could see (nearly doubled speed loss) . A conditional usage of this function does solve that effect sufficiently. 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 Compare(Item1, Item2: Pointer): Integer;var FileData1: PFileData; FileData2: PFileData; S1, S2: String;begin  FileData1 := PFileData(Item1);  FileData2 := PFileData(Item2);  if (FileData1^.FIsDir = FileData2^.FIsDir) then begin        S1 := FileData1^.FName;        S2 := FileData2^.FName;        if ((Pos('_', S1) > 0) Or (Pos('_', S2) > 0)) then           Compare := AnsiCompareText(S1, S2)        else           Compare := CompareText(S1, S2);  end  else    Compare := Ord(FileData2^.FIsDir) - Ord(FileData1^.FIsDir)end; But how to apply that sort override to the shell treeview? ---------------------------------------------------------------------- d7_2_laz · 2022-11-25 16:19 For the ShellTreeView, it would work just as expected, if the function FilesSortAlphabet would be changed as: 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 FilesSortAlphabet(p1, p2: Pointer): Integer;var  f1, f2: TFileItem; S1, S2: String;begin  f1:=TFileItem(p1);  f2:=TFileItem(p2);  // Replace:  //Result:=CompareText(f1.FileInfo.Name, f2.FileInfo.Name);  // By:  S1 := f1.FileInfo.Name;  S2 := f2.FileInfo.Name;  if ((Pos('_', S1) > 0) Or (Pos('_', S2) > 0)) then     Result := AnsiCompareText(S1, S2)  else     Result := CompareText(S1, S2);end; (when FileSortType is set to  fstAlphabet) ---------------------------------------------------------------------- wp · 2022-11-25 16:25 Quote from: d7_2_laz on November 25, 2022, 02:52:09 pmi'm using the underscore oftenly to bring some items in a certain attention: __savedVersions _tempStuff Work1I do that too, and find it very convenient. However, this seems to be windows-only. When I look at these folder from a VM with Linux I see a different sort order in the file managers which simply ignores the underscores (see attachment). So, we must be careful to not change the default order people are accustomed to. Therefore, I am afraid that hacking the FilesSortAlphabet function is not an allowed option. TShellTreeView has built-in sorting, defined by the FileSortType = (fstNone, fstAlphabet, fstFoldersFirst). For the latter two cases, the files are sorted in the implementation-only procedure GetFilesInDir. This procedure uses an internal TList to store the relevant data of each file in an instance of a TFileItem class containing the SearchRec and the base path. Sorting uses the pointers to these objects as arguments in the compare functions. The problem is that TFileItem is an internal class and cannot be accessed from outside the unit. Therefore, it is not possible to extend TFileSortType by some fstCustom option and give GetfilesInDir an additional optional CompareFunc parameter... That was my first idea. I am afraid that all other solutions will require deeper changes in the ShellTreeView internals. ---------------------------------------------------------------------- d7_2_laz · 2022-11-25 18:33 Yes, i understand these points (and feared this a bit). So even no chance to open the access to  this function incl. TFileItem for a class helper? Tthat wouldn't change any existing behaviour, but could give an app a chance to modify it. (I'd guess it's rather not possible and i'd need to patch the shellctrls.pas each time) ---------------------------------------------------------------------- wp · 2022-11-25 21:44 Ignoring the compare function which you'd have to write anyway, here's a one-liner to sort the nodes of the shelltreeview in your preferred way: 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 TForm1.TreeViewCompare(Node1, Node2: TTreeNode): Integer;var  fn1, fn2: String;begin  fn1 := Node1.Text;  fn2 := Node2.Text;  if ((Pos('_', fn1) > 0) or (Pos('_', fn2) > 0)) then     Result := AnsiCompareText(fn1, fn2)  else     Result := CompareText(fn1, fn2);end; procedure TForm1.ShellTreeView1Expanded(Sender: TObject; Node: TTreeNode);begin  Node.CustomSort(@TreeViewCompare);end; Keep ShellTreeView.FileSortType at fstNone to avoid duplicate sorting. ---------------------------------------------------------------------- d7_2_laz · 2022-11-27 09:52 Sorry wp for my late response! (I'd been out yesterday) Curios. I recently had noticed a forum article ("ttreeview and customsort") where the call to such function was triggered by a button click. But i could not imagine why and how this should replace the builtin sort when binding the call to an event. Rather, that would add a second, "corrective" sort on top of the builtin sort (time consuming ..). So i didn'r pursue such approach. Seems i needed a final push (yours! Thanks!) to try out how that really behaves in practice. Results: - seen functionally it works fine - for "normal" populated folders: no noticeable slowdown at all on top caused by the additional sorting. Absolutely very acceptable here! - for "highly" populated folders (my standard test: Windows\WinSxS): a noticeable slowdown on top (approx 180 ms) disturbs - Moreover: at the second expand (expand, collapse, expand again): the same delay happens again (although not necessary because the node is already populated and wll sorted) So far: hmm. For file system oriented components i don't like unnecessary speed losses, so here i'd rather prefer to "continue patching". Sigh ... I thought about to restrict the conditions for the call (= not at a subsequent expand; only if a need could be expected). And ended up to try this "paranoia version" which does the job quite well at least in my specifc environment: 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 TfMain.ShDirTree1Expanded(Sender: TObject; Node: TTreeNode);begin  //Node.CustomSort(@TreeViewCompare);  if Node.Count > 1 then   // else not possible or needed     if (Pos('_', Node.Items[Node.Count -1].Text)) = 1 then  // Typically for highly populated folders this condition won't be met. Unless somebody invents windows system folders starting with "_" ......        Node.CustomSort(@TreeViewCompare);end; What do you think? Is it reasonable to recommend such an approach for those who are accustomed to see sorting "sindows-like"? ---------------------------------------------------------------------- wp · 2022-11-27 11:17 Quote from: d7_2_laz on November 27, 2022, 10:52:42 amBut i could not imagine why and how this should replace the builtin sort when binding the call to an event. Rather, that would add a second, "corrective" sort on top of the builtin sort (time consuming ..).That's why I wrote to keep FileSortType at fstNone which avoids the primary sort during collecting the files. Quote from: d7_2_laz on November 27, 2022, 10:52:42 amI thought about to restrict the conditions for the call (= not at a subsequent expand; only if a need could be expected). And ended up to try this "paranoia version" which does the job quite well at least in my specifc environment: 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 TfMain.ShDirTree1Expanded(Sender: TObject; Node: TTreeNode);begin  //Node.CustomSort(@TreeViewCompare);  if Node.Count > 1 then   // else not possible or needed     if (Pos('_', Node.Items[Node.Count -1].Text)) = 1 then  // Typically for highly populated folders this condition won't be met. Unless somebody invents windows system folders starting with "_" ......        Node.CustomSort(@TreeViewCompare);end;But this works only when the name of the last file in the list starts with an underscore. This can't be true in general. '~', for example, is after the underscore in the ASCII character set, and often is used for temporary files... Quote from: d7_2_laz on November 27, 2022, 10:52:42 amWhat do you think? Is it reasonable to recommend such an approach for those who are accustomed to see sorting "sindows-like"?Of course you can do what you want. But I would not like to have it in the official ShellTreeView because the windows-like sort order does not apply to all users. I think the correct way would be to find a way to add the possibility of some custom sort to the file collection procedure (GetFilesInDir), i.e. provide a new TFileSortType fstCustom and a custom compare function. ---------------------------------------------------------------------- d7_2_laz · 2022-11-27 13:34 Quoteto keep FileSortType at fstNone Yes, right ... I'd lately removed the "FileSortType := fstAlphabet", but during the tests it had been still there. My fault. Changes a lot regarding the primary sort .. Quotethis works only when the name of the last file in the list starts with an underscore Yes, i'm aware. Therefore the somehow sceptical wording "my specifc environment". I'd seen here folders starting with "." or "$", but those were uncritical. - I'd thought about, for a short moment, for such cases to apply a backward lookup loop ... but, too much crude fuzzy logic. Quotea new TFileSortType fstCustom and a custom compare function Yep. of course. Would be the best solution. ---------------------------------------------------------------------- BobDog · 2022-11-28 18:28 Windows, console application. Simple program. Use the built in DOS sort. (for fun) 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  usessysutils,strutils,process; typeaos=array of ansistring;  type direction =(up,down); function filelength(filename:ansistring):longword;Var F : File Of byte;var L:longword;beginAssign (F,filename);  Reset (F);  L:=FileSize(F);  Close (F);  exit(L);end; procedure savefile(s:ansistring ;filename:ansistring);    var    fout:file;    begin    Assign(fout,filename);    Rewrite(fout,length(s));    blockwrite(fout,s[1],1);    close(fout);  end;      procedure loadfile(var content: ansistring;filename:ansistring);   Var Fin : File;   Var x:longint;   begin   x:=filelength(filename);   setlength(content,x);   Assign (Fin,filename);   Reset (Fin,x);   BlockRead (Fin,content[1],1);   close(fin);end;  function sort(s:array of ansistring;d:direction):aos;varcd,cmd,t:ansistring;s2: ansistring='';res:array of ansistring=nil;j:int32;tot:ansistring='';de lim:ansistring=chr(13)+chr(10);begin    t:='';    cd:=getcurrentdir;  for j:= low(s) to high(s) do tot:=tot+s[j]+delim;//chr(13)+chr(10);      savefile(tot,cd+'\templist.txt');    if (d=down) then    cmd:= 'SORT.exe /r '+ cd + '\templist.txt /o ' +cd +'\result.txt'     else   cmd:= 'SORT.exe ' + cd + '\templist.txt /o ' +cd +'\result.txt' ;       runcommand (cmd,t);   loadfile(s2,cd+'\result.txt');   res:=s2.split(delim);    DeleteFile(cd+'\templist.txt');    DeleteFile(cd+'\result.txt');   exit(res);end;  //------------------------//function dir(path:ansistring;flag:ansistring):ansistring;  var ans:ansistring=' ';  begin  RunCommand('c:\windows\system32\cmd.exe', ['/c', 'dir /'+flag+' '+path], ans);  exit(ans);  end; procedure CreateAmixedString(var a:aos;maxlen:int32); function range(f:integer;l:integer):integer ;begin    range:=  random(1000000) mod (l-f+1) + f ;end; function mixcases:byte;var i:integer;begin i:=range(97,122); if random(10)<5 then i:=i-32; exit(i)end; vari,l:int32;beginsetlength(a,maxlen);   for l:=0 to maxlen-1 do   begin   for i:=1 to 50 do a[l]:=a[l]+char(mixcases);   begin   a[l]:=midstr(a[l],1,range(10,49)); // make different lengths   if random(10)<1 then a[l]:='_'+a[l];   end;   end;     writeln('strings created, now sort ''em');end; vara:aos=nil;ans:aos=n il;l:int32;maxlen:int32=30;s:ansistring='';delim :ansistring=chr(13)+chr(10); beginrandomize;writeln('Creating a mixed case string array of ',maxlen,' elements');CreateAmixedString(a,maxlen);  ans:=sort(a,up);for l:=low(ans) to high(ans)-1 do writeln(l,'  ',ans[l]);writeln('------------------');s:=dir(GetCurrentDir ,'b');ans:=s.split(delim); ans:=sort(ans,down);for l:=low(ans) to high(ans)-1 do writeln(l,'  ',ans[l]);writeln('Press return to end');readln;end. ---------------------------------------------------------------------- d7_2_laz · 2022-11-29 09:24 BobDog, thanks! I'll try it out asap! Just as info, for the moment this (minimal modified) workaround does for me the job well for to reduce the overhead of calling an additional corrective node sort.  - A workaround, not more, but actually it does help me out. 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 TShDirtreeFilelist.ShDirTree_Expanded(Sender: TObject; Node: TTreeNode);var p: Integer;begin  //Node.CustomSort(@TreeViewCompare);  if Node.Count > 1 then begin     //if (Pos('_', Node.Items[Node.Count -1].Text)) = 1 then     p := Pos('_', Node.Items[Node.Count -1].Text);     if p <> 1 then        p := Pos('~', Node.Items[Node.Count -1].Text); // Other candidates may follow, But it's only a workaround ...     if p = 1 then        Node.CustomSort(@ShDirTree_NodeCompare);  end;end; function TShDirtreeFilelist.ShDirTree_NodeCompare(Node1, Node2: TTreeNode): Integer;var fn1, fn2: String;begin  fn1 := Node1.Text;  fn2 := Node2.Text;  if ((Pos('_', fn1) > 0) or (Pos('_', fn2) = 1)) then     Result := AnsiCompareText(fn1, fn2)  else     Result := CompareText(fn1, fn2);end; ---------------------------------------------------------------------- wp · 2022-11-29 23:34 Just committed a new version of shellctrls which supports custom sorting in the tree (https://gitlab.com/freepascal.org/lazarus/lazarus /-/commit/cbf44a384b4788d6e87697db20b04fef80d979ba). When ShellTreeView.FileSortType is fstCustom a user-defined compare function should be provided - it will be used for sorting while files and directories are collected (if it is not given no sorting is applied). This compare function is defined by the new property OnSortCompare which two TFileItem arguments and must return a negative value when the first fileitem is smaller, a positive value when the first item is larger, or zero when both fileitems are equal (as usual...). TFileItem is an auxiliary class used during item collection and has been moved from the implementation part to the interface part of the 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 type  TFileItem = class(TObject)  private    FFileInfo: TSearchRec;    FBasePath: String;  public    isFolder: Boolean;    constructor Create(const DirInfo: TSearchRec; ABasePath: String);    property BasePath: String read FBasePath;    property FileInfo: TSearchRec read FFileInfo write FFileInfo;  end; Here is a typical file item compare function, as preferred by d7_2_laz: 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 TForm1.SortCompareUnderscore(Item1, Item2: TFileItem): integer;begin  // Make sure that folders are moved to the top  Result := ord(Item2.isFolder) - ord(Item1.isFolder);  if Result = 0 then    if (pos('_', Item1.FileInfo.Name) = 1) or (pos('_', Item2.FileInfo.Name) = 1) then      Result := AnsiCompareText(Item1.FileInfo.Name, Item2.FileInfo.Name)    else      Result := CompareText(Item1.FileInfo.Name, Item2.FileInfo.Name);end; I am attaching a small test project containing the built-in sort methods (none, by name, folders first) as well as three custom sort methods (preferring underscore char, by size, by date). Note that this projects works only with the recent gitlab main branch! Sorting by date reminded me that the ShellListView is lacking a date column... ---------------------------------------------------------------------- d7_2_laz · 2022-11-30 09:56 It works. Fantastic! Wow! That does give enormous flexibility for all,who likes it each differeny! From my side very huge thanks! -- About the listview / additional date column: yes. i noted that too, but would not have opened a topic here (about add. column options) for not to bore.  As it's easily solvable with a helper class. I had that already in my wrapper class, as well as access to the OnCustomDrawItem (as i don't like the darkblue backgrounded caption selection markers). I don't open a new topic here about (promised), but for info i add a small code excerpt snippet. I mention that because i had read the belonging article in the german newsgroup and had been really surprised that i did _not_ encounter those resize recursive repaint issues that are mentioned there. Attached a small text file with the stuff that i added resp was needed to be changedr (ie. within GetFiles). -  A column sort is not yet herein, i'm still starting. ---------------------------------------------------------------------- d2010 · 2024-10-05 10:13 Quote from: BobDog on November 28, 2022, 07:28:18 pmWindows, console application. Simple program. Use the built in DOS sort. (for fun) 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 usessysutils,strutils,process; typeaos=array of ansistring;  type direction =(up,down); function filelength(filename:ansistring):longword;Var F : File Of byte;var L:longword;beginAssign (F,filename);  Reset (F);  L:=FileSize(F);  Close (F);  exit(L);end; procedure savefile(s:ansistring ;filename:ansistring);    var    fout:file;    begin    Assign(fout,filename);    Rewrite(fout,length(s));    blockwrite(fout,s[1],1);    close(fout);  end;      procedure loadfile(var content: ansistring;filename:ansistring);   Var Fin : File;   Var x:longint;   begin   x:=filelength(filename);   setlength(content,x);   Assign (Fin,filename);   Reset (Fin,x);   BlockRead (Fin,content[1],1);   close(fin);end;  You can check the file-operations with Code: [Select]    {$I-}       blockread(Fin, inbuf, sizeof ( inbuf ), readpos );     {$I+}     IF ( ioresult <> 0 ) OR ( readpos = 0 ) THEN writeln('I Read Failed'); Code: [Select]Var tranfile:system.file; Function TranOpen(exew:word;Const FileName:string):integer; Begin   Assign (tranfile, FileName);   filemode := 0;  {$I-}   reset (Tranfile, 1 );   {$I+}   Result:=IORESULT; End;  Begin   if (TranOpen(1053,'E:\100\Ladrian2024\avicow\SMPlayer\docs\smtube\Co pying.txt ')<>0) then    Writeln('OpenFile error, user by other application exe'); End. ---------------------------------------------------------------------- jipété · 2025-01-27 10:48 Hello everybody, and happy new year ! I notice a really strange bug : the project cannot find a well known folder ! I'm working with Linux Debian 12.9 and FPC 3.2.2 / Laz 3.6, and when I start the project (just customized the ExpandSignType and ExpandSignColor of the ShellTreeview) with the ShellTreeview.root set as /usr/share/fonts (with or without the trailing "/") the window is nicely displayed but when I click on the "by name" option, the project crashes : 1st img, line 1159 in ShellCtrls (1158 in yours, I've just added "Dialogs," in the uses, for ShowMessage below) : 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     begin    if not FileExistsUtf8(CurrentNodePath) then        Raise EShellCtrl .CreateFmt(sShellCtrlsSelectedItemDoesNotExists,[CurrentNodePath]);    if Assigned(Anode.Parent) then        FShellListView.Root := GetPathFromNode(ANode.Parent)      else        FShellListView.Root := '';    end;  end;end; 2nd img, trying to understand what's happening : 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     beginshowmessage(CurrentNodePath); // OK, I see "/usr/share/fonts"//    if not FileExistsUtf8(CurrentNodePath) then      if not FileExists(CurrentNodePath) then        Raise EShellCtrl.CreateFmt(sSh ellCtrlsSelectedItemDoesNotExists,[CurrentNodePath]);      if Assigned(Anode.Parent) then        FShellListView.Root := GetPathFromNode(ANode.Parent)      else        FShellListView.Root := '';    end;  end;end;Same problem, with or without "Utf8" part. 3rd img showing the good value in the tooltip, but the program doesn't find it (why ?), so crashing... I dunno what to do. Best regards, ---------------------------------------------------------------------- wp · 2025-01-27 15:57 Please post a small project demonstrating the issue. ---------------------------------------------------------------------- TRon · 2025-01-27 16:21 Is this not due to 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 if not FileExists(CurrentNodePath) then It is after all a directory not a file ? ---------------------------------------------------------------------- jipété · 2025-01-28 11:02 Quote from: wp on January 27, 2025, 04:57:28 pmPlease post a small project demonstrating the issue. It is the shelltreeview_custom.zip as found in https://forum.lazarus.f reepascal.org/index.php/topic,61347.msg462091.html#msg462091. Just replaced the last begin-end part of the original procedure TCustomShellTreeView.DoSelectionChanged; with this one : 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 TCustomShellTreeView.DoSelectionChanged;...    beginshowmessage(CurrentNodePath); // OK//      if not FileExistsUtf8(CurrentNodePath) then // commented out for test      if not FileExists(CurrentNodePath) then // but same bad result        Raise EShellCtrl.CreateFmt(sShellCtrlsSelectedItemDoesNotExists,[Curre ntNodePath]);      if Assigned(Anode.Parent) then        FShellListView.Root := GetPathFromNode(ANode.Parent)      else        FShellListView.Root := '';    end;  end;end; and then, after reading the TRon post, simply comment out the 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 if not FileExists(CurrentNodePath) then line and add below 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 if not DirectoryExists(CurrentNodePath) then // new, betterNow it runs OK but with strange results : after F9 I see one ShowMessage with the ShellTreeview.root string but anywhere else I click I don't see other ShowMessage. If I click on 6_fonts_Vista folder, I don't see a sorted result. If I ask Linux to sort by name in the pcmanfm ExplorerFile, of course the result begins with calibri.ttf (bottom of img, "6_fonts_Vista"), but it is not or badly sorted in the top window ("Form1") from shelltreeview_custom.zip. Quote from: TRon on January 27, 2025, 05:21:04 pmIt is after all a directory not a file ? I remember that sentence, "in Linux everything is file". After all, a directory is just a special file, isn't it ? Regards, ---------------------------------------------------------------------- wp · 2025-01-28 12:52 Now I can reproduce the issue. I am on Windows, though, with some chance that things may be different. But the issue seems to be that the root node is not detected as a directory which forced the code into the file branch of the "if". I'd ask you to try the following modification in TShellTreeNode.IsDirectory, and to report back: 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 TShellTreeNode.IsDirectory: Boolean;begin  Result := (Owner.GetFirstNode = self) or ((FFileInfo.Attr and faDirectory) > 0);   // Added "(...) or"end; ---------------------------------------------------------------------- TRon · 2025-01-28 14:11 Quote from: jipété on January 28, 2025, 12:02:16 pmQuote from: TRon on January 27, 2025, 05:21:04 pmIt is after all a directory not a file ? I remember that sentence, "in Linux everything is file". After all, a directory is just a special file, isn't it ? Yes and no  But, to be fair, the behaviour for FPC changed over the years. It is now required to use the functions FileExists and DirectoryExists as intended. ---------------------------------------------------------------------- wp · 2025-01-28 15:11 Quote from: wp on January 28, 2025, 01:52:37 pm... try the following modification in TShellTreeNode.IsDirectory... I think now that this is just a workaround without solving the real issue. TShellTreeView creates nodes of its own type, TShellTreeNode, which contain the searchrecord (FileInfo) found during populating the tree. The problem is that there are places in the code where the searchrecord is not assigned to the TShellTreeNode.FileInfo, and this happens when custom sorting is active and the root node is not the root of the file system. As "real" fix please make the following modifications Add a new method CreateRootNode to the private section of TCustomShellTreeView and implement it as follows belowCall it in TCustomShellTreeView.SetRoot, .SetFileSortType, and .SetOnSortCompare to replace the currently used RootNode := Items.AddChild(nil, APath), and remove the following assignments to TShellTreeNode(RootNode) since they are already contained in CreateRootNodeCode: 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 TCustomShellTreeView.CreateRootNode(const APath: string): TTreeNode;var  dirInfo: TSearchRec;begin  Result := Items.AddChild(nil, APath);  TShellTreeNode(Result).SetBasePath('');  FindFirstUTF8(APath, faAnyFile, dirInfo);  TShellTreeNode(Result).FFileInfo := dirInfo;  FindCloseUTF8(dirInfo);  Result.HasChildren := True;  Result.Expand(False);end; procedure TCustomShellTreeView.SetRoot(const AValue: string);...    //Add a node for Root and expand it (issue #0024230)    //Make FRoot contain fully qualified pathname, we need it later in GetPathFromNode()    FRoot := ExpandFileNameUtf8(FRoot);    //Set RootNode.Text to AValue so user can choose if text is fully qualified path or not    RootNode := CreateRootNode(AValue);  end;  if Assigned(ShellListView) then    ShellListView.Root := FRoot;end; procedure TCustomShellTreeView.SetFileSortType(const AValue: TFileSortType);...    else    begin      RootNode := CreateRootNode(FRoot);      if ExistsAndIsValid(CurrPath) then        SetPath(CurrPath);    end;  finally    EndUpdate;  end;end;    procedure TCustomShellTreeView.SetOnSortCompare(AValue: TFileItemCompareEvent);...    else    begin      RootNode := CreateRootNode(FRoot);      if ExistsAndIsValid(Currpath) then        SetPath(CurrPath);    end;  finally    EndUpdate;  end;end; I am not sure about the consequences of the SetRoot "Set RootNode.Text to AValue so user can choose if text is fully qualified path or not" since the "AValue" used in SetRoot has been replaced by the fully qualified root path in SetFileSortType and SetOnSortCompare. Filed a bug report https://gitlab.com/freepascal.org/lazarus/lazarus/-/issues/41373 ---------------------------------------------------------------------- jipété · 2025-01-28 18:49 Hi ! I can't answer your request because your code relies on a function that I don't have: ExistsAndIsValid, and yet I just upgraded to Laz 3.8. I don't know what to do. ---------------------------------------------------------------------- wp · 2025-01-28 19:22 Where do you need ExistsAndIsValid? You cannot apply the bugreport patch to Laz 3.8 because it depends on Laz/main, but you can follow the verbal description. Here are the new CreateRootNode method (which you should declare in the private or protected section of TCustomShellTreeView), as well as the fully patched SetFileSortType and SetOnSortCompare methods (which you just copy over the existing ones). There is no immediate need to patch SetRoot (I just included it in my patch because it contains duplicated 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 TCustomShellTreeView.CreateRootNode(const APath: string): TTreeNode; TCustomShellTreeViewvar  dirInfo: TSearchRec;begin  Result := Items.AddChild(nil, APath);  TShellTreeNode(Result).SetBasePath('');  FindFirstUTF8(APath, faAnyFile, dirInfo);  TShellTreeNode(Result).FFileInfo := dirInfo;  FindCloseUTF8(dirInfo);  Result.HasChildren := True;  Result.Expand(False);end; procedure TCustomShellTreeView.SetFileSortType(const AValue: TFileSortType);var  RootNode: TTreeNode;  CurrPath: String;begin  if FFileSortType=AValue then exit;  FFileSortType:=AValue;  if (([csLoading,csDesigning] * ComponentState) <> []) then Exit;  CurrPath := GetPath;  try    BeginUpdate;    Items.Clear;    if FRoot = '' then      PopulateWithBaseFiles()    else    begin      RootNode := CreateRootNode(FRoot);      if ExistsAndIsValid(CurrPath) then        SetPath(CurrPath);    end;  finally    EndUpdate;  end;end; procedure TCustomShellTreeView.SetOnSortCompare(AValue: TFileItemCompareEvent);var  RootNode: TTreeNode;  CurrPath: String;begin  if TMethod(AValue) = TMethod(FOnSortCompare) then    Exit;   FOnSortCompare := AValue;   if (([csLoading,csDesigning] * ComponentState) <> []) or (FFileSortType <> fstCustom) then    Exit;   CurrPath := GetPath;  try    BeginUpdate;    Items.Clear;    if FRoot = '' then      PopulateWithBaseFiles()    else    begin      RootNode := CreateRootNode(FRoot);      if ExistsAndIsValid(Currpath) then      SetPath(CurrPath);    end;  finally    EndUpdate;  end;end; With these changes the bug is gone in Laz 3.6. But make a backup copy of the shellctrls.pas file before changing it. ---------------------------------------------------------------------- jipété · 2025-01-29 09:14 Quote from: wp on January 28, 2025, 08:22:48 pmWhere do you need ExistsAndIsValid? Yesterday, see yesterday.png Quote from: wp on January 28, 2025, 08:22:48 pmyou can follow the verbal description. dunno where to get that. Quote from: wp on January 28, 2025, 08:22:48 pmWith these changes the bug is gone in Laz 3.6. or 3.8 but I cannot apply the changes, my Lazarus 3.8 complains about ExistsAndIsValid. see ExistsAndIsValid.png Quote from: wp on January 28, 2025, 08:22:48 pmBut make a backup copy of the shellctrls.pas file before changing it. As usual. My original shellctrls.pas version 3.8 has 54513 bytes, the one I find here https://gitlab.com/freepascal.org/lazarus/lazarus/- /blob/b1d3af8d2155442a1fda2ffa1d04c5f00c711a2c/lcl/shellctrls.pas has 59341 bytes. So I tried to replace mine with this one from gitlab, still bugged... On the 1137 line I get a SigSegv. See sigsegv.png Maybe I must apply the lines from your last post ? Well, shellctrls.pas is a nightmare ! and version control is a disgrace... ---------------------------------------------------------------------- wp · 2025-01-29 10:04 shellctrls.pas is not a nightmare. The problem is that I (working with Laz main) included the neighbouring line around the patch locations to help you find the location to be changed, and these neighbouring lines (if ExistsAndIsValid) are not available in Laz 3.8. I installed a fresh Laz 3.8 and patched the shellctrls.pas for you. Just unzip the attachment and copy the unit over its original in folder lcl of your Laz 3.8 installation. ---------------------------------------------------------------------- jipété · 2025-01-29 10:58 Quote from: wp on January 29, 2025, 11:04:58 amI installed a fresh Laz 3.8 and patched the shellctrls.pas for you. Just unzip the attachment and copy the unit over its original in folder lcl of your Laz 3.8 installation. Thanks for your efforts. Now it works. But in the Lazarus way, that is to say that the one holding the mouse does not understand the results displayed, for example, the sorts "by Name" and "custom (by size)" return the same results, when there are only folders. If there are also files, ok, they are sorted but just on the left, not on the right, in the Listview, where it would be useful to find the size if we have chosen a sort by size, for example. Have a nice day.