Debian Codegraph @

tools/castle-editor/code/castleshellctrls.pas

raw
1 { Fork of Lazarus ShellCtrls unit with some features useful
2 for Castle Game Engine editor.
3
4 TODO: In time, we will either submit these modifications to LCL,
5 or maybe use some more custom control for file browser in CGE editor
6 -- undecided for now.
7
8 Copyright of the modifications 2019-2019 Michalis Kamburelis.
9 Copyright of the original code: Lazarus contributors.
10 The licence of ShellCtrls is the same as the license of Castle Game Engine
11 (LGPL with static linking exception).
12 }
13 unit CastleShellCtrls;
14
15 {$mode objfpc}{$H+}
16
17 {.$define debug_shellctrls}
18
19 interface
20
21 uses
22 Classes, SysUtils,
23 // LCL
24 Forms, Graphics, ComCtrls, LCLProc, LCLStrConsts,
25 // LazUtils
26 FileUtil, LazFileUtils, LazUTF8;
27
28 {$if defined(Windows) or defined(darwin)}
29 {$define CaseInsensitiveFilenames}
30 {$endif}
31 {$IF defined(CaseInsensitiveFilenames) or defined(darwin)}
32 {$DEFINE NotLiteralFilenames}
33 {$ENDIF}
34
35 type
36
37 { TObjectTypes }
38
39 TObjectType = (otFolders, otNonFolders, otHidden);
40
41 TObjectTypes = set of TObjectType;
42
43 TFileSortType = (fstNone, fstAlphabet, fstFoldersFirst);
44
45 { Forward declaration of the classes }
46
47 TCustomCastleShellTreeView = class;
48 TCustomCastleShellListView = class;
49
50 { TCustomCastleShellTreeView }
51
52 TCustomCastleShellTreeView = class(TCustomTreeView)
53 private
54 FObjectTypes: TObjectTypes;
55 FRoot: String;
56 FShellListView: TCustomCastleShellListView;
57 FFileSortType: TFileSortType;
58 FInitialRoot: String;
59 FExcludeMask: String;
60 FExcludedCount: Cardinal;
61 { Setters and getters }
62 function GetPath: String;
63 procedure SetFileSortType(const AValue: TFileSortType);
64 procedure SetObjectTypes(AValue: TObjectTypes);
65 procedure SetPath(AValue: String);
66 procedure SetRoot(const AValue: String);
67 procedure SetShellListView(const Value: TCustomCastleShellListView);
68 procedure SetExcludeMask(const AValue: String);
69 procedure RefreshContents;
70 procedure ExcludedCountChanged;
71 protected
72 procedure DoCreateNodeClass(var NewNodeClass: TTreeNodeClass); override;
73 procedure Loaded; override;
74 function CreateNode: TTreeNode; override;
75 { Other methods specific to Lazarus }
76 function PopulateTreeNodeWithFiles(
77 ANode: TTreeNode; ANodePath: String): Boolean;
78 procedure DoSelectionChanged; override;
79 function CanExpand(Node: TTreeNode): Boolean; override;
80 public
81 { Basic methods }
82 constructor Create(AOwner: TComponent); override;
83 destructor Destroy; override;
84
85 { Methods specific to Lazarus - useful for other classes }
86 class function GetBasePath: String;
87 function GetRootPath: String;
88 class procedure GetFilesInDir(const ABaseDir: String;
89 const AMask, AExcludeMask: String;
90 const AObjectTypes: TObjectTypes;
91 const AResult: TStrings; const AFileSortType: TFileSortType;
92 out ExcludedCount: Cardinal);
93 { Other methods specific to Lazarus }
94 function GetPathFromNode(ANode: TTreeNode): String;
95 procedure PopulateWithBaseFiles;
96 procedure Refresh(ANode: TTreeNode); overload;
97
98 { Properties }
99 property ObjectTypes: TObjectTypes read FObjectTypes write SetObjectTypes;
100 property ShellListView: TCustomCastleShellListView read FShellListView write SetShellListView;
101 property FileSortType: TFileSortType read FFileSortType write SetFileSortType;
102 property Root: String read FRoot write SetRoot;
103 property Path: String read GetPath write SetPath;
104 property ExcludeMask: String read FExcludeMask write SetExcludeMask;
105
106 { Protected properties which users may want to access, see bug 15374 }
107 property Items;
108 end;
109
110 { TCastleShellTreeView }
111
112 TCastleShellTreeView = class(TCustomCastleShellTreeView)
113 published
114 { TCustomTreeView properties }
115 property Align;
116 property Anchors;
117 property AutoExpand;
118 property BorderSpacing;
119 //property BiDiMode;
120 property BackgroundColor;
121 property BorderStyle;
122 property BorderWidth;
123 property Color;
124 property Constraints;
125 property Enabled;
126 property ExcludeMask;
127 property ExpandSignType;
128 property Font;
129 property FileSortType;
130 property HideSelection;
131 property HotTrack;
132 property Images;
133 property Indent;
134 //property ParentBiDiMode;
135 property ParentColor default False;
136 property ParentFont;
137 property ParentShowHint;
138 property PopupMenu;
139 property ReadOnly;
140 property RightClickSelect;
141 property Root;
142 property RowSelect;
143 property ScrollBars;
144 property SelectionColor;
145 property ShowButtons;
146 property ShowHint;
147 property ShowLines;
148 property ShowRoot;
149 property StateImages;
150 property TabOrder;
151 property TabStop default True;
152 property Tag;
153 property ToolTips;
154 property Visible;
155 property OnAdvancedCustomDraw;
156 property OnAdvancedCustomDrawItem;
157 property OnChange;
158 property OnChanging;
159 property OnClick;
160 property OnCollapsed;
161 property OnCollapsing;
162 property OnCustomDraw;
163 property OnCustomDrawItem;
164 property OnDblClick;
165 property OnEdited;
166 property OnEditing;
167 property OnEnter;
168 property OnExit;
169 property OnExpanded;
170 property OnExpanding;
171 property OnGetImageIndex;
172 property OnGetSelectedIndex;
173 property OnKeyDown;
174 property OnKeyPress;
175 property OnKeyUp;
176 property OnMouseDown;
177 property OnMouseEnter;
178 property OnMouseLeave;
179 property OnMouseMove;
180 property OnMouseUp;
181 property OnMouseWheel;
182 property OnMouseWheelDown;
183 property OnMouseWheelUp;
184 {$ifndef VER3_0}
185 property OnMouseWheelHorz;
186 property OnMouseWheelLeft;
187 property OnMouseWheelRight;
188 {$endif}
189 property OnSelectionChanged;
190 property OnShowHint;
191 property OnUTF8KeyPress;
192 property Options;
193 property TreeLineColor;
194 property TreeLinePenStyle;
195 property ExpandSignColor;
196 { TCustomCastleShellTreeView properties }
197 property ObjectTypes;
198 property ShellListView;
199 end;
200
201 { TCustomCastleShellListView }
202
203 TCSLVFileAddedEvent = procedure(Sender: TObject; Item: TListItem) of object;
204
205 TCustomCastleShellListView = class(TCustomListView)
206 private
207 FMask, FExcludeMask: String;
208 FObjectTypes: TObjectTypes;
209 FRoot: String;
210 FShellTreeView: TCustomCastleShellTreeView;
211 FOnFileAdded: TCSLVFileAddedEvent;
212 FFileSortType: TFileSortType;
213 FExcludedCount: Cardinal;
214 { Setters and getters }
215 procedure SetFileSortType(AValue: TFileSortType);
216 procedure SetMask(const AValue: String);
217 procedure SetExcludeMask(const AValue: String);
218 procedure SetShellTreeView(const Value: TCustomCastleShellTreeView);
219 procedure SetRoot(const Value: String);
220 procedure ExcludedCountChanged;
221 function GetSelectedFileNameInRoot: String;
222 procedure SetSelectedFileNameInRoot(const Value: String);
223 protected
224 { Methods specific to Lazarus }
225 procedure PopulateWithRoot();
226 procedure Resize; override;
227 property OnFileAdded: TCSLVFileAddedEvent read FOnFileAdded write FOnFileAdded;
228 public
229 { Basic methods }
230 constructor Create(AOwner: TComponent); override;
231 destructor Destroy; override;
232 { Methods specific to Lazarus }
233 function GetPathFromItem(ANode: TListItem; const Absolute: Boolean = true): String;
234 procedure RefreshContents;
235 { Properties }
236 property Mask: String read FMask write SetMask;
237 property ExcludeMask: String read FExcludeMask write SetExcludeMask;
238 property ObjectTypes: TObjectTypes read FObjectTypes write FObjectTypes;
239 property Root: String read FRoot write SetRoot;
240 property ShellTreeView: TCustomCastleShellTreeView read FShellTreeView write SetShellTreeView;
241 property FileSortType: TFileSortType read FFileSortType write SetFileSortType;
242 { Protected properties which users may want to access, see bug 15374 }
243 property Items;
244 { Selected name in the list, without any path (the path is in @link(Root)).
245 Setting this to non-existing item is ignored without any errors. }
246 property SelectedFileNameInRoot: String read GetSelectedFileNameInRoot write SetSelectedFileNameInRoot;
247 end;
248
249 { TCastleShellListView }
250
251 TCastleShellListView = class(TCustomCastleShellListView)
252 public
253 property Columns;
254 published
255 { TCustomListView properties
256 The same as TListView excluding data properties }
257 property Align;
258 property Anchors;
259 property BorderSpacing;
260 property BorderStyle;
261 property BorderWidth;
262 // property Checkboxes;
263 property Color default clWindow;
264 // property ColumnClick;
265 property Constraints;
266 property DragCursor;
267 property DragMode;
268 // property DefaultItemHeight;
269 // property DropTarget;
270 property Enabled;
271 // property FlatScrollBars;
272 property FileSortType;
273 property Font;
274 // property FullDrag;
275 // property GridLines;
276 property HideSelection;
277 // property HotTrack;
278 // property HotTrackStyles;
279 // property HoverTime;
280 property LargeImages;
281 property Mask;
282 property ExcludeMask;
283 property MultiSelect;
284 // property OwnerData;
285 // property OwnerDraw;
286 property ParentColor default False;
287 property ParentFont;
288 property ParentShowHint;
289 property PopupMenu;
290 property ReadOnly;
291 property RowSelect;
292 property ScrollBars;
293 property ShowColumnHeaders;
294 property ShowHint;
295 // property ShowWorkAreas;
296 property SmallImages;
297 property SortColumn;
298 property SortType;
299 property StateImages;
300 property TabStop;
301 property TabOrder;
302 property ToolTips;
303 property Visible;
304 property ViewStyle default vsReport;
305 // property OnAdvancedCustomDraw;
306 // property OnAdvancedCustomDrawItem;
307 // property OnAdvancedCustomDrawSubItem;
308 property OnChange;
309 property OnClick;
310 property OnColumnClick;
311 property OnCompare;
312 property OnContextPopup;
313 // property OnCustomDraw;
314 // property OnCustomDrawItem;
315 // property OnCustomDrawSubItem;
316 property OnDblClick;
317 property OnDeletion;
318 property OnDragDrop;
319 property OnDragOver;
320 property OnEndDrag;
321 property OnKeyDown;
322 property OnKeyPress;
323 property OnKeyUp;
324 property OnMouseDown;
325 property OnMouseEnter;
326 property OnMouseLeave;
327 property OnMouseMove;
328 property OnMouseUp;
329 property OnMouseWheel;
330 property OnMouseWheelDown;
331 property OnMouseWheelUp;
332 {$ifndef VER3_0}
333 property OnMouseWheelHorz;
334 property OnMouseWheelLeft;
335 property OnMouseWheelRight;
336 {$endif}
337 property OnResize;
338 property OnSelectItem;
339 property OnStartDrag;
340 property OnUTF8KeyPress;
341 property OnFileAdded;
342 { TCustomCastleShellListView properties }
343 property ObjectTypes;
344 property Root;
345 property ShellTreeView;
346 end;
347
348 { TShellTreeNode }
349
350 TShellTreeNode = class(TTreeNode)
351 private
352 FFileInfo: TSearchRec;
353 FBasePath: String;
354 protected
355 procedure SetBasePath(ABasePath: String);
356 public
357 function ShortFilename: String;
358 function FullFilename: String;
359 function IsDirectory: Boolean;
360
361 property BasePath: String read FBasePath;
362 end;
363
364 EShellCtrl = class(Exception);
365 EInvalidPath = class(EShellCtrl);
366
367 function DbgS(OT: TObjectTypes): String; overload;
368
369 procedure Register;
370
371 const
372 { Use these to detect whether TListItem inside TCastleShellListView
373 is a directory or not. Compare these values with TListItem.Data value. }
374 ShellListItemFile = Pointer(1);
375 ShellListItemDirectory = Pointer(2);
376
377 implementation
378
379 uses {$ifdef windows} Windows, {$endif} StrUtils, CastleStringUtils;
380
381 const
382 //no need to localize, it's a message for the programmer
383 sShellTreeViewIncorrectNodeType = 'TCastleShellTreeView: the newly created node is not a TShellTreeNode!';
384
385 {$warnings off}
386 { Hide warnings that faXxx are unportable -- it is as expected. }
387 flagHidden = faHidden;
388 {$warnings on}
389
390 function DbgS(OT: TObjectTypes): String; overload;
391 begin
392 Result := '[';
393 if (otFolders in OT) then Result := Result + 'otFolders,';
394 if (otNonFolders in OT) then Result := Result + 'otNonFolders,';
395 if (otHidden in OT) then Result := Result + 'otHidden';
396 if Result[Length(Result)] = ',' then System.Delete(Result, Length(Result), 1);
397 Result := Result + ']';
398 end;
399
400 { TFileItem : internal helper class used for temporarily storing info in an internal TStrings component}
401 type
402 { TFileItem }
403 TFileItem = class(TObject)
404 private
405 FFileInfo: TSearchRec;
406 FBasePath: String;
407 public
408 //more data to sort by size, date... etc
409 isFolder: Boolean;
410 constructor Create(const DirInfo: TSearchRec; ABasePath: String);
411 property FileInfo: TSearchRec read FFileInfo write FFileInfo;
412 end;
413
414
415 constructor TFileItem.Create(const DirInfo:TSearchRec; ABasePath: String);
416 begin
417 FFileInfo := DirInfo;
418 FBasePath:= ABasePath;
419 isFolder:=DirInfo.Attr and FaDirectory > 0;
420 end;
421
422
423
424 { TShellTreeNode }
425
426 procedure TShellTreeNode.SetBasePath(ABasePath: String);
427 begin
428 FBasePath := ABasePath;
429 end;
430
431
432 function TShellTreeNode.ShortFilename: String;
433 begin
434 Result := ExtractFileName(FFileInfo.Name);
435 if (Result = '') then Result := FFileInfo.Name;
436 end;
437
438 function TShellTreeNode.FullFilename: String;
439 begin
440 if (FBasePath <> '') then
441 Result := AppendPathDelim(FBasePath) + FFileInfo.Name
442 else
443 //root nodes
444 Result := FFileInfo.Name;
445 {$if defined(windows) and not defined(wince)}
446 if (Length(Result) = 2) and (Result[2] = DriveSeparator) then
447 Result := Result + PathDelim;
448 {$endif}
449 end;
450
451 function TShellTreeNode.IsDirectory: Boolean;
452 begin
453 Result := ((FFileInfo.Attr and faDirectory) > 0);
454 end;
455
456
457 { TCustomCastleShellTreeView }
458
459 procedure TCustomCastleShellTreeView.SetShellListView(
460 const Value: TCustomCastleShellListView);
461 var
462 Tmp: TCustomCastleShellListView;
463 begin
464 if FShellListView = Value then Exit;
465
466 if Assigned(FShellListView) then
467 begin
468 Tmp := FShellListView;
469 FShellListView := nil;
470 Tmp.ShellTreeView := nil;
471 end;
472
473 FShellListView := Value;
474
475 // Update the pair, it will then update itself
476 // in the setter of this property
477 // Updates only if necessary to avoid circular calls of the setters
478 if Assigned(Value) and (Value.ShellTreeView <> Self) then
479 Value.ShellTreeView := Self;
480 end;
481
482 procedure TCustomCastleShellTreeView.SetExcludeMask(const AValue: String);
483 begin
484 if FExcludeMask = AValue then Exit;
485 FExcludeMask := AValue;
486 RefreshContents;
487 end;
488
489 procedure TCustomCastleShellTreeView.RefreshContents;
490 var
491 CurrPath: String;
492 begin
493 { Refresh visible files. Implementation copied from original LCL SetObjectTypes }
494 if (csLoading in ComponentState) then Exit;
495 CurrPath := GetPath;
496 try
497 BeginUpdate;
498 Refresh(nil);
499 try
500 SetPath(CurrPath);
501 except
502 // CurrPath may have been removed in the mean time by another process, just ignore
503 on E: EInvalidPath do ;//
504 end;
505 finally
506 EndUpdate;
507 end;
508 end;
509
510 procedure TCustomCastleShellTreeView.ExcludedCountChanged;
511 begin
512 // TODO
513 end;
514
515 procedure TCustomCastleShellTreeView.DoCreateNodeClass(
516 var NewNodeClass: TTreeNodeClass);
517 begin
518 NewNodeClass := TShellTreeNode;
519 inherited DoCreateNodeClass(NewNodeClass);
520 end;
521
522 procedure TCustomCastleShellTreeView.Loaded;
523 begin
524 inherited Loaded;
525 if (FInitialRoot = '') then
526 PopulateWithBaseFiles()
527 else
528 SetRoot(FInitialRoot);
529 end;
530
531 function TCustomCastleShellTreeView.CreateNode: TTreeNode;
532 begin
533 Result := inherited CreateNode;
534 //just in case someone attaches a new OnCreateNodeClass which does not return a TShellTreeNode (sub)class
535 if not (Result is TShellTreeNode) then
536 Raise EShellCtrl.Create(sShellTreeViewIncorrectNodeType);
537 end;
538
539 procedure TCustomCastleShellTreeView.SetRoot(const AValue: String);
540 var
541 RootNode: TTreeNode;
542 begin
543 if FRoot=AValue then exit;
544 if (csLoading in ComponentState) then
545 begin
546 FInitialRoot := AValue;
547 Exit;
548 end;
549 //Delphi raises an exception in this case, but don't crash the IDE at designtime
550 if not (csDesigning in ComponentState)
551 and (AValue <> '')
552 and not DirectoryExistsUtf8(ExpandFilenameUtf8(AValue)) then
553 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidRoot,[ExpandFileNameUtf8(AValue)]);
554 if (AValue = '') then
555 FRoot := GetBasePath
556 else
557 FRoot:=AValue;
558 Items.Clear;
559 if FRoot = '' then
560 begin
561 PopulateWithBaseFiles()
562 end
563 else
564 begin
565 //Add a node for Root and expand it (issue #0024230)
566 //Make FRoot contain fully qualified pathname, we need it later in GetPathFromNode()
567 FRoot := ExpandFileNameUtf8(FRoot);
568 //Set RootNode.Text to AValue so user can choose if text is fully qualified path or not
569 RootNode := Items.AddChild(nil, ExtractFileName(ExcludeTrailingPathDelimiter(AValue)));
570 TShellTreeNode(RootNode).FFileInfo.Attr := FileGetAttr(FRoot);
571 TShellTreeNode(RootNode).FFileInfo.Name := FRoot;
572 TShellTreeNode(RootNode).SetBasePath('');
573 RootNode.HasChildren := True;
574 RootNode.Expand(False);
575 end;
576 if Assigned(ShellListView) then
577 ShellListView.Root := FRoot;
578 end;
579
580 // ToDo: Optimize, now the tree is populated in constructor, SetRoot and SetFileSortType.
581 // For some reason it does not show in performance really.
582 procedure TCustomCastleShellTreeView.SetFileSortType(const AValue: TFileSortType);
583 var
584 RootNode: TTreeNode;
585 CurrPath: String;
586 begin
587 if FFileSortType=AValue then exit;
588 FFileSortType:=AValue;
589 if (csLoading in ComponentState) then Exit;
590 CurrPath := GetPath;
591 try
592 BeginUpdate;
593 Items.Clear;
594 if FRoot = '' then
595 PopulateWithBaseFiles()
596 else
597 begin
598 RootNode := Items.AddChild(nil, FRoot);
599 RootNode.HasChildren := True;
600 RootNode.Expand(False);
601 try
602 SetPath(CurrPath);
603 except
604 // CurrPath may have been removed in the mean time by another process, just ignore
605 on E: EInvalidPath do ;//
606 end;
607 end;
608 finally
609 EndUpdate;
610 end;
611 end;
612
613 procedure TCustomCastleShellTreeView.SetObjectTypes(AValue: TObjectTypes);
614 begin
615 if FObjectTypes = AValue then Exit;
616 FObjectTypes := AValue;
617 RefreshContents;
618 end;
619
620 function TCustomCastleShellTreeView.CanExpand(Node: TTreeNode): Boolean;
621 var
622 OldAutoExpand: Boolean;
623 begin
624 Result:=inherited CanExpand(Node);
625 if not Result then exit;
626 OldAutoExpand:=AutoExpand;
627 AutoExpand:=False;
628 Node.DeleteChildren;
629 Result := PopulateTreeNodeWithFiles(Node, GetPathFromNode(Node));
630 AutoExpand:=OldAutoExpand;
631 end;
632
633 constructor TCustomCastleShellTreeView.Create(AOwner: TComponent);
634 begin
635 inherited Create(AOwner);
636 FInitialRoot := '';
637
638 // Initial property values
639 FObjectTypes:= [otFolders];
640
641 // Populating the base dirs is done in Loaded
642 end;
643
644 destructor TCustomCastleShellTreeView.Destroy;
645 begin
646 ShellListView := nil;
647 inherited Destroy;
648 end;
649
650
651 function FilesSortAlphabet(p1, p2: Pointer): Integer;
652 var
653 f1, f2: TFileItem;
654 begin
655 f1:=TFileItem(p1);
656 f2:=TFileItem(p2);
657 Result:=CompareText(f1.FileInfo.Name, f2.FileInfo.Name);
658 end;
659
660 function FilesSortFoldersFirst(p1,p2: Pointer): Integer;
661 var
662 f1, f2: TFileItem;
663 begin
664 f1:=TFileItem(p1);
665 f2:=TFileItem(p2);
666 if f1.isFolder=f2.isFolder then
667 Result:=FilesSortAlphabet(p1,p2)
668 else begin
669 if f1.isFolder then Result:=-1
670 else Result:=1;
671 end;
672
673 end;
674
675 function STVCompareFiles(f1, f2: Pointer): integer;
676 begin
677 Result:=CompareFilenames(AnsiString(f1),AnsiString(f2));
678 end;
679
680 { Does given Name match one of the masks in Masks. }
681 function ExcludedFileName(const Name: String; const Masks: TStringList): Boolean;
682 var
683 Mask: String;
684 begin
685 for Mask in Masks do
686 if IsWild(Name, Mask, not FilenamesCaseSensitive) then
687 Exit(true);
688 Result := false;
689 end;
690
691 { Helper routine.
692 Finds all files/directories directly inside a directory.
693 Does not recurse inside subdirectories.
694
695 AResult will contain TFileItem objects upon return, make sure to free them in the calling routine
696
697 AMask may contain multiple file masks separated by ;
698 Don't add a final ; after the last mask.
699 }
700 class procedure TCustomCastleShellTreeView.GetFilesInDir(
701 const ABaseDir: String; const AMask, AExcludeMask: String;
702 const AObjectTypes: TObjectTypes; const AResult: TStrings;
703 const AFileSortType: TFileSortType; out ExcludedCount: Cardinal);
704 var
705 DirInfo: TSearchRec;
706 FindResult: Integer;
707 IsDirectory, IsValidDirectory, IsHidden, AddFile: Boolean;
708 SearchStr: String;
709 MaskStr: String;
710 Files: TList;
711 FileItem: TFileItem;
712 i: Integer;
713 MaskStrings, ExcludeMaskStrings: TStringList;
714 //FileTree: TStringList;
715 ShortFilename: AnsiString;
716 {$if defined(windows) and not defined(wince)}
717 ErrMode : UInt32;
718 {$endif}
719 begin
720 ExcludedCount := 0;
721
722 {$if defined(windows) and not defined(wince)}
723 // disables the error dialog, while enumerating not-available drives
724 // for example listing A: path, without diskette present.
725 ErrMode:=SetErrorMode(SEM_FAILCRITICALERRORS or SEM_NOALIGNMENTFAULTEXCEPT or SEM_NOGPFAULTERRORBOX or SEM_NOOPENFILEERRORBOX);
726 try
727 {$endif}
728
729 if Trim(AMask) = '' then MaskStr := AllFilesMask
730 else MaskStr := AMask;
731
732 // The string list implements support for multiple masks separated
733 // by semi-colon ";"
734 MaskStrings := TStringList.Create;
735 ExcludeMaskStrings := TStringList.Create;
736 try
737
738 {$ifdef NotLiteralFilenames}
739 MaskStrings.CaseSensitive := False;
740 ExcludeMaskStrings.CaseSensitive := False;
741 {$else}
742 MaskStrings.CaseSensitive := True;
743 ExcludeMaskStrings.CaseSensitive := True;
744 {$endif}
745 MaskStrings.Delimiter := ';';
746 MaskStrings.DelimitedText := MaskStr;
747 ExcludeMaskStrings.Delimiter := ';';
748 ExcludeMaskStrings.DelimitedText := AExcludeMask;
749
750 if AFileSortType=fstNone then Files:=nil
751 else Files:=TList.Create;
752
753 for i := 0 to MaskStrings.Count - 1 do
754 begin
755 if MaskStrings.IndexOf(MaskStrings[i]) < i then Continue; // From patch from bug 17761: TCastleShellListView Mask: duplicated items if mask is " *.ext;*.ext "
756 SearchStr := IncludeTrailingPathDelimiter(ABaseDir) + MaskStrings.Strings[i];
757
758 FindResult := FindFirstUTF8(SearchStr, faAnyFile, DirInfo);
759
760 while FindResult = 0 do
761 begin
762 ShortFilename := DirInfo.Name;
763
764 IsDirectory := (DirInfo.Attr and FaDirectory = FaDirectory);
765
766 IsValidDirectory := (ShortFilename <> '.') and (ShortFilename <> '..');
767
768 IsHidden := (DirInfo.Attr and flagHidden = flagHidden);
769
770 // First check if we show hidden files
771 if IsHidden then AddFile := (otHidden in AObjectTypes)
772 else AddFile := True;
773
774 // If it is a directory, check if it is a valid one
775 if IsDirectory then
776 AddFile := AddFile and ((otFolders in AObjectTypes) and IsValidDirectory)
777 else
778 AddFile := AddFile and (otNonFolders in AObjectTypes);
779
780 // Take into account ExcludeMaskStrings value
781 if AddFile then
782 begin
783 AddFile := not ExcludedFileName(ShortFilename, ExcludeMaskStrings);
784 if not AddFile then
785 Inc(ExcludedCount);
786 end;
787
788 // AddFile identifies if the file is valid or not
789 if AddFile then
790 begin
791 if not Assigned(Files) then
792 begin
793 (*
794 CGE: Since we only use this with hardcoded masks,
795 that do not duplicate extensions, we remove FileTree stuff.
796 This way it compiles with older LCL too. }
797 if FileTree.Find(Pointer(ShortFilename))=nil then
798 begin
799 // From patch from bug 17761: TCastleShellListView Mask: duplicated items if mask is " *.ext;*.ext "
800 FileTree.Add(Pointer(ShortFilename));
801 AResult.AddObject(ShortFilename, TFileItem.Create(DirInfo, ABaseDir));
802 end;
803 *)
804 AResult.AddObject(ShortFilename, TFileItem.Create(DirInfo, ABaseDir));
805 end else
806 Files.Add ( TFileItem.Create(DirInfo, ABaseDir));
807 end;
808
809 FindResult := FindNextUTF8(DirInfo);
810 end;
811
812 FindCloseUTF8(DirInfo);
813 end;
814 finally
815 MaskStrings.Free;
816 ExcludeMaskStrings.Free;
817 end;
818
819 if Assigned(Files) then begin
820
821 case AFileSortType of
822 fstNone: ; // do no sorting
823 fstAlphabet: Files.Sort(@FilesSortAlphabet);
824 fstFoldersFirst: Files.Sort(@FilesSortFoldersFirst);
825 end;
826
827 for i:=0 to Files.Count-1 do
828 begin
829 FileItem:=TFileItem(Files[i]);
830 if (i < Files.Count - 1) and (TFileItem(Files[i]).FileInfo.Name = TFileItem(Files[i + 1]).FileInfo.Name) then
831 begin
832 FileItem.Free;
833 Continue; // cause Files is sorted // From patch from bug 17761: TCastleShellListView Mask: duplicated items if mask is " *.ext;*.ext "
834 end;
835 AResult.AddObject(FileItem.FileInfo.Name, FileItem);
836 end;
837 //don't free the TFileItems here, they will freed by the calling routine
838 Files.Free;
839 end;
840
841 {$if defined(windows) and not defined(wince)}
842 finally
843 SetErrorMode(ErrMode);
844 end;
845 {$endif}
846 end;
847
848 class function TCustomCastleShellTreeView.GetBasePath: String;
849 begin
850 {$if defined(windows) and not defined(wince)}
851 Result := '';
852 {$endif}
853 {$ifdef wince}
854 Result := '\';
855 {$endif}
856 {$ifdef unix}
857 Result := '/';
858 {$endif}
859 {$ifdef HASAMIGA}
860 Result := '';
861 {$endif}
862 end;
863
864 function TCustomCastleShellTreeView.GetRootPath: String;
865 begin
866 if FRoot <> '' then
867 Result := FRoot
868 else
869 Result := GetBasePath();
870 if Result <> '' then
871 Result := IncludeTrailingPathDelimiter(Result);
872 end;
873
874 { Returns true if at least one item was added, false otherwise }
875 function TCustomCastleShellTreeView.PopulateTreeNodeWithFiles(
876 ANode: TTreeNode; ANodePath: String): Boolean;
877 var
878 i: Integer;
879 Files: TStringList;
880 NewNode: TTreeNode;
881
882 function HasSubDir(Const ADir: String): Boolean;
883 var
884 SR: TSearchRec;
885 FindRes: LongInt;
886 Attr: Longint;
887 IsHidden: Boolean;
888 begin
889 Result:=False;
890 try
891 Attr := faDirectory;
892 if (otHidden in fObjectTypes) then Attr := Attr or flagHidden;
893 FindRes := FindFirstUTF8(AppendPathDelim(ADir) + AllFilesMask, Attr , SR);
894 while (FindRes = 0) do
895 begin
896 if ((SR.Attr and faDirectory <> 0) and (SR.Name <> '.') and
897 (SR.Name <> '..')) then
898 begin
899 IsHidden := ((Attr and flagHidden) > 0);
900 if not (IsHidden and (not ((otHidden in fObjectTypes)))) then
901 begin
902 Result := True;
903 Break;
904 end;
905 end;
906 FindRes := FindNextUtf8(SR);
907 end;
908 finally
909 FindCloseUTF8(SR);
910 end; //try
911 end;
912
913 begin
914 Result := False;
915 // avoids crashes in the IDE by not populating during design
916 if (csDesigning in ComponentState) then Exit;
917
918 Files := TStringList.Create;
919 try
920 Files.OwnsObjects := True;
921 GetFilesInDir(ANodePath, AllFilesMask, ExcludeMask, FObjectTypes, Files,
922 FFileSortType, FExcludedCount);
923 ExcludedCountChanged;
924 Result := Files.Count > 0;
925
926 for i := 0 to Files.Count - 1 do
927 begin
928 NewNode := Items.AddChildObject(ANode, Files.Strings[i], nil);
929 TShellTreeNode(NewNode).FFileInfo := TFileItem(Files.Objects[i]).FileInfo;
930 TShellTreeNode(NewNode).SetBasePath(TFileItem(Files.Objects[i]).FBasePath);
931
932 if (fObjectTypes * [otNonFolders] = []) then
933 NewNode.HasChildren := (TShellTreeNode(NewNode).IsDirectory and
934 HasSubDir(AppendpathDelim(ANodePath)+Files[i]))
935 else
936 NewNode.HasChildren := TShellTreeNode(NewNode).IsDirectory;
937 end;
938 finally
939 Files.Free;
940 end;
941 end;
942
943 procedure TCustomCastleShellTreeView.PopulateWithBaseFiles;
944 {$if defined(windows) and not defined(wince)}
945 var
946 r: UInt32;
947 Drives: array[0..128] of char;
948 pDrive: PChar;
949 NewNode: TTreeNode;
950 begin
951 // avoids crashes in the IDE by not populating during design
952 if (csDesigning in ComponentState) then Exit;
953 Items.Clear;
954 r := GetLogicalDriveStrings(SizeOf(Drives), Drives);
955 if r = 0 then Exit;
956 if r > SizeOf(Drives) then Exit;
957 // raise Exception.Create(SysErrorMessage(ERROR_OUTOFMEMORY));
958 pDrive := Drives;
959 while pDrive^ <> #0 do
960 begin
961 NewNode := Items.AddChildObject(nil, ExcludeTrailingBackslash(pDrive), pDrive);
962 //Yes, we want to remove the backslash,so don't use ChompPathDelim here
963 TShellTreeNode(NewNode).FFileInfo.Name := ExcludeTrailingBackslash(pDrive);
964 //On NT platforms drive-roots really have these attributes
965 {$warnings off} // do not warn that faSysFile unportable
966 TShellTreeNode(NewNode).FFileInfo.Attr := faDirectory + faSysFile + flagHidden;
967 {$warnings on}
968 TShellTreeNode(NewNode).SetBasePath('');
969 NewNode.HasChildren := True;
970 Inc(pDrive, 4);
971 end;
972 end;
973 {$else}
974 var
975 NewNode: TTreeNode;
976 begin
977 // avoids crashes in the IDE by not populating during design
978 // also do not populate before loading is done
979 if ([csDesigning, csLoading] * ComponentState <> []) then Exit;
980 Items.Clear;
981
982 // This allows showing "/" in Linux, but in Windows it makes no sense to show the base
983 if GetBasePath() <> '' then
984 begin
985 NewNode := Items.AddChild(nil, GetBasePath());
986 NewNode.HasChildren := True;
987 PopulateTreeNodeWithFiles(NewNode, GetBasePath());
988 NewNode.Expand(False);
989 end
990 else
991 PopulateTreeNodeWithFiles(nil, GetBasePath());
992 end;
993 {$endif}
994
995 procedure TCustomCastleShellTreeView.DoSelectionChanged;
996 var
997 ANode: TTreeNode;
998 CurrentNodePath: String;
999 begin
1000 inherited DoSelectionChanged;
1001 ANode := Selected;
1002 if Assigned(FShellListView) and Assigned(ANode) then
1003 begin
1004 //You cannot rely on HasChildren here, because it can become FALSE when user
1005 //clicks the expand sign and folder is empty
1006 //Issue 0027571
1007 CurrentNodePath := ChompPathDelim(GetPathFromNode(ANode));
1008 if TShellTreeNode(ANode).IsDirectory then
1009 begin
1010 //Note: the folder may have been deleted in the mean time
1011 //an exception will be raised by the next line in that case
1012 FShellListView.Root := GetPathFromNode(ANode)
1013 end
1014 else
1015 begin
1016 if not FileExistsUtf8(CurrentNodePath) then
1017 Raise EShellCtrl.CreateFmt(sShellCtrlsSelectedItemDoesNotExists,[CurrentNodePath]);
1018 if Assigned(Anode.Parent) then
1019 FShellListView.Root := GetPathFromNode(ANode.Parent)
1020 else
1021 FShellListView.Root := '';
1022 end;
1023 end;
1024 end;
1025
1026 function TCustomCastleShellTreeView.GetPathFromNode(ANode: TTreeNode): String;
1027 begin
1028 if Assigned(ANode) then
1029 begin
1030 Result := TShellTreeNode(ANode).FullFilename;
1031 if TShellTreeNode(ANode).IsDirectory then
1032 Result := AppendPathDelim(Result);
1033 if not FilenameIsAbsolute(Result) then
1034 Result := GetRootPath() + Result; // Include root directory
1035 end
1036 else
1037 Result := '';
1038 end;
1039
1040
1041 procedure TCustomCastleShellTreeView.Refresh(ANode: TTreeNode);
1042 //nil will refresh root
1043 var
1044 RootNodeText: String;
1045 IsRoot: Boolean;
1046 begin
1047 if (Items.Count = 0) then Exit;
1048 {$ifdef debug_shellctrls}
1049 debugln(['TCustomCastleShellTreeView.Refresh: GetFirstVisibleNode.Text = "',Items.GetFirstVisibleNode.Text,'"']);
1050 {$endif}
1051
1052 IsRoot := (ANode = nil) or ((ANode = Items.GetFirstVisibleNode) and (GetRootPath <> ''));
1053 {$ifdef debug_shellctrls}
1054 debugln(['IsRoot = ',IsRoot]);
1055 {$endif}
1056
1057
1058 if (ANode = nil) and (GetRootPath <> '') then ANode := Items.GetFirstVisibleNode;
1059 if IsRoot then
1060 begin
1061 { Castle: commented this out, it is broken.
1062 In case we would do Tree.Refresh(Tree.Selected),
1063 with Tree.Selected <> nil and equal to tree root,
1064 we would effectively set RootNodeText to the name (but not full path!)
1065 of the root directory.
1066 But we need a full path, otherwise SetRoot with it will fail. }
1067 //if Assigned(ANode) then
1068 // RootNodeText := ANode.Text //this may differ from FRoot, so don't use FRoot here
1069 //else
1070
1071 RootNodeText := GetRootPath;
1072 {$ifdef debug_shellctrls}
1073 debugln(['IsRoot = TRUE, RootNodeText = "',RootNodeText,'"']);
1074 {$endif}
1075
1076 FRoot := #0; //invalidate FRoot
1077 SetRoot(RootNodeText); //re-initialize the entire tree
1078 end
1079 else
1080 begin
1081 ANode.Expand(False);
1082 end;
1083 end;
1084
1085 function TCustomCastleShellTreeView.GetPath: String;
1086 begin
1087 Result := GetPathFromNode(Selected);
1088 end;
1089
1090 {
1091 SetPath: Path can be
1092 - Absolute like '/usr/lib'
1093 - Relative like 'foo/bar'
1094 This can be relative to:
1095 - Self.Root (which takes precedence over)
1096 - Current directory
1097 }
1098 procedure TCustomCastleShellTreeView.SetPath(AValue: String);
1099 var
1100 sl: TStringList;
1101 Node: TTreeNode;
1102 i: integer;
1103 FQRootPath, RelPath: String;
1104 RootIsAbsolute: Boolean;
1105 IsRelPath: Boolean;
1106
1107 function GetAdjustedNodeText(ANode: TTreeNode): String;
1108 begin
1109 if (ANode = Items.GetFirstVisibleNode) and (FQRootPath <> '') then
1110 begin
1111 if not RootIsAbsolute then
1112 Result := ''
1113 else
1114 Result := FQRootPath;
1115 end
1116 else Result := ANode.Text;
1117 end;
1118
1119 function Exists(Fn: String): Boolean;
1120 //Fn should be fully qualified
1121 var
1122 Attr: LongInt;
1123 begin
1124 Result := False;
1125 Attr := FileGetAttrUtf8(Fn);
1126 {$ifdef debug_shellctrls}
1127 debugln(['TCustomCastleShellTreeView.SetPath.Exists: Attr = ', Attr]);
1128 {$endif}
1129 if (Attr = -1) then Exit;
1130 if not (otNonFolders in FObjectTypes) then
1131 Result := ((Attr and faDirectory) > 0)
1132 else
1133 Result := True;
1134 {$ifdef debug_shellctrls}
1135 debugln(['TCustomCastleShellTreeView.SetPath.Exists: Result = ',Result]);
1136 {$endif}
1137 end;
1138
1139 function PathIsDriveRoot({%H-}Path: String): Boolean; {$if not (defined(windows) and not defined(wince))}inline;{$endif}
1140 //WinNT filesystem reports faHidden on all physical drive-roots (e.g. C:\)
1141 begin
1142 {$if defined(windows) and not defined(wince)}
1143 Result := (Length(Path) = 3) and
1144 (Upcase(Path[1]) in ['A'..'Z']) and
1145 (Path[2] = DriveSeparator) and
1146 (Path[3] in AllowDirectorySeparators);
1147 {$else}
1148 Result := False;
1149 {$endif windows}
1150 end;
1151
1152 function ContainsHiddenDir(Fn: String): Boolean;
1153 var
1154 i: Integer;
1155 Attr: LongInt;
1156 Dirs: TStringList;
1157 RelPath: String;
1158 begin
1159 //if fn=root then always return false
1160 if (CompareFileNames(Fn, FQRootPath) = 0) then
1161 Result := False
1162 else
1163 begin
1164 Attr := FileGetAttrUtf8(Fn);
1165 Result := ((Attr and flagHidden) = flagHidden) and not PathIsDriveRoot(Fn);
1166 if not Result then
1167 begin
1168 //it also is not allowed that any folder above is hidden
1169 Fn := ChompPathDelim(Fn);
1170 Fn := ExtractFileDir(Fn);
1171 Dirs := TStringList.Create;
1172 try
1173 Dirs.StrictDelimiter := True;
1174 Dirs.Delimiter := PathDelim;
1175 Dirs.DelimitedText := Fn;
1176 Fn := '';
1177 for i := 0 to Dirs.Count - 1 do
1178 begin
1179 if (i = 0) then
1180 Fn := Dirs.Strings[i]
1181 else
1182 Fn := Fn + PathDelim + Dirs.Strings[i];
1183 if (Fn = '') then Continue;
1184 RelPath := CreateRelativePath(Fn, FQRootPath, False, True);
1185 //don't check if Fn now is "higher up the tree" than the current root
1186 if (RelPath = '') or ((Length(RelPath) > 1) and (RelPath[1] = '.') and (RelPath[2] = '.')) then
1187 begin
1188 {$ifdef debug_shellctrls}
1189 debugln(['TCustomCastleShellTreeView.SetPath.ContainsHidden: Fn is higher: ',Fn]);
1190 {$endif}
1191 Continue;
1192 end;
1193 {$if defined(windows) and not defined(wince)}
1194 if (Length(Fn) = 2) and (Fn[2] = ':') then Continue;
1195 {$endif}
1196 Attr := FileGetAttrUtf8(Fn);
1197 if (Attr <> -1) and ((Attr and flagHidden) > 0) and not PathIsDriveRoot(Fn) then
1198 begin
1199 Result := True;
1200 {$ifdef debug_shellctrls}
1201 debugln(['TCustomCastleShellTreeView.SetPath.Exists: a subdir is hidden: Result := False']);
1202 {$endif}
1203 Break;
1204 end;
1205 end;
1206 finally
1207 Dirs.Free;
1208 end;
1209 end;
1210 end;
1211 end;
1212
1213 begin
1214 RelPath := '';
1215
1216 {$ifdef debug_shellctrls}
1217 debugln(['SetPath: GetRootPath = "',getrootpath,'"',' AValue=',AValue]);
1218 {$endif}
1219 if (GetRootPath <> '') then
1220 //FRoot is already Expanded in SetRoot, just add PathDelim if needed
1221 FQRootPath := AppendPathDelim(GetRootPath)
1222 else
1223 FQRootPath := '';
1224 RootIsAbsolute := (FQRootPath = '') or (FQRootPath = PathDelim)
1225 or ((Length(FQRootPath) = 3) and (FQRootPath[2] = ':') and (FQRootPath[3] = PathDelim));
1226
1227 {$ifdef debug_shellctrls}
1228 debugln(['SetPath: FQRootPath = ',fqrootpath]);
1229 debugln(['SetPath: RootIsAbsolute = ',RootIsAbsolute]);
1230 debugln(['SetPath: FilenameIsAbsolute = ',FileNameIsAbsolute(AValue)]);
1231 {$endif}
1232
1233 if not FileNameIsAbsolute(AValue) then
1234 begin
1235 if Exists(FQRootPath + AValue) then
1236 begin
1237 //Expand it, since it may be in the form of ../../foo
1238 AValue := ExpandFileNameUtf8(FQRootPath + AValue);
1239 end
1240 else
1241 begin
1242 //don't expand Avalue yet, we may need it in error message
1243 if not Exists(ExpandFileNameUtf8(AValue)) then
1244 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidPath,[ExpandFileNameUtf8(FQRootPath + AValue)]);
1245 //Directory (or file) exists
1246 //Make it fully qualified
1247 AValue := ExpandFileNameUtf8(AValue);
1248 end;
1249 end
1250 else
1251 begin
1252 //AValue is an absoulte path to begin with
1253 //if not DirectoryExistsUtf8(AValue) then
1254 if not Exists(AValue) then
1255 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidPath,[AValue]);
1256 end;
1257
1258 //AValue now is a fully qualified path and it exists
1259 //Now check if it is a subdirectory of FQRootPath
1260 //RelPath := CreateRelativePath(AValue, FQRootPath, False);
1261 IsRelPath := (FQRootPath = '') or TryCreateRelativePath(AValue, FQRootPath, False, True, RelPath);
1262
1263 {$ifdef debug_shellctrls}
1264 debugln('TCustomCastleShellTreeView.SetPath: ');
1265 debugln([' IsRelPath = ',IsRelPath]);
1266 debugln([' RelPath = "',RelPath,'"']);
1267 debugln([' FQRootPath = "',FQRootPath,'"']);
1268 {$endif}
1269
1270 if (not IsRelpath) or ((RelPath <> '') and ((Length(RelPath) > 1) and (RelPath[1] = '.') and (RelPath[2] = '.'))) then
1271 begin
1272 // CreateRelativePath retruns a string beginning with ..
1273 // so AValue is not a subdirectory of FRoot
1274 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidPathRelative,[AValue, FQRootPath]);
1275 end;
1276
1277 if (RelPath = '') and (FQRootPath = '') then
1278 RelPath := AValue;
1279 {$ifdef debug_shellctrls}
1280 debugln(['RelPath = ',RelPath]);
1281 {$endif}
1282
1283 if (RelPath = '') then
1284 begin
1285 {$ifdef debug_shellctrls}
1286 debugln('Root selected');
1287 {$endif}
1288 Node := Items.GetFirstVisibleNode;
1289 if Assigned(Node) then
1290 begin
1291 Node.Expanded := True;
1292 Node.Selected := True;
1293 end;
1294 Exit;
1295 end;
1296
1297 if not (otHidden in FObjectTypes) and ContainsHiddenDir(AValue) then
1298 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidPath,[AValue, FQRootPath]);
1299
1300 sl := TStringList.Create;
1301 sl.Delimiter := PathDelim;
1302 sl.StrictDelimiter := True;
1303 sl.DelimitedText := RelPath;
1304 if (sl.Count > 0) and (sl[0] = '') then // This happens when root dir is empty
1305 sl[0] := PathDelim; // and PathDelim was the first char
1306 if (sl.Count > 0) and (sl[sl.Count-1] = '') then sl.Delete(sl.Count-1); //remove last empty string
1307 if (sl.Count = 0) then
1308 begin
1309 sl.Free;
1310 Exit;
1311 end;
1312
1313 {$ifdef debug_shellctrls}
1314 for i := 0 to sl.Count - 1 do debugln(['sl[',i,']="',sl[i],'"']);
1315 {$endif}
1316
1317
1318
1319 BeginUpdate;
1320 try
1321 Node := Items.GetFirstVisibleNode;
1322 {$ifdef debug_shellctrls}
1323 if assigned(node) then debugln(['GetFirstVisibleNode = ',GetAdjustedNodeText(Node)]);
1324 {$endif}
1325 //Root node doesn't have Siblings in this case, we need one level down the tree
1326 if (GetRootPath <> '') and Assigned(Node) then
1327 begin
1328 {$ifdef debug_shellctrls}
1329 debugln('Root node doesn''t have Siblings');
1330 {$endif}
1331 Node := Node.GetFirstVisibleChild;
1332 {$ifdef debug_shellctrls}
1333 debugln(['Node = ',GetAdjustedNodeText(Node)]);
1334 {$endif}
1335 //I don't know why I wrote this in r44893, but it seems to be wrong so I comment it out
1336 //for the time being (2015-12-05: BB)
1337 //if RootIsAbsolute then sl.Delete(0);
1338 end;
1339
1340 for i := 0 to sl.Count-1 do
1341 begin
1342 {$ifdef debug_shellctrls}
1343 DbgOut(['i=',i,' sl[',i,']=',sl[i],' ']);
1344 if Node <> nil then DbgOut(['GetAdjustedNodeText = ',GetAdjustedNodeText(Node)])
1345 else DbgOut('Node = NIL');
1346 debugln;
1347 {$endif}
1348 while (Node <> Nil) and
1349 {$IF defined(CaseInsensitiveFilenames) or defined(NotLiteralFilenames)}
1350 (Utf8LowerCase(GetAdjustedNodeText(Node)) <> Utf8LowerCase(sl[i]))
1351 {$ELSE}
1352 (GetAdjustedNodeText(Node) <> sl[i])
1353 {$ENDIF}
1354 do
1355 begin
1356 {$ifdef debug_shellctrls}
1357 DbgOut([' i=',i,' "',GetAdjustedNodeText(Node),' <> ',sl[i],' -> GetNextVisibleSibling -> ']);
1358 {$endif}
1359 Node := Node.GetNextVisibleSibling;
1360 {$ifdef debug_shellctrls}
1361 if Node <> nil then DbgOut(['GetAdjustedNodeText = ',GetAdjustedNodeText(Node)])
1362 else DbgOut('Node = NIL');
1363 debugln;
1364 {$endif}
1365 end;
1366 if Node <> Nil then
1367 begin
1368 Node.Expanded := True;
1369 Node.Selected := True;
1370 Node := Node.GetFirstVisibleChild;
1371 end
1372 else
1373 Break;
1374 end;
1375 finally
1376 sl.free;
1377 EndUpdate;
1378 end;
1379 end;
1380
1381
1382 { TCustomCastleShellListView }
1383
1384 procedure TCustomCastleShellListView.SetShellTreeView(
1385 const Value: TCustomCastleShellTreeView);
1386 var
1387 Tmp: TCustomCastleShellTreeView;
1388 begin
1389 if FShellTreeView = Value then Exit;
1390 if FShellTreeView <> nil then
1391 begin
1392 Tmp := FShellTreeView;
1393 FShellTreeView := nil;
1394 Tmp.ShellListView := nil;
1395 end;
1396
1397 FShellTreeView := Value;
1398
1399 if not (csDestroying in ComponentState) then
1400 Clear;
1401
1402 if Value <> nil then
1403 begin
1404 FRoot := Value.GetPathFromNode(Value.Selected);
1405 PopulateWithRoot();
1406
1407 // Also update the pair, but only if necessary to avoid circular calls of the setters
1408 if Value.ShellListView <> Self then Value.ShellListView := Self;
1409 end;
1410
1411 end;
1412
1413 procedure TCustomCastleShellListView.SetMask(const AValue: String);
1414 begin
1415 if AValue <> FMask then
1416 begin
1417 FMask := AValue;
1418 RefreshContents;
1419 end;
1420 end;
1421
1422 procedure TCustomCastleShellListView.SetFileSortType(AValue: TFileSortType);
1423 begin
1424 if FFileSortType <> AValue then
1425 begin
1426 FFileSortType := AValue;
1427 RefreshContents;
1428 end;
1429 end;
1430
1431 procedure TCustomCastleShellListView.SetExcludeMask(const AValue: String);
1432 begin
1433 if AValue <> FExcludeMask then
1434 begin
1435 FExcludeMask := AValue;
1436 RefreshContents;
1437 end;
1438 end;
1439
1440 procedure TCustomCastleShellListView.SetRoot(const Value: String);
1441 begin
1442 if FRoot <> Value then
1443 begin
1444 //Delphi raises an unspecified exception in this case, but don't crash the IDE at designtime
1445 if not (csDesigning in ComponentState)
1446 and (Value <> '')
1447 and not DirectoryExistsUtf8(ExpandFilenameUtf8(Value)) then
1448 Raise EInvalidPath.CreateFmt(sShellCtrlsInvalidRoot,[Value]);
1449 FRoot := Value;
1450 RefreshContents;
1451 end;
1452 end;
1453
1454 procedure TCustomCastleShellListView.RefreshContents;
1455 begin
1456 Clear;
1457 Items.Clear;
1458 PopulateWithRoot();
1459 end;
1460
1461 procedure TCustomCastleShellListView.ExcludedCountChanged;
1462 begin
1463 // TODO
1464 end;
1465
1466 constructor TCustomCastleShellListView.Create(AOwner: TComponent);
1467 begin
1468 inherited Create(AOwner);
1469
1470 // Initial property values
1471 ViewStyle := vsReport;
1472 ObjectTypes := [otNonFolders];
1473
1474 Self.Columns.Add;
1475 Self.Columns.Add;
1476 Self.Columns.Add;
1477 Self.Column[0].Caption := sShellCtrlsName;
1478 Self.Column[1].Caption := sShellCtrlsSize;
1479 Self.Column[2].Caption := sShellCtrlsType;
1480 // Initial sizes, necessary under Windows CE
1481 Resize;
1482 end;
1483
1484 destructor TCustomCastleShellListView.Destroy;
1485 begin
1486 ShellTreeView := nil;
1487 inherited Destroy;
1488 end;
1489
1490 procedure TCustomCastleShellListView.PopulateWithRoot();
1491 var
1492 i: Integer;
1493 Files: TStringList;
1494 NewItem: TListItem;
1495 CurFileName, CurFilePath: String;
1496 CurFileSize: Int64;
1497 begin
1498 // avoids crashes in the IDE by not populating during design
1499 if (csDesigning in ComponentState) then Exit;
1500
1501 // Check inputs
1502 if Trim(FRoot) = '' then Exit;
1503
1504 Files := TStringList.Create;
1505 try
1506 Files.OwnsObjects := True;
1507 TCustomCastleShellTreeView.GetFilesInDir(FRoot, FMask, FExcludeMask,
1508 FObjectTypes, Files, FFileSortType, FExcludedCount);
1509 ExcludedCountChanged;
1510
1511 for i := 0 to Files.Count - 1 do
1512 begin
1513 NewItem := Items.Add;
1514 CurFileName := Files.Strings[i];
1515 CurFilePath := IncludeTrailingPathDelimiter(FRoot) + CurFileName;
1516 if DirectoryExists(CurFilePath) then
1517 begin
1518 NewItem.Caption := CurFileName;
1519 NewItem.SubItems.Add('');
1520 NewItem.SubItems.Add('');
1521 NewItem.Data := ShellListItemDirectory;
1522 NewItem.ImageIndex := 0;
1523 end else
1524 begin
1525 // First column - Name
1526 NewItem.Caption := CurFileName;
1527 // Second column - Size
1528 // The raw size in bytes is stored in the data part of the item
1529 CurFileSize := FileSize(CurFilePath); // in Bytes
1530 NewItem.Data := Pointer(PtrInt(CurFileSize));
1531 if CurFileSize < 1024 then
1532 NewItem.SubItems.Add(Format(sShellCtrlsBytes, [IntToStr(CurFileSize)]))
1533 else if CurFileSize < 1024 * 1024 then
1534 NewItem.SubItems.Add(Format(sShellCtrlsKB, [IntToStr(CurFileSize div 1024)]))
1535 else
1536 NewItem.SubItems.Add(Format(sShellCtrlsMB, [IntToStr(CurFileSize div (1024 * 1024))]));
1537 // Third column - Type
1538 NewItem.SubItems.Add(ExtractFileExt(CurFileName));
1539 NewItem.Data := ShellListItemFile;
1540 end;
1541 if Assigned(FOnFileAdded) then FOnFileAdded(Self,NewItem);
1542 end;
1543 Sort;
1544 finally
1545 Files.Free;
1546 end;
1547 end;
1548
1549 procedure TCustomCastleShellListView.Resize;
1550 begin
1551 inherited Resize;
1552 {$ifdef DEBUG_SHELLCTRLS}
1553 debugln(':>TCustomCastleShellListView.HandleResize');
1554 {$endif}
1555
1556 // The correct check is with count,
1557 // if Column[0] <> nil then
1558 // will raise an exception
1559 if Self.Columns.Count < 3 then Exit;
1560
1561 // If the space available is small,
1562 // alloc a larger percentage to the secondary
1563 // fields
1564 if Width < 400 then
1565 begin
1566 Column[0].Width := (50 * Width) div 100;
1567 Column[1].Width := (25 * Width) div 100;
1568 Column[2].Width := (25 * Width) div 100;
1569 end
1570 else
1571 begin
1572 Column[0].Width := (70 * Width) div 100;
1573 Column[1].Width := (15 * Width) div 100;
1574 Column[2].Width := (15 * Width) div 100;
1575 end;
1576
1577 {$ifdef DEBUG_SHELLCTRLS}
1578 debugln([':<TCustomCastleShellListView.HandleResize C0.Width=',
1579 Column[0].Width, ' C1.Width=', Column[1].Width,
1580 ' C2.Width=', Column[2].Width]);
1581 {$endif}
1582 end;
1583
1584 function TCustomCastleShellListView.GetPathFromItem(ANode: TListItem; const Absolute: Boolean): String;
1585 var
1586 FileName: String;
1587 begin
1588 FileName := ANode.Caption;
1589 if Absolute then
1590 Result := IncludeTrailingPathDelimiter(FRoot) + FileName
1591 else
1592 Result := FileName;
1593 end;
1594
1595 function TCustomCastleShellListView.GetSelectedFileNameInRoot: String;
1596 begin
1597 if Selected <> nil then
1598 Result := GetPathFromItem(Selected, false)
1599 else
1600 Result := '';
1601 end;
1602
1603 procedure TCustomCastleShellListView.SetSelectedFileNameInRoot(const Value: String);
1604 begin
1605 if Value = '' then
1606 Selected := nil
1607 else
1608 begin
1609 // See LCL source lazarus/lcl/include/listitems.inc for the meaning of Items.FindCaption parameters.
1610 // Items.FindCaption returns nil when not found.
1611 Selected := Items.FindCaption(
1612 0, // StartIndex, 0 to search all items
1613 Value,
1614 false, // Partial, would find values that only contain Value
1615 true, // Inclusive, otherwise StartIndex would actually be interpreted as 1
1616 false, // Wrap, ignored when StartIndex = 0
1617 false // PartStart, ignored when Partial = false (would make Partial to match only prefix)
1618 );
1619 end;
1620 end;
1621
1622 procedure Register;
1623 begin
1624 RegisterComponents('Castle', [TCastleShellTreeView, TCastleShellListView]);
1625 end;
1626
1627 end.