{"TotalCount":16,"Files":[{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/AssetContextMenuHelper.cs","FileName":"AssetContextMenuHelper.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Threading.Tasks;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Helper for building asset context menus with Create Material/Texture options.\n/// \u003C/summary\u003E\npublic static class AssetContextMenuHelper\n{\n    // Builds the right-click menu for a single file/asset. Shared by the tree view and the icon grid\n    // so both show identical options. Rename UI differs per view, so it is passed in via onRename.\n    public static void BuildFileMenu(Menu menu, string fullPath, Asset asset, Action onRename, Action onChanged)\n    {\n        var fileName = Path.GetFileName(fullPath);\n\n        if (asset != null)\n            menu.AddOption(\u0022Open in Editor\u0022, \u0022edit\u0022, () =\u003E asset.OpenInEditor());\n        else\n            menu.AddOption(\u0022Open\u0022, \u0022open_in_new\u0022, () =\u003E EditorUtility.OpenFolder(fullPath));\n\n        menu.AddOption(\u0022Show in Explorer\u0022, \u0022folder_open\u0022, () =\u003E EditorUtility.OpenFileFolder(fullPath));\n\n        menu.AddSeparator();\n\n        if (asset != null)\n            menu.AddOption(\u0022Copy Relative Path\u0022, \u0022content_paste_go\u0022, () =\u003E EditorUtility.Clipboard.Copy(asset.RelativePath));\n        menu.AddOption(\u0022Copy Absolute Path\u0022, \u0022content_paste\u0022, () =\u003E EditorUtility.Clipboard.Copy(fullPath));\n\n        // Asset-type specific options (Create Material, Create Texture, etc.)\n        AddAssetTypeOptions(menu, asset);\n\n        menu.AddSeparator();\n\n        menu.AddOption(\u0022Rename\u0022, \u0022edit\u0022, () =\u003E onRename?.Invoke());\n        menu.AddOption(\u0022Duplicate\u0022, \u0022file_copy\u0022, () =\u003E\n        {\n            DuplicateFileWithRename(fullPath, () =\u003E onChanged?.Invoke());\n        });\n\n        menu.AddSeparator();\n\n        var parentFolder = Path.GetDirectoryName(fullPath);\n        if (!string.IsNullOrEmpty(parentFolder))\n        {\n            var createMenu = menu.AddMenu(\u0022Create\u0022, \u0022add\u0022);\n            AssetCreator.AddOptions(createMenu, parentFolder);\n            menu.AddSeparator();\n        }\n\n        menu.AddOption(\u0022Delete\u0022, \u0022delete\u0022, () =\u003E\n        {\n            var confirm = new PopupWindow(\n                \u0022Delete File\u0022,\n                $\u0022Are you sure you want to delete \u0027{fileName}\u0027?\u0022,\n                \u0022Cancel\u0022,\n                new Dictionary\u003Cstring, Action\u003E()\n                {\n                    { \u0022Delete\u0022, () =\u003E\n                        {\n                            try\n                            {\n                                DeleteFileWithCompiled(fullPath, asset);\n                                onChanged?.Invoke();\n                            }\n                            catch (Exception ex)\n                            {\n                                Log.Error($\u0022Failed to delete file: {ex.Message}\u0022);\n                            }\n                        }\n                    }\n                }\n            );\n            confirm.Show();\n        });\n    }\n\n    // Builds the right-click menu for a folder. Shared by the tree view and the icon grid.\n    public static void BuildFolderMenu(Menu menu, string fullPath, string displayName, bool isRoot,\n        Action onOpen, Action onRename, Action onRefresh, Action onDeleted)\n    {\n        if (onOpen != null)\n            menu.AddOption(\u0022Open\u0022, \u0022folder_open\u0022, () =\u003E onOpen());\n\n        menu.AddOption(\u0022Open in Explorer\u0022, \u0022launch\u0022, () =\u003E EditorUtility.OpenFolder(fullPath));\n\n        menu.AddSeparator();\n\n        var createMenu = menu.AddMenu(\u0022Create\u0022, \u0022add\u0022);\n        AssetCreator.AddOptions(createMenu, fullPath);\n\n        // Paste files copied from Windows Explorer into this folder\n        if (WindowsClipboard.HasFiles())\n        {\n            menu.AddOption(\u0022Paste\u0022, \u0022content_paste\u0022, () =\u003E\n            {\n                PasteFromClipboard(fullPath);\n                onRefresh?.Invoke();\n            });\n        }\n\n        menu.AddSeparator();\n\n        if (!isRoot)\n            menu.AddOption(\u0022Rename\u0022, \u0022edit\u0022, () =\u003E onRename?.Invoke());\n\n        menu.AddOption(\u0022Copy Path\u0022, \u0022content_copy\u0022, () =\u003E EditorUtility.Clipboard.Copy(fullPath));\n        menu.AddOption(\u0022Copy Relative Path\u0022, \u0022content_copy\u0022, () =\u003E\n        {\n            var relativePath = Path.GetRelativePath(Project.Current?.GetRootPath() ?? \u0022\u0022, fullPath);\n            EditorUtility.Clipboard.Copy(relativePath);\n        });\n\n        menu.AddSeparator();\n\n        menu.AddOption(\u0022Refresh\u0022, \u0022refresh\u0022, () =\u003E onRefresh?.Invoke());\n\n        if (!isRoot)\n        {\n            menu.AddSeparator();\n            menu.AddOption(\u0022Delete\u0022, \u0022delete\u0022, () =\u003E\n            {\n                var confirm = new PopupWindow(\n                    \u0022Delete Folder\u0022,\n                    $\u0022Are you sure you want to delete \u0027{displayName}\u0027?\\nAll contents will be deleted.\u0022,\n                    \u0022Cancel\u0022,\n                    new Dictionary\u003Cstring, Action\u003E()\n                    {\n                        { \u0022Delete\u0022, () =\u003E\n                            {\n                                try\n                                {\n                                    Directory.Delete(fullPath, recursive: true);\n                                    onDeleted?.Invoke();\n                                }\n                                catch (Exception ex)\n                                {\n                                    Log.Error($\u0022Failed to delete folder: {ex.Message}\u0022);\n                                }\n                            }\n                        }\n                    }\n                );\n                confirm.Show();\n            });\n        }\n    }\n\n    // Duplicates a file next to itself, finding a free \u0022_copy\u0022 name.\n    public static string DuplicateFile(string filePath)\n    {\n        try\n        {\n            var directory = Path.GetDirectoryName(filePath);\n            var nameWithoutExt = Path.GetFileNameWithoutExtension(filePath);\n            var extension = Path.GetExtension(filePath);\n\n            var newName = $\u0022{nameWithoutExt}_copy{extension}\u0022;\n            var newPath = Path.Combine(directory, newName);\n\n            var counter = 1;\n            while (File.Exists(newPath))\n            {\n                newName = $\u0022{nameWithoutExt}_copy{counter\u002B\u002B}{extension}\u0022;\n                newPath = Path.Combine(directory, newName);\n            }\n\n            File.Copy(filePath, newPath);\n\n            // Register the new file so it gets compiled and recognised as an asset immediately\n            // (without this it shows up uncompiled until an editor restart or rename).\n            AssetSystem.RegisterFile(newPath);\n\n            return newPath;\n        }\n        catch (Exception ex)\n        {\n            Log.Error($\u0022Failed to duplicate file: {ex.Message}\u0022);\n            return null;\n        }\n    }\n\n    // Duplicates a file and immediately opens a rename modal pre-filled with the copy\u0027s name.\n    public static void DuplicateFileWithRename(string filePath, Action onComplete = null)\n    {\n        var newPath = DuplicateFile(filePath);\n        if (string.IsNullOrEmpty(newPath))\n            return;\n\n        onComplete?.Invoke();\n\n        var extension = Path.GetExtension(newPath);\n        var dialog = new RenameDialog(\u0022Rename Duplicate\u0022, Path.GetFileNameWithoutExtension(newPath));\n        dialog.OnConfirm = (newName) =\u003E\n        {\n            if (string.IsNullOrWhiteSpace(newName))\n                return;\n\n            // Preserve extension if the user didn\u0027t type one\n            if (!Path.HasExtension(newName))\n                newName \u002B= extension;\n\n            if (newName == Path.GetFileName(newPath))\n                return;\n\n            var renamedPath = Path.Combine(Path.GetDirectoryName(newPath), newName);\n            if (File.Exists(renamedPath))\n            {\n                Log.Warning($\u0022A file named \u0027{newName}\u0027 already exists\u0022);\n                return;\n            }\n\n            try\n            {\n                File.Move(newPath, renamedPath);\n\n                // Drop the freshly compiled _c file so it doesn\u0027t linger under the old name\n                var oldCompiled = newPath \u002B \u0022_c\u0022;\n                if (File.Exists(oldCompiled))\n                    File.Delete(oldCompiled);\n\n                AssetSystem.RegisterFile(renamedPath);\n                onComplete?.Invoke();\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to rename duplicate: {ex.Message}\u0022);\n            }\n        };\n        dialog.Show();\n    }\n\n    // Registers a freshly created/copied/moved path with the asset system so it compiles right away.\n    // Accepts a single file or a directory (registers every file inside, recursively).\n    public static void RegisterNewPath(string path)\n    {\n        try\n        {\n            if (Directory.Exists(path))\n            {\n                foreach (var file in Directory.EnumerateFiles(path, \u0022*\u0022, SearchOption.AllDirectories))\n                {\n                    if (ShouldRegister(file))\n                        AssetSystem.RegisterFile(file);\n                }\n            }\n            else if (File.Exists(path) \u0026\u0026 ShouldRegister(path))\n            {\n                AssetSystem.RegisterFile(path);\n            }\n        }\n        catch (Exception ex)\n        {\n            Log.Warning($\u0022Failed to register \u0027{path}\u0027: {ex.Message}\u0022);\n        }\n    }\n\n    // Copies the files currently on the Windows clipboard into the target folder (always copy, never move).\n    public static void PasteFromClipboard(string targetFolder)\n    {\n        if (string.IsNullOrEmpty(targetFolder) || !Directory.Exists(targetFolder))\n            return;\n\n        foreach (var file in WindowsClipboard.GetFiles())\n        {\n            if (string.IsNullOrEmpty(file))\n                continue;\n\n            try\n            {\n                var name = Path.GetFileName(file.TrimEnd(\u0027\\\\\u0027, \u0027/\u0027));\n                var destPath = Path.Combine(targetFolder, name);\n\n                // Don\u0027t paste a folder into itself\n                if (Path.GetFullPath(file).Equals(Path.GetFullPath(destPath), StringComparison.OrdinalIgnoreCase))\n                    destPath = MakeUniquePath(destPath);\n                else if (File.Exists(destPath) || Directory.Exists(destPath))\n                    destPath = MakeUniquePath(destPath);\n\n                if (Directory.Exists(file))\n                    CopyDirectory(file, destPath);\n                else if (File.Exists(file))\n                    File.Copy(file, destPath, overwrite: false);\n                else\n                    continue;\n\n                RegisterNewPath(destPath);\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to paste \u0027{file}\u0027: {ex.Message}\u0022);\n            }\n        }\n    }\n\n    private static string MakeUniquePath(string path)\n    {\n        if (!File.Exists(path) \u0026\u0026 !Directory.Exists(path))\n            return path;\n\n        var directory = Path.GetDirectoryName(path);\n        var name = Path.GetFileNameWithoutExtension(path);\n        var ext = Path.GetExtension(path);\n\n        int counter = 1;\n        string candidate;\n        do\n        {\n            var suffix = counter == 1 ? \u0022_copy\u0022 : $\u0022_copy{counter}\u0022;\n            candidate = Path.Combine(directory, $\u0022{name}{suffix}{ext}\u0022);\n            counter\u002B\u002B;\n        }\n        while (File.Exists(candidate) || Directory.Exists(candidate));\n\n        return candidate;\n    }\n\n    private static void CopyDirectory(string sourceDir, string destDir)\n    {\n        Directory.CreateDirectory(destDir);\n\n        foreach (var file in Directory.GetFiles(sourceDir))\n        {\n            File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)));\n        }\n\n        foreach (var dir in Directory.GetDirectories(sourceDir))\n        {\n            CopyDirectory(dir, Path.Combine(destDir, Path.GetFileName(dir)));\n        }\n    }\n\n    // True when the path lives outside the current project (e.g. dragged in from Windows Explorer).\n    // Such sources must be copied, never moved, so we don\u0027t delete files from their original location.\n    public static bool IsExternalSource(string path)\n    {\n        try\n        {\n            var root = Project.Current?.GetRootPath();\n            if (string.IsNullOrEmpty(root))\n                return false;\n\n            var full = Path.GetFullPath(path);\n            var rootFull = Path.GetFullPath(root);\n            return !full.StartsWith(rootFull, StringComparison.OrdinalIgnoreCase);\n        }\n        catch\n        {\n            return false;\n        }\n    }\n\n    // Create a prefab from GameObject(s) dragged in from the scene hierarchy.\n    // A single object becomes the prefab root directly; multiple objects are\n    // wrapped under a new root, mirroring the engine\u0027s \u0022Convert to Prefab\u0022.\n    public static void CreatePrefabFromGameObjects(GameObject[] gameObjects, string targetFolder, Action onComplete = null)\n    {\n        if (gameObjects == null || string.IsNullOrEmpty(targetFolder)) return;\n\n        var selection = gameObjects.Where(g =\u003E g != null).ToArray();\n        var first = selection.FirstOrDefault();\n        if (first == null) return;\n\n        try\n        {\n            var session = SceneEditorSession.Resolve(first);\n            if (session == null) return;\n\n            var baseName = string.IsNullOrWhiteSpace(first.Name) ? \u0022Prefab\u0022 : first.Name;\n            var location = GetUniquePrefabPath(targetFolder, baseName);\n\n            using var scene = session.Scene.Push();\n            using (session.UndoScope(\u0022Create Prefab from Hierarchy\u0022).WithGameObjectChanges(selection, GameObjectUndoFlags.All).WithGameObjectCreations().Push())\n            {\n                GameObject prefabRoot;\n\n                if (selection.Length == 1)\n                {\n                    prefabRoot = first;\n                }\n                else\n                {\n                    prefabRoot = new GameObject();\n                    prefabRoot.WorldTransform = first.WorldTransform;\n\n                    foreach (var go in selection)\n                        go.SetParent(prefabRoot, true);\n                }\n\n                prefabRoot.Name = Path.GetFileNameWithoutExtension(location);\n\n                EditorUtility.Prefabs.ConvertGameObjectToPrefab(prefabRoot, location);\n                EditorUtility.InspectorObject = prefabRoot;\n            }\n        }\n        catch (Exception ex)\n        {\n            Log.Error($\u0022Failed to create prefab: {ex.Message}\u0022);\n        }\n\n        onComplete?.Invoke();\n    }\n\n    // Build a non-colliding \u0022name.prefab\u0022 path inside the target folder.\n    private static string GetUniquePrefabPath(string folder, string baseName)\n    {\n        var path = Path.Combine(folder, $\u0022{baseName}.prefab\u0022);\n        int n = 1;\n        while (File.Exists(path) || AssetSystem.FindByPath(path) != null)\n        {\n            path = Path.Combine(folder, $\u0022{baseName} ({n}).prefab\u0022);\n            n\u002B\u002B;\n        }\n        return path;\n    }\n\n    // ===== Backward compatibility: move an asset and optionally fix references to its old path =====\n\n    private static readonly HashSet\u003Cstring\u003E NonTextExtensions = new(StringComparer.OrdinalIgnoreCase)\n    {\n        \u0022.png\u0022, \u0022.jpg\u0022, \u0022.jpeg\u0022, \u0022.tga\u0022, \u0022.psd\u0022, \u0022.bmp\u0022, \u0022.gif\u0022, \u0022.dds\u0022, \u0022.hdr\u0022,\n        \u0022.fbx\u0022, \u0022.obj\u0022, \u0022.gltf\u0022, \u0022.glb\u0022, \u0022.dmx\u0022, \u0022.blend\u0022,\n        \u0022.wav\u0022, \u0022.mp3\u0022, \u0022.ogg\u0022, \u0022.flac\u0022,\n        \u0022.vtex\u0022, \u0022.vsnd\u0022, \u0022.vmdl\u0022, \u0022.dll\u0022, \u0022.pdb\u0022, \u0022.exe\u0022, \u0022.zip\u0022, \u0022.bin\u0022\n    };\n\n    // True if this is a single registered asset being moved inside the project - the case the\n    // backward-compatibility reference check applies to.\n    public static bool IsBackwardCompatMove(IReadOnlyList\u003Cstring\u003E files, bool isCopy)\n    {\n        if (!BrowserSettings.BackwardCompatibility) return false;\n        if (isCopy) return false;\n        if (files == null || files.Count != 1) return false;\n\n        var file = files[0];\n        if (string.IsNullOrEmpty(file) || IsExternalSource(file) || Directory.Exists(file)) return false;\n        if (!File.Exists(file)) return false;\n\n        var asset = AssetSystem.FindByPath(file);\n        return asset != null \u0026\u0026 !asset.IsDeleted;\n    }\n\n    // Moves an asset, first asking (via a modal) whether to update references to its old path.\n    public static void MoveAssetWithReferenceCheck(string sourceFile, string targetFolder, Action onComplete)\n    {\n        var asset = AssetSystem.FindByPath(sourceFile);\n        if (asset == null || asset.IsDeleted)\n            return;\n\n        // Don\u0027t bother if it\u0027s already in the target folder\n        if (string.Equals(Path.GetFullPath(Path.GetDirectoryName(sourceFile)), Path.GetFullPath(targetFolder), StringComparison.OrdinalIgnoreCase))\n            return;\n\n        var assetsRoot = Project.Current?.GetAssetsPath();\n        var oldRef = asset.RelativePath?.Replace(\u0027\\\\\u0027, \u0027/\u0027);\n        var newAbs = Path.Combine(targetFolder, Path.GetFileName(sourceFile));\n        var newRef = string.IsNullOrEmpty(assetsRoot)\n            ? null\n            : Path.GetRelativePath(assetsRoot, newAbs).Replace(\u0027\\\\\u0027, \u0027/\u0027);\n\n        void JustMove()\n        {\n            EditorUtility.MoveAssetToDirectory(asset, targetFolder);\n            onComplete?.Invoke();\n        }\n\n        // Can\u0027t compute a clean reference (asset outside the assets mount) - just move normally\n        if (string.IsNullOrEmpty(oldRef) || string.IsNullOrEmpty(newRef) || newRef.StartsWith(\u0022..\u0022))\n        {\n            JustMove();\n            return;\n        }\n\n        var affected = FindFilesReferencing(oldRef);\n        affected.RemoveAll(f =\u003E string.Equals(Path.GetFullPath(f), Path.GetFullPath(asset.AbsolutePath), StringComparison.OrdinalIgnoreCase));\n\n        var dialog = new MoveReferencesDialog(oldRef, newRef, affected,\n            onJustMove: JustMove,\n            onMoveAndUpdate: () =\u003E\n            {\n                EditorUtility.MoveAssetToDirectory(asset, targetFolder);\n                RewriteReferences(affected, oldRef, newRef);\n                onComplete?.Invoke();\n            });\n        dialog.Show();\n    }\n\n    // Matches the reference only at a path boundary, so \u0022models/foo.vmdl\u0022 doesn\u0027t match inside\n    // \u0022othermodels/foo.vmdl\u0022 or \u0022sub/models/foo.vmdl\u0022. A trailing \u0022_c\u0022 (compiled form) is still matched.\n    private static Regex BuildReferenceRegex(string reference)\n    {\n        return new Regex(@\u0022(?\u003C![\\w./\\\\-])\u0022 \u002B Regex.Escape(reference), RegexOptions.IgnoreCase);\n    }\n\n    // Finds every text-based project file that mentions the given reference path.\n    public static List\u003Cstring\u003E FindFilesReferencing(string reference)\n    {\n        var results = new List\u003Cstring\u003E();\n        if (string.IsNullOrEmpty(reference))\n            return results;\n\n        var root = Project.Current?.GetAssetsPath();\n        if (string.IsNullOrEmpty(root) || !Directory.Exists(root))\n            return results;\n\n        var regex = BuildReferenceRegex(reference);\n\n        foreach (var file in Directory.EnumerateFiles(root, \u0022*\u0022, SearchOption.AllDirectories))\n        {\n            if (!IsScannableTextFile(file))\n                continue;\n\n            try\n            {\n                var info = new FileInfo(file);\n                if (info.Length == 0 || info.Length \u003E 16_000_000)\n                    continue;\n\n                var text = File.ReadAllText(file);\n                if (regex.IsMatch(text))\n                    results.Add(file);\n            }\n            catch\n            {\n                // Ignore unreadable files\n            }\n        }\n\n        return results;\n    }\n\n    // Rewrites the old reference to the new one in each file (covers compiled \u0022_c\u0022 forms too, since\n    // they share the prefix). Re-registers the file afterwards.\n    public static void RewriteReferences(IEnumerable\u003Cstring\u003E files, string oldRef, string newRef)\n    {\n        var regex = BuildReferenceRegex(oldRef);\n\n        foreach (var file in files)\n        {\n            try\n            {\n                var text = File.ReadAllText(file);\n                var updated = regex.Replace(text, _ =\u003E newRef);\n\n                if (updated != text)\n                {\n                    File.WriteAllText(file, updated);\n                    AssetSystem.RegisterFile(file);\n                }\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to update references in \u0027{file}\u0027: {ex.Message}\u0022);\n            }\n        }\n    }\n\n    private static bool IsScannableTextFile(string file)\n    {\n        if (!ShouldRegister(file))\n            return false;\n\n        var ext = Path.GetExtension(file);\n        if (NonTextExtensions.Contains(ext))\n            return false;\n\n        return true;\n    }\n\n    private static bool ShouldRegister(string file)\n    {\n        var name = Path.GetFileName(file);\n        if (name.StartsWith(\u0022.\u0022)) return false;\n        if (name.EndsWith(\u0022_c\u0022, StringComparison.OrdinalIgnoreCase)) return false;\n        if (name.EndsWith(\u0022.meta\u0022, StringComparison.OrdinalIgnoreCase)) return false;\n        if (name.Contains(\u0022.generated\u0022, StringComparison.OrdinalIgnoreCase)) return false;\n        return true;\n    }\n\n    // Deletes a file, also removing its compiled \u0022_c\u0022 sibling. Uses Asset.Delete when registered.\n    public static void DeleteFileWithCompiled(string fullPath, Asset asset)\n    {\n        if (asset != null)\n        {\n            asset.Delete();\n            return;\n        }\n\n        File.Delete(fullPath);\n\n        var compiledPath = fullPath \u002B \u0022_c\u0022;\n        if (File.Exists(compiledPath))\n        {\n            File.Delete(compiledPath);\n        }\n    }\n\n    private static readonly HashSet\u003Cstring\u003E MeshExtensions =\n        new(StringComparer.OrdinalIgnoreCase) { \u0022.fbx\u0022, \u0022.obj\u0022, \u0022.dmx\u0022, \u0022.gltf\u0022, \u0022.glb\u0022 };\n\n    // Builds the right-click menu shown when several files are selected at once.\n    // Shared by the tree view and the icon grid so both behave identically.\n    public static void BuildMultiFileMenu(Menu menu, List\u003C(string Path, Asset Asset)\u003E items, Action onChanged)\n    {\n        if (items == null || items.Count == 0) return;\n\n        int count = items.Count;\n        var assets = items.Where(i =\u003E i.Asset != null).Select(i =\u003E i.Asset).ToList();\n\n        // Asset-type batch options (Create Material (N), Create Texture (N), etc.)\n        bool addedTypeOptions = AddMultiAssetTypeOptions(menu, assets);\n\n        if (addedTypeOptions)\n            menu.AddSeparator();\n\n        menu.AddOption($\u0022Duplicate ({count})\u0022, \u0022file_copy\u0022, () =\u003E\n        {\n            foreach (var it in items)\n                DuplicateFile(it.Path);\n            onChanged?.Invoke();\n        });\n\n        menu.AddOption($\u0022Delete ({count})\u0022, \u0022delete\u0022, () =\u003E\n        {\n            var confirm = new PopupWindow(\n                \u0022Delete Files\u0022,\n                $\u0022Are you sure you want to delete {count} item(s)?\u0022,\n                \u0022Cancel\u0022,\n                new Dictionary\u003Cstring, Action\u003E()\n                {\n                    { \u0022Delete\u0022, () =\u003E\n                        {\n                            foreach (var it in items)\n                            {\n                                try\n                                {\n                                    DeleteFileWithCompiled(it.Path, it.Asset);\n                                }\n                                catch (Exception ex)\n                                {\n                                    Log.Error($\u0022Failed to delete \u0027{it.Path}\u0027: {ex.Message}\u0022);\n                                }\n                            }\n                            onChanged?.Invoke();\n                        }\n                    }\n                }\n            );\n            confirm.Show();\n        });\n    }\n\n    // Adds asset-type specific batch options with a count suffix, e.g. \u0022Create Material (3)\u0022.\n    // Each option auto-creates the result next to every source asset (no save dialog).\n    // Returns true if any option was added.\n    public static bool AddMultiAssetTypeOptions(Menu menu, List\u003CAsset\u003E assets)\n    {\n        if (assets == null || assets.Count == 0) return false;\n\n        var images = assets.Where(a =\u003E a.AssetType == AssetType.ImageFile).ToList();\n        var shaders = assets.Where(a =\u003E a.AssetType == AssetType.Shader).ToList();\n        var meshes = assets.Where(a =\u003E MeshExtensions.Contains(Path.GetExtension(a.AbsolutePath))).ToList();\n\n        bool added = false;\n\n        if (images.Count \u003E 0)\n        {\n            menu.AddOption($\u0022Create Material ({images.Count})\u0022, \u0022image\u0022, () =\u003E\n            {\n                foreach (var a in images) CreateMaterialFromImageAuto(a);\n                Log.Info($\u0022Created {images.Count} material(s)\u0022);\n            });\n            menu.AddOption($\u0022Create Texture ({images.Count})\u0022, \u0022texture\u0022, () =\u003E\n            {\n                foreach (var a in images) CreateTextureFromImageAuto(a);\n            });\n            menu.AddOption($\u0022Create Sprite ({images.Count})\u0022, \u0022emoji_emotions\u0022, () =\u003E\n            {\n                foreach (var a in images) CreateSpriteFromImageAuto(a);\n            });\n            added = true;\n        }\n\n        if (shaders.Count \u003E 0)\n        {\n            if (added) menu.AddSeparator();\n            menu.AddOption($\u0022Create Material ({shaders.Count})\u0022, \u0022image\u0022, () =\u003E\n            {\n                foreach (var a in shaders) CreateMaterialFromShaderAuto(a);\n            });\n            added = true;\n        }\n\n        if (meshes.Count \u003E 0)\n        {\n            if (added) menu.AddSeparator();\n            menu.AddOption($\u0022Create Model ({meshes.Count})\u0022, \u0022view_in_ar\u0022, () =\u003E\n            {\n                foreach (var a in meshes) CreateModelFromMeshAuto(a);\n            });\n            added = true;\n        }\n\n        var sounds = assets.Where(a =\u003E a.AssetType == AssetType.SoundFile).ToList();\n        if (sounds.Count \u003E 0)\n        {\n            if (added) menu.AddSeparator();\n\n            // One sound event per file\n            menu.AddOption($\u0022Create Sound Event ({sounds.Count})\u0022, \u0022graphic_eq\u0022, () =\u003E\n            {\n                foreach (var a in sounds) CreateSoundEventFromAudioAuto(a);\n                Log.Info($\u0022Created {sounds.Count} sound event(s)\u0022);\n            });\n\n            // A single sound event that randomly picks between all the selected sounds\n            menu.AddOption($\u0022Create Random Sound Event ({sounds.Count})\u0022, \u0022shuffle\u0022, () =\u003E\n            {\n                CreateRandomSoundEventFromAudios(sounds);\n            });\n\n            added = true;\n        }\n\n        return added;\n    }\n\n    /// \u003Csummary\u003E\n    /// Add asset-type specific options like Create Material, Create Texture, etc.\n    /// \u003C/summary\u003E\n    public static void AddAssetTypeOptions(Menu menu, Asset asset)\n    {\n        if (asset == null) return;\n\n        var assetType = asset.AssetType;\n        if (assetType == null) return;\n\n        // Image files - can create Material, Texture, Sprite\n        if (assetType == AssetType.ImageFile)\n        {\n            menu.AddSeparator();\n            menu.AddOption(\u0022Create Material\u0022, \u0022image\u0022, () =\u003E CreateMaterialFromImage(asset));\n            menu.AddOption(\u0022Create Texture\u0022, \u0022texture\u0022, () =\u003E CreateTextureFromImage(asset));\n            menu.AddOption(\u0022Create Sprite\u0022, \u0022emoji_emotions\u0022, () =\u003E CreateSpriteFromImage(asset));\n        }\n\n        // Shader files - can create Material\n        if (assetType == AssetType.Shader)\n        {\n            menu.AddSeparator();\n            menu.AddOption(\u0022Create Material\u0022, \u0022image\u0022, () =\u003E CreateMaterialFromShader(asset));\n        }\n\n        // Mesh files (FBX, OBJ) - can create Model\n        if (MeshExtensions.Contains(Path.GetExtension(asset.AbsolutePath)))\n        {\n            menu.AddSeparator();\n            menu.AddOption(\u0022Create Model\u0022, \u0022view_in_ar\u0022, () =\u003E CreateModelFromMesh(asset));\n        }\n\n        // Sound files - can create a Sound Event\n        if (assetType == AssetType.SoundFile)\n        {\n            menu.AddSeparator();\n            menu.AddOption(\u0022Create Sound Event\u0022, \u0022graphic_eq\u0022, () =\u003E CreateSoundEventFromAudio(asset));\n        }\n    }\n\n    private static void CreateTextureFromImage(Asset asset)\n    {\n        var fd = new FileDialog(null);\n        fd.Title = \u0022Create Texture from Image..\u0022;\n        fd.Directory = Path.GetDirectoryName(asset.AbsolutePath);\n        fd.DefaultSuffix = \u0022.vtex\u0022;\n        fd.SelectFile($\u0022{asset.Name}.vtex\u0022);\n        fd.SetFindFile();\n        fd.SetModeSave();\n        fd.SetNameFilter(\u0022Texture File (*.vtex)\u0022);\n\n        if (!fd.Execute())\n            return;\n\n        File.WriteAllText(fd.SelectedFile, BuildVtexContent(asset));\n        AssetSystem.RegisterFile(fd.SelectedFile);\n    }\n\n    private static void CreateMaterialFromImage(Asset asset)\n    {\n        var fd = new FileDialog(null);\n        fd.Title = \u0022Create Material from Image..\u0022;\n        fd.Directory = Path.GetDirectoryName(asset.AbsolutePath);\n        fd.DefaultSuffix = \u0022.vmat\u0022;\n        fd.SelectFile($\u0022{GetMaterialBaseName(asset)}.vmat\u0022);\n        fd.SetFindFile();\n        fd.SetModeSave();\n        fd.SetNameFilter(\u0022Material File (*.vmat)\u0022);\n\n        if (!fd.Execute())\n            return;\n\n        File.WriteAllText(fd.SelectedFile, BuildImageMaterialContent(asset));\n        AssetSystem.RegisterFile(fd.SelectedFile);\n    }\n\n    private static async void CreateSpriteFromImage(Asset asset)\n    {\n        var fd = new FileDialog(null);\n        fd.Title = \u0022Create Sprite from Image..\u0022;\n        fd.Directory = Path.GetDirectoryName(asset.AbsolutePath);\n        fd.DefaultSuffix = \u0022.sprite\u0022;\n        fd.SelectFile($\u0022{asset.Name}.sprite\u0022);\n        fd.SetFindFile();\n        fd.SetModeSave();\n        fd.SetNameFilter(\u0022Sprite File (*.sprite)\u0022);\n\n        if (!fd.Execute())\n            return;\n\n        File.WriteAllText(fd.SelectedFile, BuildSpriteContent(asset));\n\n        var resultAsset = AssetSystem.RegisterFile(fd.SelectedFile);\n        while (!resultAsset.IsCompiledAndUpToDate)\n        {\n            await Task.Delay(10);\n        }\n    }\n\n    private static void CreateMaterialFromShader(Asset asset)\n    {\n        var fd = new FileDialog(null);\n        fd.Title = \u0022Create Material from Shader..\u0022;\n        fd.Directory = Path.GetDirectoryName(asset.AbsolutePath);\n        fd.DefaultSuffix = \u0022.vmat\u0022;\n        fd.SelectFile($\u0022{asset.Name}.vmat\u0022);\n        fd.SetFindFile();\n        fd.SetModeSave();\n        fd.SetNameFilter(\u0022Material File (*.vmat)\u0022);\n\n        if (!fd.Execute())\n            return;\n\n        File.WriteAllText(fd.SelectedFile, BuildShaderMaterialContent(asset));\n        AssetSystem.RegisterFile(fd.SelectedFile);\n    }\n\n    private static void CreateModelFromMesh(Asset asset)\n    {\n        var targetPath = EditorUtility.SaveFileDialog(\u0022Create Model..\u0022, \u0022vmdl\u0022, Path.ChangeExtension(asset.AbsolutePath, \u0022vmdl\u0022));\n        if (targetPath == null)\n            return;\n\n        EditorUtility.CreateModelFromMeshFile(asset, targetPath);\n    }\n\n    private static void CreateSoundEventFromAudio(Asset asset)\n    {\n        var fd = new FileDialog(null);\n        fd.Title = \u0022Create Sound Event..\u0022;\n        fd.Directory = Path.GetDirectoryName(asset.AbsolutePath);\n        fd.DefaultSuffix = \u0022.sound\u0022;\n        fd.SelectFile($\u0022{asset.Name}.sound\u0022);\n        fd.SetFindFile();\n        fd.SetModeSave();\n        fd.SetNameFilter(\u0022Sound Event (*.sound)\u0022);\n\n        if (!fd.Execute())\n            return;\n\n        File.WriteAllText(fd.SelectedFile, BuildSoundEventContent(new[] { GetVsndReference(asset) }));\n        AssetSystem.RegisterFile(fd.SelectedFile);\n    }\n\n    // ===== Batch creators: auto-name next to each source asset, skip if it already exists =====\n\n    private static void CreateMaterialFromImageAuto(Asset asset)\n    {\n        var directory = Path.GetDirectoryName(asset.AbsolutePath);\n        var destPath = Path.Combine(directory, $\u0022{GetMaterialBaseName(asset)}.vmat\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        File.WriteAllText(destPath, BuildImageMaterialContent(asset));\n        AssetSystem.RegisterFile(destPath);\n    }\n\n    private static void CreateTextureFromImageAuto(Asset asset)\n    {\n        var directory = Path.GetDirectoryName(asset.AbsolutePath);\n        var destPath = Path.Combine(directory, $\u0022{asset.Name}.vtex\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        File.WriteAllText(destPath, BuildVtexContent(asset));\n        AssetSystem.RegisterFile(destPath);\n    }\n\n    private static async void CreateSpriteFromImageAuto(Asset asset)\n    {\n        var directory = Path.GetDirectoryName(asset.AbsolutePath);\n        var destPath = Path.Combine(directory, $\u0022{asset.Name}.sprite\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        File.WriteAllText(destPath, BuildSpriteContent(asset));\n\n        var resultAsset = AssetSystem.RegisterFile(destPath);\n        while (!resultAsset.IsCompiledAndUpToDate)\n        {\n            await Task.Delay(10);\n        }\n    }\n\n    private static void CreateMaterialFromShaderAuto(Asset asset)\n    {\n        var directory = Path.GetDirectoryName(asset.AbsolutePath);\n        var destPath = Path.Combine(directory, $\u0022{asset.Name}.vmat\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        File.WriteAllText(destPath, BuildShaderMaterialContent(asset));\n        AssetSystem.RegisterFile(destPath);\n    }\n\n    private static void CreateModelFromMeshAuto(Asset asset)\n    {\n        var destPath = Path.ChangeExtension(asset.AbsolutePath, \u0022vmdl\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        EditorUtility.CreateModelFromMeshFile(asset, destPath);\n    }\n\n    private static void CreateSoundEventFromAudioAuto(Asset asset)\n    {\n        var directory = Path.GetDirectoryName(asset.AbsolutePath);\n        var destPath = Path.Combine(directory, $\u0022{asset.Name}.sound\u0022);\n        if (File.Exists(destPath))\n            return;\n\n        File.WriteAllText(destPath, BuildSoundEventContent(new[] { GetVsndReference(asset) }));\n        AssetSystem.RegisterFile(destPath);\n    }\n\n    // Creates a single sound event that randomly picks between all the given audio files.\n    private static void CreateRandomSoundEventFromAudios(List\u003CAsset\u003E assets)\n    {\n        if (assets == null || assets.Count == 0)\n            return;\n\n        var first = assets[0];\n        var directory = Path.GetDirectoryName(first.AbsolutePath);\n        var destPath = FindFreePath(directory, GetSoundBaseName(first), \u0022.sound\u0022);\n\n        var references = assets.Select(GetVsndReference).ToList();\n        File.WriteAllText(destPath, BuildSoundEventContent(references));\n        AssetSystem.RegisterFile(destPath);\n    }\n\n    // ===== Content builders shared by single and batch creators =====\n\n    // Strips trailing texture-role suffixes (_color, _normal, ...) to get the material base name.\n    private static string GetMaterialBaseName(Asset asset)\n    {\n        string[] suffixes = { \u0022color\u0022, \u0022ao\u0022, \u0022normal\u0022, \u0022metallic\u0022, \u0022rough\u0022, \u0022diff\u0022, \u0022diffuse\u0022, \u0022nrm\u0022, \u0022spec\u0022, \u0022selfillum\u0022, \u0022mask\u0022 };\n\n        var assetName = asset.Name;\n        foreach (var t in suffixes)\n        {\n            if (assetName.EndsWith($\u0022_{t}\u0022))\n                assetName = assetName.Substring(0, assetName.Length - (t.Length \u002B 1));\n        }\n        return assetName;\n    }\n\n    // Builds a complex.shader material, auto-wiring sibling textures (normal/ao/rough/...) by name.\n    private static string BuildImageMaterialContent(Asset asset)\n    {\n        var assetName = GetMaterialBaseName(asset);\n\n        var assetPath = Path.GetDirectoryName(asset.AbsolutePath).NormalizeFilename(false);\n        var assetPeers = AssetSystem.All\n            .Where(x =\u003E x.AssetType == AssetType.ImageFile)\n            .Where(x =\u003E x.AbsolutePath.StartsWith(assetPath))\n            .ToArray();\n\n        var assetPeersWithSameBaseName = assetPeers\n            .Where(x =\u003E x.Name == assetName || x.Name.StartsWith(assetName \u002B \u0022_\u0022))\n            .ToArray();\n\n        if (assetPeersWithSameBaseName.Length \u003E 0)\n        {\n            assetPeers = assetPeersWithSameBaseName;\n        }\n\n        string texColor = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_color\u0022) || x.Name.Contains(\u0022_diff\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault();\n        texColor ??= asset.RelativePath;\n\n        string texNormal = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_nrm\u0022) || x.Name.Contains(\u0022_normal\u0022) || x.Name.Contains(\u0022_amb\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault() ?? \u0022materials/default/default_normal.tga\u0022;\n        string texAo = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_ao\u0022) || x.Name.Contains(\u0022_occ\u0022) || x.Name.Contains(\u0022_amb\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault() ?? \u0022materials/default/default_ao.tga\u0022;\n        string texRough = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_rough\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault() ?? \u0022materials/default/default_rough.tga\u0022;\n\n        string texMetallic = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_metallic\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault();\n        if (texMetallic != null)\n        {\n            texMetallic = $\u0022\\n\\tF_METALNESS_TEXTURE 1\\n\\tF_SPECULAR 1\\n\\tTextureMetalness \\\u0022{texMetallic}\\\u0022\u0022;\n        }\n\n        string texSelfIllum = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_selfillum\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault();\n        if (texSelfIllum != null)\n        {\n            texSelfIllum = $\u0022\\n\\tF_SELF_ILLUM 1\\n\\tTextureSelfIllumMask \\\u0022{texSelfIllum}\\\u0022\u0022;\n        }\n\n        string tintMask = assetPeers.Where(x =\u003E x.Name.Contains(\u0022_mask\u0022)).Select(x =\u003E x.RelativePath).FirstOrDefault();\n        if (tintMask != null)\n        {\n            tintMask = $\u0022\\n\\tF_TINT_MASK 1\\n\\tTextureTintMask \\\u0022{tintMask}\\\u0022\u0022;\n        }\n\n        return $@\u0022\nLayer0\n{{\n\tshader \u0022\u0022shaders/complex.shader_c\u0022\u0022\n\n\tTextureColor \u0022\u0022{texColor}\u0022\u0022\n\tTextureAmbientOcclusion \u0022\u0022{texAo}\u0022\u0022\n\tTextureNormal \u0022\u0022{texNormal}\u0022\u0022\n\tTextureRoughness \u0022\u0022{texRough}\u0022\u0022{texMetallic}{texSelfIllum}{tintMask}\n\n}}\n\u0022;\n    }\n\n    private static string BuildShaderMaterialContent(Asset asset)\n    {\n        var shaderPath = asset.GetCompiledFile();\n\n        return $@\u0022\nLayer0\n{{\n\tshader \u0022\u0022{shaderPath}\u0022\u0022\n\n}}\n\u0022;\n    }\n\n    private static string BuildVtexContent(Asset asset)\n    {\n        var vtexContent = new Dictionary\u003Cstring, object\u003E\n        {\n            { \u0022Sequences\u0022, new object[]\n                {\n                    new Dictionary\u003Cstring, object\u003E\n                    {\n                        { \u0022Source\u0022, asset.RelativePath },\n                        { \u0022IsLooping\u0022, true }\n                    }\n                }\n            }\n        };\n\n        return Json.Serialize(vtexContent);\n    }\n\n    private static string BuildSpriteContent(Asset asset)\n    {\n        var path = Path.ChangeExtension(asset.Path, Path.GetExtension(asset.AbsolutePath));\n        var sprite = Sprite.FromTexture(Texture.Load(path));\n        return sprite.Serialize().ToJsonString();\n    }\n\n    // Builds a .sound (SoundEvent) resource that plays a random sound from the given references.\n    private static string BuildSoundEventContent(IEnumerable\u003Cstring\u003E vsndReferences)\n    {\n        var content = new Dictionary\u003Cstring, object\u003E\n        {\n            { \u0022Volume\u0022, \u00221\u0022 },\n            { \u0022Pitch\u0022, \u00221\u0022 },\n            { \u0022SelectionMode\u0022, \u0022Random\u0022 },\n            { \u0022Sounds\u0022, vsndReferences.ToArray() },\n            { \u0022__version\u0022, 1 }\n        };\n\n        return Json.Serialize(content);\n    }\n\n    // Sound events reference the compiled .vsnd, regardless of the source file extension.\n    private static string GetVsndReference(Asset asset)\n    {\n        return Path.ChangeExtension(asset.RelativePath, \u0022vsnd\u0022).Replace(\u0027\\\\\u0027, \u0027/\u0027);\n    }\n\n    // Strips a trailing numeric index so \u0022footstep_01\u0022 -\u003E \u0022footstep\u0022 for naming a combined event.\n    private static string GetSoundBaseName(Asset asset)\n    {\n        var name = asset.Name;\n        var underscore = name.LastIndexOf(\u0027_\u0027);\n        if (underscore \u003E 0 \u0026\u0026 int.TryParse(name.Substring(underscore \u002B 1), out _))\n            name = name.Substring(0, underscore);\n        return name;\n    }\n\n    private static string FindFreePath(string directory, string baseName, string extension)\n    {\n        var path = Path.Combine(directory, $\u0022{baseName}{extension}\u0022);\n\n        int counter = 1;\n        while (File.Exists(path))\n            path = Path.Combine(directory, $\u0022{baseName}_{counter\u002B\u002B}{extension}\u0022);\n\n        return path;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/CloudAssetPanel.cs","FileName":"CloudAssetPanel.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Panel for browsing cloud assets from the S\u0026box community as a tree view.\n/// Shows categories with auto-loaded items and supports per-category search.\n/// \u003C/summary\u003E\npublic class CloudAssetPanel : Widget, IBrowserPanel\n{\n    private Widget _toolbar;\n    private LineEdit _searchEdit;\n    private IconButton _closeBtn;\n    private IconButton _searchBtn;\n    private IconButton _clearSearchBtn;\n    private IconButton _refreshBtn;\n    private IconButton _moveLeftBtn;\n    private IconButton _moveRightBtn;\n    private TreeView _treeView;\n    private Label _statusLabel;\n\n    private const int InitialItemsPerCategory = 10;\n    private const int SearchItemsPerCategory = 20;\n    private bool _isSearchMode = false;\n    private string _currentSearchQuery = \u0022\u0022;\n\n    public Action OnCloseRequested { get; set; }\n    public Action OnMoveLeftRequested { get; set; }\n    public Action OnMoveRightRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Called when a cloud category/folder is clicked (for syncing with preview panels)\n    /// \u003C/summary\u003E\n    public Action\u003CList\u003CPackage\u003E\u003E OnCloudAssetsLoaded;\n\n    public bool ShowCloseButton\n    {\n        get =\u003E _closeBtn?.Visible ?? false;\n        set\n        {\n            if (_closeBtn != null)\n                _closeBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveLeftButton\n    {\n        get =\u003E _moveLeftBtn?.Visible ?? false;\n        set\n        {\n            if (_moveLeftBtn != null)\n                _moveLeftBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveRightButton\n    {\n        get =\u003E _moveRightBtn?.Visible ?? false;\n        set\n        {\n            if (_moveRightBtn != null)\n                _moveRightBtn.Visible = value;\n        }\n    }\n\n    public CloudAssetPanel(Widget parent) : base(parent)\n    {\n        SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n        CreateUI();\n        BuildCategoryTree();\n\n        // Auto-load initial items for all categories\n        _ = LoadAllCategoriesAsync();\n    }\n\n    private void CreateUI()\n    {\n        Layout = Layout.Column();\n        Layout.Spacing = 4;\n        Layout.Margin = 4;\n\n        // Toolbar\n        _toolbar = Layout.Add(new Widget(this));\n        _toolbar.Layout = Layout.Row();\n        _toolbar.Layout.Spacing = 4;\n        _toolbar.FixedHeight = 28;\n\n        // Cloud icon\n        var cloudIcon = _toolbar.Layout.Add(new Label(\u0022cloud\u0022, this));\n        cloudIcon.SetStyles(\u0022font-family: Material Icons; font-size: 16px; color: #888;\u0022);\n        cloudIcon.FixedWidth = 20;\n\n        // Search input\n        _searchEdit = _toolbar.Layout.Add(new LineEdit(this));\n        _searchEdit.PlaceholderText = \u0022Search cloud...\u0022;\n        _searchEdit.ReturnPressed \u002B= DoSearch;\n\n        // Search button\n        _searchBtn = _toolbar.Layout.Add(new IconButton(\u0022search\u0022));\n        _searchBtn.ToolTip = \u0022Search\u0022;\n        _searchBtn.Background = Color.Transparent;\n        _searchBtn.OnClick = DoSearch;\n\n        // Clear search button\n        _clearSearchBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _clearSearchBtn.ToolTip = \u0022Clear Search\u0022;\n        _clearSearchBtn.Background = Color.Transparent;\n        _clearSearchBtn.OnClick = ClearSearch;\n        _clearSearchBtn.Visible = false;\n\n        // Refresh button\n        _refreshBtn = _toolbar.Layout.Add(new IconButton(\u0022refresh\u0022));\n        _refreshBtn.ToolTip = \u0022Refresh All\u0022;\n        _refreshBtn.Background = Color.Transparent;\n        _refreshBtn.OnClick = RefreshAll;\n\n        _toolbar.Layout.AddStretchCell();\n\n        _moveLeftBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_left\u0022));\n        _moveLeftBtn.ToolTip = \u0022Move Panel Left\u0022;\n        _moveLeftBtn.Background = Color.Transparent;\n        _moveLeftBtn.OnClick = () =\u003E OnMoveLeftRequested?.Invoke();\n        _moveLeftBtn.Visible = false;\n\n        _moveRightBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_right\u0022));\n        _moveRightBtn.ToolTip = \u0022Move Panel Right\u0022;\n        _moveRightBtn.Background = Color.Transparent;\n        _moveRightBtn.OnClick = () =\u003E OnMoveRightRequested?.Invoke();\n        _moveRightBtn.Visible = false;\n\n        // Close button\n        _closeBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _closeBtn.ToolTip = \u0022Close Panel\u0022;\n        _closeBtn.Background = Color.Transparent;\n        _closeBtn.OnClick = () =\u003E OnCloseRequested?.Invoke();\n        _closeBtn.Visible = false;\n\n        // Tree view\n        _treeView = Layout.Add(new TreeView(this));\n        _treeView.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n        _treeView.MultiSelect = false;\n        _treeView.ItemSpacing = 1;\n        _treeView.IndentWidth = 16;\n\n        _treeView.ItemActivated \u002B= OnItemActivated;\n        _treeView.OnSelectionChanged \u002B= OnSelectionChanged;\n\n        // Status label at bottom\n        _statusLabel = Layout.Add(new Label(\u0022Loading...\u0022, this));\n        _statusLabel.SetStyles(\u0022color: #888; font-size: 10px; padding: 2px;\u0022);\n        _statusLabel.FixedHeight = 18;\n    }\n\n    private List\u003CCloudCategoryNode\u003E _categoryNodes = new();\n\n    private void BuildCategoryTree()\n    {\n        _treeView.Clear();\n        _categoryNodes.Clear();\n\n        // Add category folders - filter format: \u0022type:model\u0022, \u0022type:material\u0022, etc.\n        var models = new CloudCategoryNode(\u0022model\u0022, \u0022Models\u0022, \u0022view_in_ar\u0022, this);\n        var materials = new CloudCategoryNode(\u0022material\u0022, \u0022Materials\u0022, \u0022texture\u0022, this);\n        var sounds = new CloudCategoryNode(\u0022sound\u0022, \u0022Sounds\u0022, \u0022audiotrack\u0022, this);\n        var maps = new CloudCategoryNode(\u0022map\u0022, \u0022Maps\u0022, \u0022landscape\u0022, this);\n\n        _categoryNodes.Add(models);\n        _categoryNodes.Add(materials);\n        _categoryNodes.Add(sounds);\n        _categoryNodes.Add(maps);\n\n        foreach (var node in _categoryNodes)\n        {\n            _treeView.AddItem(node);\n        }\n\n        _treeView.Update();\n    }\n\n    /// \u003Csummary\u003E\n    /// Load initial items for all categories on startup\n    /// \u003C/summary\u003E\n    private async Task LoadAllCategoriesAsync()\n    {\n        _statusLabel.Text = \u0022Loading categories...\u0022;\n        int totalLoaded = 0;\n\n        foreach (var categoryNode in _categoryNodes)\n        {\n            try\n            {\n                // Query format: \u0022type:model\u0022, \u0022type:material\u0022, etc.\n                var query = $\u0022type:{categoryNode.TypeFilter}\u0022;\n                var result = await Package.FindAsync(query, InitialItemsPerCategory, 0);\n\n                if (result?.Packages != null)\n                {\n                    categoryNode.SetPackagesAndRefresh(result.Packages.ToList());\n                    totalLoaded \u002B= categoryNode.Packages.Count;\n                }\n            }\n            catch (Exception ex)\n            {\n                Log.Warning($\u0022[CloudAssetPanel] Failed to load {categoryNode.DisplayName}: {ex.Message}\u0022);\n            }\n        }\n\n        _treeView.Update();\n        _statusLabel.Text = $\u0022Loaded {totalLoaded} cloud assets\u0022;\n    }\n\n    private async void DoSearch()\n    {\n        var query = _searchEdit.Text?.Trim() ?? \u0022\u0022;\n        if (string.IsNullOrEmpty(query))\n        {\n            ClearSearch();\n            return;\n        }\n\n        _currentSearchQuery = query;\n        _isSearchMode = true;\n        _searchBtn.Enabled = false;\n        _clearSearchBtn.Visible = true;\n        _statusLabel.Text = $\u0022Searching \\\u0022{query}\\\u0022...\u0022;\n\n        try\n        {\n            int totalFound = 0;\n\n            // Search in each category\n            foreach (var categoryNode in _categoryNodes)\n            {\n                try\n                {\n                    // Combine search query with type filter\n                    var searchQuery = $\u0022{query} type:{categoryNode.TypeFilter}\u0022;\n                    var result = await Package.FindAsync(searchQuery, SearchItemsPerCategory, 0);\n\n                    if (result?.Packages != null \u0026\u0026 result.Packages.Any())\n                    {\n                        categoryNode.SetPackagesAndRefresh(result.Packages.ToList());\n                        totalFound \u002B= result.Packages.Count();\n                        // Auto-expand categories that have search results\n                        _treeView.Open(categoryNode);\n                    }\n                    else\n                    {\n                        categoryNode.SetPackagesAndRefresh(new List\u003CPackage\u003E());\n                        // Collapse empty categories\n                        _treeView.Close(categoryNode);\n                    }\n                }\n                catch (Exception ex)\n                {\n                    Log.Warning($\u0022Search error in {categoryNode.DisplayName}: {ex.Message}\u0022);\n                }\n            }\n\n            _treeView.Update();\n            _statusLabel.Text = $\u0022Found {totalFound} results for \\\u0022{query}\\\u0022\u0022;\n\n            // Notify with all found packages\n            var allPackages = _categoryNodes.SelectMany(c =\u003E c.Packages).ToList();\n            if (allPackages.Any())\n            {\n                OnCloudAssetsLoaded?.Invoke(allPackages);\n            }\n        }\n        catch (Exception ex)\n        {\n            _statusLabel.Text = $\u0022Search error: {ex.Message}\u0022;\n            Log.Warning($\u0022Cloud search error: {ex.Message}\u0022);\n        }\n        finally\n        {\n            _searchBtn.Enabled = true;\n        }\n    }\n\n    private void ClearSearch()\n    {\n        _searchEdit.Text = \u0022\u0022;\n        _currentSearchQuery = \u0022\u0022;\n        _isSearchMode = false;\n        _clearSearchBtn.Visible = false;\n\n        // Reload all categories with default items\n        foreach (var node in _categoryNodes)\n        {\n            node.ClearPackages();\n        }\n        _ = LoadAllCategoriesAsync();\n    }\n\n    private async void RefreshAll()\n    {\n        foreach (var node in _categoryNodes)\n        {\n            node.ClearPackages();\n        }\n\n        if (_isSearchMode \u0026\u0026 !string.IsNullOrEmpty(_currentSearchQuery))\n        {\n            DoSearch();\n        }\n        else\n        {\n            await LoadAllCategoriesAsync();\n        }\n    }\n\n    private void OnItemActivated(object item)\n    {\n        if (item is CloudCategoryNode categoryNode)\n        {\n            _treeView.Toggle(categoryNode);\n        }\n        else if (item is CloudPackageNode packageNode)\n        {\n            // Open package page in browser\n            var url = $\u0022https://sbox.game/{packageNode.FullIdent}\u0022;\n            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n            {\n                FileName = url,\n                UseShellExecute = true\n            });\n        }\n        else if (item is CloudLoadMoreNode loadMoreNode)\n        {\n            _ = LoadMoreForCategory(loadMoreNode.Category);\n        }\n    }\n\n    private async Task LoadMoreForCategory(CloudCategoryNode categoryNode)\n    {\n        if (categoryNode.IsLoadingMore)\n            return;\n\n        categoryNode.IsLoadingMore = true;\n        var currentCount = categoryNode.Packages.Count;\n        _statusLabel.Text = $\u0022Loading more {categoryNode.DisplayName.ToLower()}...\u0022;\n\n        try\n        {\n            string query;\n            if (_isSearchMode \u0026\u0026 !string.IsNullOrEmpty(_currentSearchQuery))\n            {\n                query = $\u0022{_currentSearchQuery} type:{categoryNode.TypeFilter}\u0022;\n            }\n            else\n            {\n                query = $\u0022type:{categoryNode.TypeFilter}\u0022;\n            }\n\n            var result = await Package.FindAsync(query, 20, currentCount);\n\n            if (result?.Packages != null \u0026\u0026 result.Packages.Any())\n            {\n                categoryNode.AppendPackagesAndRefresh(result.Packages.ToList());\n                _treeView.Update();\n                _statusLabel.Text = $\u0022Loaded {categoryNode.Packages.Count} {categoryNode.DisplayName.ToLower()}\u0022;\n                OnCloudAssetsLoaded?.Invoke(categoryNode.Packages);\n            }\n            else\n            {\n                _statusLabel.Text = $\u0022No more {categoryNode.DisplayName.ToLower()} found\u0022;\n            }\n        }\n        catch (Exception ex)\n        {\n            _statusLabel.Text = $\u0022Error: {ex.Message}\u0022;\n            Log.Warning($\u0022Load more error: {ex.Message}\u0022);\n        }\n        finally\n        {\n            categoryNode.IsLoadingMore = false;\n        }\n    }\n\n    private void OnSelectionChanged(object[] items)\n    {\n        var item = items.FirstOrDefault();\n\n        if (item is CloudCategoryNode categoryNode)\n        {\n            if (categoryNode.Packages.Count \u003E 0)\n            {\n                _statusLabel.Text = $\u0022{categoryNode.Packages.Count} {categoryNode.DisplayName.ToLower()}\u0022;\n                OnCloudAssetsLoaded?.Invoke(categoryNode.Packages);\n            }\n        }\n        else if (item is CloudPackageNode packageNode)\n        {\n            _statusLabel.Text = $\u0022{packageNode.Title} by {packageNode.Author}\u0022;\n        }\n    }\n}\n\n/// \u003Csummary\u003E\n/// Tree node representing a cloud asset category (Models, Materials, etc.)\n/// \u003C/summary\u003E\ninternal class CloudCategoryNode : TreeNode\n{\n    public string TypeFilter { get; }\n    public string DisplayName { get; }\n    public string IconName { get; }\n    public bool IsLoadingMore { get; set; }\n    public List\u003CPackage\u003E Packages { get; private set; } = new();\n\n    private CloudAssetPanel _panel;\n\n    // Always show expand arrow - categories always have potential children\n    public override bool HasChildren =\u003E true;\n    public override string Name =\u003E DisplayName;\n\n    public CloudCategoryNode(string typeFilter, string displayName, string icon, CloudAssetPanel panel)\n    {\n        TypeFilter = typeFilter;\n        DisplayName = displayName;\n        IconName = icon;\n        _panel = panel;\n        Value = this;\n    }\n\n    public void ClearPackages()\n    {\n        Packages.Clear();\n        Clear();\n        Dirty();\n    }\n\n    public void SetPackagesAndRefresh(List\u003CPackage\u003E packages)\n    {\n        Packages = packages;\n\n        // Clear and rebuild children\n        Clear();\n\n        foreach (var pkg in Packages)\n        {\n            AddItem(new CloudPackageNode(pkg));\n        }\n\n        // Always add \u0022Load More\u0022 node\n        AddItem(new CloudLoadMoreNode(this));\n\n        Dirty();\n    }\n\n    public void AppendPackagesAndRefresh(List\u003CPackage\u003E newPackages)\n    {\n        Packages.AddRange(newPackages);\n\n        // Clear and rebuild children\n        Clear();\n\n        foreach (var pkg in Packages)\n        {\n            AddItem(new CloudPackageNode(pkg));\n        }\n\n        // Add \u0022Load More\u0022 node\n        AddItem(new CloudLoadMoreNode(this));\n\n        Dirty();\n    }\n\n    protected override void BuildChildren()\n    {\n        // Children are built via SetPackagesAndRefresh/AppendPackagesAndRefresh\n        // This is called by TreeView when expanding - we already have children built\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        // Draw folder icon\n        var iconColor = Theme.Yellow;\n        if (IsLoadingMore)\n            iconColor = Theme.Primary;\n\n        Paint.SetPen(iconColor);\n        Paint.DrawIcon(rect, IconName, 16, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 22;\n\n        // Draw name\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont(9, item.Selected ? 600 : 400);\n        Paint.DrawText(rect, DisplayName, TextFlag.LeftCenter);\n\n        // Draw count\n        var countText = $\u0022({Packages.Count})\u0022;\n        Paint.SetPen(Theme.Text.WithAlpha(0.5f));\n        Paint.SetDefaultFont(8, 400);\n        var countRect = new Rect(item.Rect.Right - 50, item.Rect.Top, 46, item.Rect.Height);\n        Paint.DrawText(countRect, countText, TextFlag.RightCenter);\n    }\n}\n\n/// \u003Csummary\u003E\n/// Tree node for \u0022Load More\u0022 action\n/// \u003C/summary\u003E\ninternal class CloudLoadMoreNode : TreeNode\n{\n    public CloudCategoryNode Category { get; }\n\n    public override bool HasChildren =\u003E false;\n    public override string Name =\u003E \u0022Load More...\u0022;\n\n    public CloudLoadMoreNode(CloudCategoryNode category)\n    {\n        Category = category;\n        Value = this;\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        var rect = item.Rect;\n\n        // Draw load more icon\n        Paint.SetPen(Theme.Primary.WithAlpha(0.7f));\n        Paint.DrawIcon(rect, \u0022add_circle_outline\u0022, 14, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 20;\n\n        // Draw text\n        Paint.SetPen(Theme.Primary);\n        Paint.SetDefaultFont(8, 400);\n        Paint.DrawText(rect, \u0022Load More...\u0022, TextFlag.LeftCenter);\n    }\n}\n\n/// \u003Csummary\u003E\n/// Tree node representing a single cloud package/asset\n/// \u003C/summary\u003E\ninternal class CloudPackageNode : TreeNode\n{\n    public Package Package { get; }\n    public string FullIdent { get; }\n    public string Title { get; }\n    public string Author { get; }\n    public string Thumb { get; }\n\n    public override bool HasChildren =\u003E false;\n    public override string Name =\u003E Title;\n\n    public CloudPackageNode(Package package)\n    {\n        Package = package;\n        FullIdent = package.FullIdent;\n        Title = package.Title ?? package.FullIdent;\n        Author = package.Org?.Title ?? \u0022Unknown\u0022;\n        Thumb = package.Thumb;\n        Value = this;\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        // Draw package thumbnail if available, otherwise use type icon\n        if (!string.IsNullOrEmpty(Thumb) \u0026\u0026 Thumb.StartsWith(\u0022http\u0022))\n        {\n            var iconRect = rect.Shrink(0, 2);\n            iconRect.Width = 16;\n            iconRect.Height = 16;\n\n            Paint.Draw(iconRect, Thumb);\n            rect.Left \u002B= 20;\n        }\n        else\n        {\n            // Fallback to type icon\n            var icon = GetIconForType(Package.TypeName);\n            var iconColor = GetColorForType(Package.TypeName);\n\n            Paint.SetPen(iconColor);\n            Paint.DrawIcon(rect, icon, 14, TextFlag.LeftCenter);\n            rect.Left \u002B= 20;\n        }\n\n        // Draw title\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont(9, item.Selected ? 600 : 400);\n\n        var title = Title;\n        if (title.Length \u003E 30)\n            title = title.Substring(0, 28) \u002B \u0022..\u0022;\n        Paint.DrawText(rect, title, TextFlag.LeftCenter);\n    }\n\n    public override bool OnDragStart()\n    {\n        var drag = new Drag(TreeView);\n        drag.Data.Text = FullIdent;\n\n        // Set preview image if available\n        if (!string.IsNullOrEmpty(Thumb))\n        {\n            drag.Data.Url = new Uri(Thumb);\n        }\n\n        drag.Execute();\n        return true;\n    }\n\n    public override bool OnContextMenu()\n    {\n        var menu = new ContextMenu(null);\n\n        menu.AddOption(\u0022Open in Browser\u0022, \u0022open_in_new\u0022, () =\u003E\n        {\n            var url = $\u0022https://sbox.game/{FullIdent}\u0022;\n            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n            {\n                FileName = url,\n                UseShellExecute = true\n            });\n        });\n\n        menu.AddOption(\u0022Copy Identifier\u0022, \u0022content_copy\u0022, () =\u003E\n        {\n            EditorUtility.Clipboard.Copy(FullIdent);\n        });\n\n        menu.OpenAtCursor();\n        return true;\n    }\n\n    private static string GetIconForType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E \u0022view_in_ar\u0022,\n            \u0022material\u0022 =\u003E \u0022texture\u0022,\n            \u0022sound\u0022 =\u003E \u0022audiotrack\u0022,\n            \u0022map\u0022 =\u003E \u0022landscape\u0022,\n            _ =\u003E \u0022cloud_download\u0022\n        };\n    }\n\n    private static Color GetColorForType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E new Color(0.9f, 0.6f, 0.3f),\n            \u0022material\u0022 =\u003E new Color(0.9f, 0.4f, 0.6f),\n            \u0022sound\u0022 =\u003E new Color(0.4f, 0.7f, 1.0f),\n            \u0022map\u0022 =\u003E new Color(0.9f, 0.9f, 0.3f),\n            _ =\u003E Theme.Text.WithAlpha(0.7f)\n        };\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/PanelSplitter.cs","FileName":"PanelSplitter.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing System;\n\nnamespace GeneralGame.Editor;\n\npublic class PanelSplitter : Widget\n{\n    public const float Thickness = 6f;\n    private const float MinPanelWidth = 150f;\n\n    private readonly Widget _left;\n    private readonly Widget _right;\n\n    // Called when a drag finishes, so the owner can persist the new sizing\n    public Action OnResized;\n\n    private bool _isDragging;\n    private bool _isHovered;\n    private float _dragStartScreenX;\n    private float _leftStartWidth;\n    private float _rightStartWidth;\n\n    public PanelSplitter(Widget parent, Widget left, Widget right) : base(parent)\n    {\n        _left = left;\n        _right = right;\n\n        FixedWidth = Thickness;\n        Cursor = CursorShape.SizeH;\n        SetSizeMode(SizeMode.Default, SizeMode.CanGrow);\n    }\n\n    protected override void OnPaint()\n    {\n        var rect = LocalRect;\n\n        var color = _isDragging || _isHovered\n            ? Theme.Primary.WithAlpha(0.6f)\n            : Color.White.WithAlpha(0.08f);\n\n        Paint.SetBrush(color);\n        var line = new Rect(rect.Center.x - 1, rect.Top \u002B 2, 2, rect.Height - 4);\n        Paint.DrawRect(line, 1);\n    }\n\n    protected override void OnMouseEnter()\n    {\n        _isHovered = true;\n        Update();\n    }\n\n    protected override void OnMouseLeave()\n    {\n        _isHovered = false;\n        Update();\n    }\n\n    protected override void OnMousePress(MouseEvent e)\n    {\n        base.OnMousePress(e);\n\n        if (e.LeftMouseButton)\n        {\n            _isDragging = true;\n            _dragStartScreenX = e.ScreenPosition.x;\n            _leftStartWidth = _left.Width;\n            _rightStartWidth = _right.Width;\n            e.Accepted = true;\n        }\n    }\n\n    protected override void OnMouseMove(MouseEvent e)\n    {\n        base.OnMouseMove(e);\n\n        if (!_isDragging)\n            return;\n\n        var delta = e.ScreenPosition.x - _dragStartScreenX;\n\n        // Keep both neighbours above the minimum width\n        var minDelta = MinPanelWidth - _leftStartWidth;\n        var maxDelta = _rightStartWidth - MinPanelWidth;\n        delta = Math.Clamp(delta, minDelta, maxDelta);\n\n        _left.FixedWidth = _leftStartWidth \u002B delta;\n    }\n\n    protected override void OnMouseReleased(MouseEvent e)\n    {\n        base.OnMouseReleased(e);\n\n        if (_isDragging)\n        {\n            _isDragging = false;\n            OnResized?.Invoke();\n        }\n\n        Update();\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/CloudIconGridPanel.cs","FileName":"CloudIconGridPanel.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Panel displaying cloud assets as large icons in a grid layout.\n/// \u003C/summary\u003E\npublic class CloudIconGridPanel : Widget, IBrowserPanel\n{\n    private Widget _toolbar;\n    private Label _titleLabel;\n    private IconButton _closeBtn;\n    private IconButton _moveLeftBtn;\n    private IconButton _moveRightBtn;\n    private ScrollArea _scrollArea;\n    private CloudGridCanvas _gridCanvas;\n\n    public Action OnCloseRequested { get; set; }\n    public Action OnMoveLeftRequested { get; set; }\n    public Action OnMoveRightRequested { get; set; }\n\n    public bool ShowCloseButton\n    {\n        get =\u003E _closeBtn?.Visible ?? false;\n        set\n        {\n            if (_closeBtn != null)\n                _closeBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveLeftButton\n    {\n        get =\u003E _moveLeftBtn?.Visible ?? false;\n        set\n        {\n            if (_moveLeftBtn != null)\n                _moveLeftBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveRightButton\n    {\n        get =\u003E _moveRightBtn?.Visible ?? false;\n        set\n        {\n            if (_moveRightBtn != null)\n                _moveRightBtn.Visible = value;\n        }\n    }\n\n    public CloudIconGridPanel(Widget parent) : base(parent)\n    {\n        SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n        CreateUI();\n    }\n\n    private void CreateUI()\n    {\n        Layout = Layout.Column();\n        Layout.Spacing = 4;\n        Layout.Margin = 4;\n\n        // Toolbar\n        _toolbar = Layout.Add(new Widget(this));\n        _toolbar.Layout = Layout.Row();\n        _toolbar.Layout.Spacing = 4;\n        _toolbar.FixedHeight = 28;\n\n        // Cloud icon\n        var cloudIcon = _toolbar.Layout.Add(new Label(\u0022cloud\u0022, this));\n        cloudIcon.SetStyles(\u0022font-family: Material Icons; font-size: 16px; color: #888;\u0022);\n        cloudIcon.FixedWidth = 20;\n\n        _titleLabel = _toolbar.Layout.Add(new Label(\u0022Cloud Assets Preview\u0022, this));\n        _titleLabel.SetStyles(\u0022color: #888; font-size: 11px;\u0022);\n\n        _toolbar.Layout.AddStretchCell();\n\n        _moveLeftBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_left\u0022));\n        _moveLeftBtn.ToolTip = \u0022Move Panel Left\u0022;\n        _moveLeftBtn.Background = Color.Transparent;\n        _moveLeftBtn.OnClick = () =\u003E OnMoveLeftRequested?.Invoke();\n        _moveLeftBtn.Visible = false;\n\n        _moveRightBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_right\u0022));\n        _moveRightBtn.ToolTip = \u0022Move Panel Right\u0022;\n        _moveRightBtn.Background = Color.Transparent;\n        _moveRightBtn.OnClick = () =\u003E OnMoveRightRequested?.Invoke();\n        _moveRightBtn.Visible = false;\n\n        _closeBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _closeBtn.ToolTip = \u0022Close Panel\u0022;\n        _closeBtn.Background = Color.Transparent;\n        _closeBtn.OnClick = () =\u003E OnCloseRequested?.Invoke();\n        _closeBtn.Visible = false;\n\n        // Scroll area with custom canvas\n        _scrollArea = Layout.Add(new ScrollArea(this));\n        _scrollArea.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n\n        _gridCanvas = new CloudGridCanvas(_scrollArea);\n        _scrollArea.Canvas = _gridCanvas;\n    }\n\n    /// \u003Csummary\u003E\n    /// Show cloud packages in the grid\n    /// \u003C/summary\u003E\n    public void ShowPackages(List\u003CPackage\u003E packages)\n    {\n        _gridCanvas.LoadPackages(packages);\n        _titleLabel.Text = $\u0022Cloud Assets ({packages.Count})\u0022;\n    }\n\n    /// \u003Csummary\u003E\n    /// Clear the grid\n    /// \u003C/summary\u003E\n    public void Clear()\n    {\n        _gridCanvas.Clear();\n        _titleLabel.Text = \u0022Cloud Assets Preview\u0022;\n    }\n}\n\n/// \u003Csummary\u003E\n/// Canvas that draws cloud package icons\n/// \u003C/summary\u003E\ninternal class CloudGridCanvas : Widget\n{\n    private List\u003CCloudGridItem\u003E _items = new();\n    private int _hoveredIndex = -1;\n    private int _selectedIndex = -1;\n\n    private const float ItemWidth = 100;\n    private const float ItemHeight = 120;\n    private const float IconSize = 64;\n    private const float Spacing = 8;\n    private const float Padding = 8;\n\n    public CloudGridCanvas(Widget parent) : base(parent)\n    {\n        MinimumHeight = 100;\n    }\n\n    public void Clear()\n    {\n        _items.Clear();\n        _hoveredIndex = -1;\n        _selectedIndex = -1;\n        MinimumHeight = 100;\n        Update();\n    }\n\n    public void LoadPackages(List\u003CPackage\u003E packages)\n    {\n        _items.Clear();\n        _hoveredIndex = -1;\n        _selectedIndex = -1;\n\n        foreach (var pkg in packages)\n        {\n            _items.Add(new CloudGridItem\n            {\n                Package = pkg,\n                Title = pkg.Title ?? pkg.FullIdent,\n                Author = pkg.Org?.Title ?? \u0022Unknown\u0022,\n                FullIdent = pkg.FullIdent,\n                Thumb = pkg.Thumb\n            });\n        }\n\n        UpdateSize();\n        Update();\n    }\n\n    private void UpdateSize()\n    {\n        if (_items == null || _items.Count == 0)\n        {\n            MinimumHeight = 100;\n            return;\n        }\n\n        float width = 400;\n        try { width = Parent?.Width ?? 400; } catch { }\n        if (width \u003C= 0) width = 400;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n        int rows = (_items.Count \u002B columns - 1) / columns;\n\n        float height = Padding * 2 \u002B rows * ItemHeight \u002B Math.Max(0, rows - 1) * Spacing;\n        MinimumHeight = Math.Max(100, height);\n    }\n\n    protected override void OnPaint()\n    {\n        if (_items == null || _items.Count == 0)\n        {\n            // Draw placeholder\n            Paint.SetPen(Theme.Text.WithAlpha(0.3f));\n            Paint.SetDefaultFont(10, 400);\n            Paint.DrawText(LocalRect, \u0022Select a category in the Cloud Assets tree\u0022, TextFlag.Center);\n            return;\n        }\n\n        float width = Width;\n        if (width \u003C= 0) width = 400;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n\n        for (int i = 0; i \u003C _items.Count; i\u002B\u002B)\n        {\n            int col = i % columns;\n            int row = i / columns;\n\n            float x = Padding \u002B col * (ItemWidth \u002B Spacing);\n            float y = Padding \u002B row * (ItemHeight \u002B Spacing);\n\n            var itemRect = new Rect(x, y, ItemWidth, ItemHeight);\n            DrawItem(i, itemRect);\n        }\n    }\n\n    private void DrawItem(int index, Rect rect)\n    {\n        var item = _items[index];\n\n        // Background\n        if (index == _selectedIndex)\n        {\n            Paint.SetBrush(Theme.Primary.WithAlpha(0.3f));\n            Paint.DrawRect(rect, 4);\n        }\n        else if (index == _hoveredIndex)\n        {\n            Paint.SetBrush(Color.White.WithAlpha(0.05f));\n            Paint.DrawRect(rect, 4);\n        }\n\n        // Icon area\n        var iconRect = new Rect(\n            rect.Left \u002B (rect.Width - IconSize) / 2,\n            rect.Top \u002B 4,\n            IconSize,\n            IconSize\n        );\n\n        // Draw thumbnail if available, otherwise icon based on package type\n        if (!string.IsNullOrEmpty(item.Thumb) \u0026\u0026 item.Thumb.StartsWith(\u0022http\u0022))\n        {\n            Paint.Draw(iconRect, item.Thumb);\n        }\n        else\n        {\n            Paint.SetBrush(Theme.WidgetBackground);\n            Paint.DrawRect(iconRect, 4);\n\n            var icon = GetIconForType(item.Package.TypeName);\n            var iconColor = GetColorForType(item.Package.TypeName);\n            Paint.SetPen(iconColor);\n            Paint.DrawIcon(iconRect, icon, 48, TextFlag.Center);\n        }\n\n        // Title\n        var titleRect = new Rect(rect.Left \u002B 2, iconRect.Bottom \u002B 2, rect.Width - 4, 16);\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont(8, 500);\n\n        var title = item.Title;\n        if (title.Length \u003E 14) title = title.Substring(0, 12) \u002B \u0022..\u0022;\n        Paint.DrawText(titleRect, title, TextFlag.Center);\n\n        // Author\n        var authorRect = new Rect(rect.Left \u002B 2, titleRect.Bottom, rect.Width - 4, 14);\n        Paint.SetPen(Theme.Text.WithAlpha(0.5f));\n        Paint.SetDefaultFont(7, 400);\n\n        var author = item.Author;\n        if (author.Length \u003E 16) author = author.Substring(0, 14) \u002B \u0022..\u0022;\n        Paint.DrawText(authorRect, author, TextFlag.Center);\n    }\n\n    private int GetItemAtPosition(Vector2 pos)\n    {\n        if (_items == null || _items.Count == 0)\n            return -1;\n\n        float width = Width;\n        if (width \u003C= 0) return -1;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n\n        int col = (int)((pos.x - Padding) / (ItemWidth \u002B Spacing));\n        int row = (int)((pos.y - Padding) / (ItemHeight \u002B Spacing));\n\n        if (col \u003C 0 || col \u003E= columns) return -1;\n\n        int index = row * columns \u002B col;\n        if (index \u003C 0 || index \u003E= _items.Count) return -1;\n\n        return index;\n    }\n\n    private Vector2 _dragStartPos;\n    private bool _isDragging;\n    private int _dragItemIndex = -1;\n\n    protected override void OnMouseMove(MouseEvent e)\n    {\n        base.OnMouseMove(e);\n        int newHover = GetItemAtPosition(e.LocalPosition);\n        if (newHover != _hoveredIndex)\n        {\n            _hoveredIndex = newHover;\n            Update();\n        }\n\n        // Handle drag\n        if (e.ButtonState.HasFlag(MouseButtons.Left) \u0026\u0026 !_isDragging \u0026\u0026 _dragItemIndex \u003E= 0)\n        {\n            var delta = e.LocalPosition - _dragStartPos;\n            if (delta.Length \u003E 5)\n            {\n                _isDragging = true;\n                StartDrag(_dragItemIndex);\n            }\n        }\n    }\n\n    protected override void OnMouseLeave()\n    {\n        base.OnMouseLeave();\n        _hoveredIndex = -1;\n        Update();\n    }\n\n    protected override void OnMousePress(MouseEvent e)\n    {\n        base.OnMousePress(e);\n        if (e.LeftMouseButton)\n        {\n            int index = GetItemAtPosition(e.LocalPosition);\n            _dragStartPos = e.LocalPosition;\n            _isDragging = false;\n            _dragItemIndex = index;\n\n            if (index \u003E= 0)\n            {\n                _selectedIndex = index;\n                Update();\n            }\n        }\n    }\n\n    private void StartDrag(int index)\n    {\n        if (index \u003C 0 || index \u003E= _items.Count) return;\n        var item = _items[index];\n\n        var drag = new Drag(this);\n        drag.Data.Text = item.FullIdent;\n\n        // Set thumbnail URL if available\n        if (!string.IsNullOrEmpty(item.Thumb))\n        {\n            drag.Data.Url = new Uri(item.Thumb);\n        }\n\n        drag.Execute();\n    }\n\n    protected override void OnDoubleClick(MouseEvent e)\n    {\n        base.OnDoubleClick(e);\n        if (e.LeftMouseButton)\n        {\n            int index = GetItemAtPosition(e.LocalPosition);\n            if (index \u003E= 0)\n            {\n                var item = _items[index];\n                // Open package page in browser\n                var url = $\u0022https://sbox.game/{item.FullIdent}\u0022;\n                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n                {\n                    FileName = url,\n                    UseShellExecute = true\n                });\n            }\n        }\n    }\n\n    protected override void OnContextMenu(ContextMenuEvent e)\n    {\n        int index = GetItemAtPosition(e.LocalPosition);\n        if (index \u003C 0) return;\n\n        var item = _items[index];\n        var menu = new ContextMenu(this);\n\n        menu.AddOption(\u0022Open in Browser\u0022, \u0022open_in_new\u0022, () =\u003E\n        {\n            var url = $\u0022https://sbox.game/{item.FullIdent}\u0022;\n            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n            {\n                FileName = url,\n                UseShellExecute = true\n            });\n        });\n\n        menu.AddOption(\u0022Copy Identifier\u0022, \u0022content_copy\u0022, () =\u003E\n        {\n            EditorUtility.Clipboard.Copy(item.FullIdent);\n        });\n\n        menu.OpenAtCursor();\n        e.Accepted = true;\n    }\n\n    private static string GetIconForType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E \u0022view_in_ar\u0022,\n            \u0022material\u0022 =\u003E \u0022texture\u0022,\n            \u0022sound\u0022 =\u003E \u0022audiotrack\u0022,\n            \u0022map\u0022 =\u003E \u0022landscape\u0022,\n            _ =\u003E \u0022cloud_download\u0022\n        };\n    }\n\n    private static Color GetColorForType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E new Color(0.9f, 0.6f, 0.3f),\n            \u0022material\u0022 =\u003E new Color(0.9f, 0.4f, 0.6f),\n            \u0022sound\u0022 =\u003E new Color(0.4f, 0.7f, 1.0f),\n            \u0022map\u0022 =\u003E new Color(0.9f, 0.9f, 0.3f),\n            _ =\u003E Theme.Text.WithAlpha(0.7f)\n        };\n    }\n\n    private class CloudGridItem\n    {\n        public Package Package;\n        public string Title;\n        public string Author;\n        public string FullIdent;\n        public string Thumb;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":309726,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\r\nglobal using Microsoft.AspNetCore.Components;\r\nglobal using Microsoft.AspNetCore.Components.Rendering;\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022Tree Assets Browser\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022treeassetsbrowser\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022evilinc\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022evilinc.treeassetsbrowser\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002228\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\r\n\r\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022CompileTime\u0022, \u00222026-07-13T18:00:17.6610244Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.111.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.111.0\u0022)]"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/PackageFolderNode.cs","FileName":"PackageFolderNode.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Tree node representing a cloud package folder (parent project loaded from cloud)\n/// \u003C/summary\u003E\npublic class PackageFolderNode : TreeNode\n{\n    public Package Package { get; }\n    public string DisplayName { get; }\n    public string IconName { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Tracks whether this folder is currently expanded in the tree view.\n    /// Updated during OnPaint.\n    /// \u003C/summary\u003E\n    public bool IsExpanded { get; private set; }\n\n    private List\u003Cstring\u003E _cachedFiles;\n\n    public override bool HasChildren =\u003E GetPackageFiles().Any();\n    public override string Name =\u003E DisplayName;\n    public override bool CanEdit =\u003E false;\n\n    public PackageFolderNode(Package package, string icon = \u0022cloud\u0022) : base()\n    {\n        Package = package;\n        DisplayName = package.Title;\n        IconName = icon;\n        Value = this;\n    }\n\n    private List\u003Cstring\u003E GetPackageFiles()\n    {\n        if (_cachedFiles == null)\n        {\n            try\n            {\n                _cachedFiles = AssetSystem.GetPackageFiles(Package).ToList();\n            }\n            catch\n            {\n                _cachedFiles = new List\u003Cstring\u003E();\n            }\n        }\n        return _cachedFiles;\n    }\n\n    protected override void BuildChildren()\n    {\n        Clear();\n\n        var files = GetPackageFiles();\n        if (!files.Any())\n            return;\n\n        try\n        {\n            // Group files by directory structure\n            var directories = new Dictionary\u003Cstring, List\u003Cstring\u003E\u003E(StringComparer.OrdinalIgnoreCase);\n            var rootFiles = new List\u003Cstring\u003E();\n\n            foreach (var file in files)\n            {\n                var parts = file.Split(\u0027/\u0027, \u0027\\\\\u0027);\n                if (parts.Length \u003E 1)\n                {\n                    var topDir = parts[0];\n                    if (!directories.ContainsKey(topDir))\n                        directories[topDir] = new List\u003Cstring\u003E();\n                    directories[topDir].Add(file);\n                }\n                else\n                {\n                    rootFiles.Add(file);\n                }\n            }\n\n            // Add subdirectories\n            foreach (var dir in directories.OrderBy(d =\u003E d.Key, StringComparer.OrdinalIgnoreCase))\n            {\n                AddItem(new PackageSubFolderNode(Package, dir.Key, dir.Value));\n            }\n\n            // Add root files\n            foreach (var file in rootFiles.OrderBy(f =\u003E f, StringComparer.OrdinalIgnoreCase))\n            {\n                var fullPath = global::Editor.FileSystem.Cloud.GetFullPath(file);\n                if (!string.IsNullOrEmpty(fullPath))\n                {\n                    AddItem(new AssetFileNode(fullPath));\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n            Log.Warning($\u0022Error building package tree: {ex.Message}\u0022);\n        }\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        // Track expanded state for external access\n        IsExpanded = item.IsOpen;\n\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        // Package icon\n        Paint.SetPen(Theme.Blue);\n        Paint.DrawIcon(rect, item.IsOpen ? \u0022folder_open\u0022 : IconName, 16, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 22;\n\n        // Package name\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont();\n        Paint.DrawText(rect, DisplayName, TextFlag.LeftCenter);\n    }\n\n    public override bool OnContextMenu()\n    {\n        var menu = new ContextMenu(null);\n\n        menu.AddOption(\u0022Refresh\u0022, \u0022refresh\u0022, () =\u003E\n        {\n            _cachedFiles = null;\n            Dirty();\n        });\n\n        menu.AddOption(\u0022View on asset.party\u0022, \u0022open_in_new\u0022, () =\u003E\n        {\n            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n            {\n                FileName = $\u0022https://asset.party/{Package.FullIdent}\u0022,\n                UseShellExecute = true\n            });\n        });\n\n        menu.OpenAtCursor();\n        return true;\n    }\n\n    /// \u003Csummary\u003E\n    /// Check if this folder or any of its contents matches the search filter.\n    /// \u003C/summary\u003E\n    public bool MatchesFilter(string filter)\n    {\n        if (string.IsNullOrEmpty(filter))\n            return true;\n\n        // Check package name\n        if (DisplayName.ToLowerInvariant().Contains(filter))\n            return true;\n\n        // Check files\n        foreach (var file in GetPackageFiles())\n        {\n            if (file.ToLowerInvariant().Contains(filter))\n                return true;\n        }\n\n        return false;\n    }\n}\n\n/// \u003Csummary\u003E\n/// Subfolder within a package\n/// \u003C/summary\u003E\npublic class PackageSubFolderNode : TreeNode\n{\n    public Package Package { get; }\n    public string FolderName { get; }\n    public List\u003Cstring\u003E Files { get; }\n\n    /// \u003Csummary\u003E\n    /// Tracks whether this folder is currently expanded in the tree view.\n    /// Updated during OnPaint.\n    /// \u003C/summary\u003E\n    public bool IsExpanded { get; private set; }\n\n    public override bool HasChildren =\u003E Files.Any();\n    public override string Name =\u003E FolderName;\n    public override bool CanEdit =\u003E false;\n\n    public PackageSubFolderNode(Package package, string folderName, List\u003Cstring\u003E files) : base()\n    {\n        Package = package;\n        FolderName = folderName;\n        Files = files;\n        Value = this;\n    }\n\n    protected override void BuildChildren()\n    {\n        Clear();\n\n        // Group by next level directory\n        var subDirs = new Dictionary\u003Cstring, List\u003Cstring\u003E\u003E(StringComparer.OrdinalIgnoreCase);\n        var currentFiles = new List\u003Cstring\u003E();\n\n        foreach (var file in Files)\n        {\n            // Remove the current folder prefix\n            var relativePath = file;\n            if (file.StartsWith(FolderName \u002B \u0022/\u0022, StringComparison.OrdinalIgnoreCase) ||\n                file.StartsWith(FolderName \u002B \u0022\\\\\u0022, StringComparison.OrdinalIgnoreCase))\n            {\n                relativePath = file.Substring(FolderName.Length \u002B 1);\n            }\n\n            var parts = relativePath.Split(\u0027/\u0027, \u0027\\\\\u0027);\n            if (parts.Length \u003E 1)\n            {\n                var subDir = parts[0];\n                if (!subDirs.ContainsKey(subDir))\n                    subDirs[subDir] = new List\u003Cstring\u003E();\n                subDirs[subDir].Add(file);\n            }\n            else\n            {\n                currentFiles.Add(file);\n            }\n        }\n\n        // Add subdirectories\n        foreach (var dir in subDirs.OrderBy(d =\u003E d.Key, StringComparer.OrdinalIgnoreCase))\n        {\n            AddItem(new PackageSubFolderNode(Package, FolderName \u002B \u0022/\u0022 \u002B dir.Key, dir.Value));\n        }\n\n        // Add files\n        foreach (var file in currentFiles.OrderBy(f =\u003E f, StringComparer.OrdinalIgnoreCase))\n        {\n            var fullPath = global::Editor.FileSystem.Cloud.GetFullPath(file);\n            if (!string.IsNullOrEmpty(fullPath))\n            {\n                AddItem(new AssetFileNode(fullPath));\n            }\n        }\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        // Track expanded state for external access\n        IsExpanded = item.IsOpen;\n\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        Paint.SetPen(Theme.Yellow);\n        Paint.DrawIcon(rect, item.IsOpen ? \u0022folder_open\u0022 : \u0022folder\u0022, 16, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 22;\n\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont();\n\n        // Show just the folder name, not full path\n        var displayName = FolderName.Contains(\u0027/\u0027) ? FolderName.Split(\u0027/\u0027).Last() : FolderName;\n        Paint.DrawText(rect, displayName, TextFlag.LeftCenter);\n    }\n\n    public bool MatchesFilter(string filter)\n    {\n        if (string.IsNullOrEmpty(filter))\n            return true;\n\n        if (FolderName.ToLowerInvariant().Contains(filter))\n            return true;\n\n        foreach (var file in Files)\n        {\n            if (file.ToLowerInvariant().Contains(filter))\n                return true;\n        }\n\n        return false;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/WindowsClipboard.cs","FileName":"WindowsClipboard.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace GeneralGame.Editor;\n\n// Reads the file list (CF_HDROP) that Windows Explorer puts on the clipboard when you Copy/Cut files.\n// The engine clipboard only exposes text, so we go straight to the Win32 API.\ninternal static class WindowsClipboard\n{\n    private const uint CF_HDROP = 15;\n\n    [DllImport(\u0022user32.dll\u0022, SetLastError = true)]\n    private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n    [DllImport(\u0022user32.dll\u0022, SetLastError = true)]\n    private static extern bool CloseClipboard();\n\n    [DllImport(\u0022user32.dll\u0022, SetLastError = true)]\n    private static extern IntPtr GetClipboardData(uint uFormat);\n\n    [DllImport(\u0022user32.dll\u0022, SetLastError = true)]\n    private static extern bool IsClipboardFormatAvailable(uint format);\n\n    [DllImport(\u0022shell32.dll\u0022, CharSet = CharSet.Unicode)]\n    private static extern uint DragQueryFile(IntPtr hDrop, uint iFile, IntPtr lpszFile, uint cch);\n\n    [DllImport(\u0022shell32.dll\u0022, CharSet = CharSet.Unicode)]\n    private static extern uint DragQueryFile(IntPtr hDrop, uint iFile, StringBuilder lpszFile, uint cch);\n\n    public static bool HasFiles()\n    {\n        try\n        {\n            return IsClipboardFormatAvailable(CF_HDROP);\n        }\n        catch\n        {\n            return false;\n        }\n    }\n\n    public static List\u003Cstring\u003E GetFiles()\n    {\n        var result = new List\u003Cstring\u003E();\n\n        try\n        {\n            if (!IsClipboardFormatAvailable(CF_HDROP))\n                return result;\n\n            if (!OpenClipboard(IntPtr.Zero))\n                return result;\n\n            try\n            {\n                var hDrop = GetClipboardData(CF_HDROP);\n                if (hDrop == IntPtr.Zero)\n                    return result;\n\n                uint count = DragQueryFile(hDrop, 0xFFFFFFFF, IntPtr.Zero, 0);\n                for (uint i = 0; i \u003C count; i\u002B\u002B)\n                {\n                    uint length = DragQueryFile(hDrop, i, IntPtr.Zero, 0);\n                    var sb = new StringBuilder((int)length \u002B 1);\n                    if (DragQueryFile(hDrop, i, sb, (uint)sb.Capacity) \u003E 0)\n                        result.Add(sb.ToString());\n                }\n            }\n            finally\n            {\n                CloseClipboard();\n            }\n        }\n        catch\n        {\n            // P/Invoke unavailable or clipboard access failed - just paste nothing\n        }\n\n        return result;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/BrowserSettings.cs","FileName":"BrowserSettings.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\n\nnamespace GeneralGame.Editor;\n\n// Global, persisted settings for the asset browser, edited from the toolbar settings button.\npublic static class BrowserSettings\n{\n    private const string ShowTreeIconsKey = \u0022TreeAssetBrowser.Settings.ShowTreeIcons\u0022;\n    private const string BackwardCompatibilityKey = \u0022TreeAssetBrowser.Settings.BackwardCompatibility\u0022;\n\n    // Fired whenever a setting changes so open panels can repaint.\n    public static event Action OnChanged;\n\n    private static bool _loaded;\n    private static bool _showTreeIcons;\n    private static bool _backwardCompatibility;\n\n    public static bool ShowTreeIcons\n    {\n        get { EnsureLoaded(); return _showTreeIcons; }\n        set\n        {\n            EnsureLoaded();\n            if (_showTreeIcons == value) return;\n            _showTreeIcons = value;\n            ProjectCookie.Set(ShowTreeIconsKey, value);\n            OnChanged?.Invoke();\n        }\n    }\n\n    public static bool BackwardCompatibility\n    {\n        get { EnsureLoaded(); return _backwardCompatibility; }\n        set\n        {\n            EnsureLoaded();\n            if (_backwardCompatibility == value) return;\n            _backwardCompatibility = value;\n            ProjectCookie.Set(BackwardCompatibilityKey, value);\n            OnChanged?.Invoke();\n        }\n    }\n\n    private static void EnsureLoaded()\n    {\n        if (_loaded) return;\n        _loaded = true;\n        _showTreeIcons = ProjectCookie.Get(ShowTreeIconsKey, false);\n        _backwardCompatibility = ProjectCookie.Get(BackwardCompatibilityKey, false);\n    }\n}\n\n// Dropdown opened from the browser toolbar settings button.\ninternal class BrowserSettingsPopup : PopupWidget\n{\n    public BrowserSettingsPopup() : base(null)\n    {\n        Layout = Layout.Column();\n        Layout.Margin = 12;\n        Layout.Spacing = 10;\n        MinimumWidth = 260;\n\n        var title = Layout.Add(new Label(\u0022Browser Settings\u0022, this));\n        title.SetStyles(\u0022font-weight: 600; font-size: 13px;\u0022);\n\n        // Show asset thumbnails next to the type icons in the tree view\n        var iconsCheck = Layout.Add(new Checkbox(\u0022Show icons in Tree View\u0022, this));\n        iconsCheck.Value = BrowserSettings.ShowTreeIcons;\n        iconsCheck.StateChanged = (_) =\u003E BrowserSettings.ShowTreeIcons = iconsCheck.Value;\n\n        // When moving a single asset, offer to scan the project and fix references to its old path\n        var backwardCompatCheck = Layout.Add(new Checkbox(\u0022Backward Compatibility\u0022, this));\n        backwardCompatCheck.ToolTip = \u0022When moving a single asset, ask whether to update references to it in scenes, resources and materials.\u0022;\n        backwardCompatCheck.Value = BrowserSettings.BackwardCompatibility;\n        backwardCompatCheck.StateChanged = (_) =\u003E BrowserSettings.BackwardCompatibility = backwardCompatCheck.Value;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/MoveReferencesDialog.cs","FileName":"MoveReferencesDialog.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n// Shown when moving a single asset with Backward Compatibility on. Lists the files that reference the\n// asset\u0027s current path and lets the user either just move it, or move it and rewrite those references.\ninternal class MoveReferencesDialog : Dialog\n{\n    public MoveReferencesDialog(string oldRef, string newRef, List\u003Cstring\u003E affectedFiles, Action onJustMove, Action onMoveAndUpdate) : base(null)\n    {\n        affectedFiles ??= new List\u003Cstring\u003E();\n\n        Window.WindowTitle = \u0022Move Asset\u0022;\n        Window.Size = new Vector2(580, 440);\n        Window.MinimumSize = new Vector2(420, 300);\n\n        Layout = Layout.Column();\n        Layout.Margin = 16;\n        Layout.Spacing = 10;\n\n        var header = Layout.Add(new Label(\u0022Update references to this asset?\u0022, this));\n        header.SetStyles(\u0022font-size: 14px; font-weight: 600;\u0022);\n\n        var pathLabel = Layout.Add(new Label($\u0022{oldRef}\\n\u2192 {newRef}\u0022, this));\n        pathLabel.SetStyles(\u0022color: #aaa; font-size: 11px;\u0022);\n        pathLabel.WordWrap = true;\n\n        if (affectedFiles.Count \u003E 0)\n        {\n            var countLabel = Layout.Add(new Label($\u0022{affectedFiles.Count} file(s) will be changed:\u0022, this));\n            countLabel.SetStyles(\u0022font-size: 12px;\u0022);\n\n            // Scrollable list of affected files (project-relative for readability)\n            var scroll = Layout.Add(new ScrollArea(this));\n            scroll.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n\n            var list = new Widget(scroll);\n            list.Layout = Layout.Column();\n            list.Layout.Margin = 4;\n            list.Layout.Spacing = 2;\n\n            var projectRoot = Project.Current?.GetRootPath() ?? \u0022\u0022;\n            foreach (var file in affectedFiles)\n            {\n                var display = string.IsNullOrEmpty(projectRoot)\n                    ? file\n                    : Path.GetRelativePath(projectRoot, file).Replace(\u0027\\\\\u0027, \u0027/\u0027);\n\n                var row = list.Layout.Add(new Label(display, list));\n                row.SetStyles(\u0022font-size: 11px; color: #ddd;\u0022);\n            }\n\n            list.Layout.AddStretchCell();\n            scroll.Canvas = list;\n        }\n        else\n        {\n            var none = Layout.Add(new Label(\u0022No other files reference this asset.\u0022, this));\n            none.SetStyles(\u0022color: #aaa; font-size: 12px;\u0022);\n            Layout.AddStretchCell();\n        }\n\n        // Buttons\n        var buttonRow = Layout.AddRow();\n        buttonRow.Spacing = 8;\n        buttonRow.AddStretchCell();\n\n        var cancelBtn = buttonRow.Add(new Button(\u0022Cancel\u0022, this));\n        cancelBtn.MinimumWidth = 80;\n        cancelBtn.Clicked = Close;\n\n        if (affectedFiles.Count \u003E 0)\n        {\n            var moveBtn = buttonRow.Add(new Button(\u0022Just Move\u0022, this));\n            moveBtn.MinimumWidth = 90;\n            moveBtn.Clicked = () =\u003E\n            {\n                onJustMove?.Invoke();\n                Close();\n            };\n\n            var updateBtn = buttonRow.Add(new Button.Primary($\u0022Move \u0026 Update ({affectedFiles.Count})\u0022, this));\n            updateBtn.MinimumWidth = 140;\n            updateBtn.Clicked = () =\u003E\n            {\n                onMoveAndUpdate?.Invoke();\n                Close();\n            };\n        }\n        else\n        {\n            var moveBtn = buttonRow.Add(new Button.Primary(\u0022Move\u0022, this));\n            moveBtn.MinimumWidth = 90;\n            moveBtn.Clicked = () =\u003E\n            {\n                onJustMove?.Invoke();\n                Close();\n            };\n        }\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/TreeAssetBrowser.cs","FileName":"TreeAssetBrowser.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Custom Asset Browser displayed as a tree view of files and folders.\n/// Supports multiple side-by-side panels for comparing/browsing different locations.\n/// Supports different panel types: Tree View and Icon Grid.\n/// Automatically switches to tab mode when window is narrow.\n/// \u003C/summary\u003E\n[Dock(\u0022Editor\u0022, \u0022Tree Asset Browser\u0022, \u0022account_tree\u0022)]\npublic class TreeAssetBrowser : Widget\n{\n    private List\u003CWidget\u003E _panels = new();\n    private List\u003CPanelSplitter\u003E _splitters = new();\n    private Widget _panelsContainer;\n    private Widget _mainToolbar;\n    private Widget _tabsContainer;\n    private Label _titleLabel;\n    private IconButton _toggleModeBtn;\n    private int _activeTabIndex = 0;\n    private bool _isTabMode = false;\n\n    // Unique instance ID for this browser window (assigned from saved state or generated)\n    private string _instanceId;\n    private static int _nextInstanceId = 0;\n    private static HashSet\u003Cstring\u003E _usedInstanceIds = new();\n\n    // Cookie keys\n    private string BrowserStateCookieKey =\u003E $\u0022TreeAssetBrowser.{_instanceId}.State\u0022;\n    private const string AllBrowserIdsCookieKey = \u0022TreeAssetBrowser.AllInstanceIds\u0022;\n\n    // Selected asset callback (forwarded from panels)\n    public Action\u003CAsset\u003E OnAssetSelected;\n    public Action\u003Cstring\u003E OnFileSelected;\n    public Action\u003Cstring\u003E OnFolderSelected;\n\n    public TreeAssetBrowser(Widget parent) : base(parent)\n    {\n        // Try to claim an existing saved instance ID, or generate new one\n        _instanceId = ClaimOrCreateInstanceId();\n        _usedInstanceIds.Add(_instanceId);\n\n        WindowTitle = \u0022Tree Asset Browser\u0022;\n        MinimumSize = new Vector2(250, 200);\n        SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n\n        CreateUI();\n\n        // Try to restore saved state, or create default panel\n        if (!RestoreBrowserState())\n        {\n            AddTreePanel();\n        }\n    }\n\n    public override void OnDestroyed()\n    {\n        // Save before base destroys the child panels, otherwise their widths read as 0\n        SaveBrowserState();\n        base.OnDestroyed();\n        _usedInstanceIds.Remove(_instanceId);\n    }\n\n    /// \u003Csummary\u003E\n    /// Find an available saved instance ID or create a new one\n    /// \u003C/summary\u003E\n    private string ClaimOrCreateInstanceId()\n    {\n        // Get list of saved instance IDs\n        var savedIds = ProjectCookie.Get\u003CList\u003Cstring\u003E\u003E(AllBrowserIdsCookieKey, new List\u003Cstring\u003E());\n\n        // Find first unused saved ID\n        foreach (var id in savedIds)\n        {\n            if (!_usedInstanceIds.Contains(id))\n            {\n                return id;\n            }\n        }\n\n        // Generate new unique ID\n        string newId;\n        do\n        {\n            newId = $\u0022Browser_{_nextInstanceId\u002B\u002B}\u0022;\n        } while (_usedInstanceIds.Contains(newId) || savedIds.Contains(newId));\n\n        return newId;\n    }\n\n    private void CreateUI()\n    {\n        Layout = Layout.Column();\n        Layout.Spacing = 2;\n\n        // Main toolbar with tabs, toggle and add buttons\n        _mainToolbar = Layout.Add(new Widget(this));\n        _mainToolbar.Layout = Layout.Row();\n        _mainToolbar.Layout.Spacing = 4;\n        _mainToolbar.Layout.Margin = 4;\n        _mainToolbar.FixedHeight = 28;\n\n        // Title label (hidden in tab mode)\n        _titleLabel = _mainToolbar.Layout.Add(new Label(\u0022Panels:\u0022, this));\n        _titleLabel.SetStyles(\u0022color: #888; font-size: 11px;\u0022);\n\n        // Tabs container (hidden by default, shown in tab mode)\n        _tabsContainer = _mainToolbar.Layout.Add(new Widget(this));\n        _tabsContainer.Layout = Layout.Row();\n        _tabsContainer.Layout.Spacing = 2;\n        _tabsContainer.SetSizeMode(SizeMode.CanGrow, SizeMode.Default);\n        _tabsContainer.Visible = false;\n\n        _mainToolbar.Layout.AddStretchCell();\n\n        // Toggle tab/side-by-side mode button\n        _toggleModeBtn = _mainToolbar.Layout.Add(new IconButton(\u0022tab\u0022));\n        _toggleModeBtn.ToolTip = \u0022Switch to Tab Mode\u0022;\n        _toggleModeBtn.Background = Color.Transparent;\n        _toggleModeBtn.OnClick = ToggleLayoutMode;\n\n        // Add panel button (with dropdown menu)\n        var addBtn = _mainToolbar.Layout.Add(new IconButton(\u0022add\u0022));\n        addBtn.ToolTip = \u0022Add Browser Panel\u0022;\n        addBtn.Background = Color.Transparent;\n        addBtn.OnClick = ShowAddPanelMenu;\n\n        // Settings button (browser-wide settings dropdown)\n        var settingsBtn = _mainToolbar.Layout.Add(new IconButton(\u0022settings\u0022));\n        settingsBtn.ToolTip = \u0022Browser Settings\u0022;\n        settingsBtn.Background = Color.Transparent;\n        settingsBtn.OnClick = ShowSettingsPopup;\n\n        // Panels container (horizontal layout with splitters)\n        _panelsContainer = Layout.Add(new Widget(this));\n        _panelsContainer.Layout = Layout.Row();\n        _panelsContainer.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n    }\n\n    /// \u003Csummary\u003E\n    /// Save browser state (panels, tab mode, etc.) to cookie\n    /// \u003C/summary\u003E\n    private void SaveBrowserState()\n    {\n        var state = new BrowserState\n        {\n            IsTabMode = _isTabMode,\n            ActiveTabIndex = _activeTabIndex,\n            PanelTypes = _panels.Select(GetPanelTypeName).ToList(),\n            PanelWidths = _panels.Select(p =\u003E p.Width).ToList()\n        };\n\n        ProjectCookie.Set(BrowserStateCookieKey, state);\n\n        // Update global list of instance IDs\n        var savedIds = ProjectCookie.Get\u003CList\u003Cstring\u003E\u003E(AllBrowserIdsCookieKey, new List\u003Cstring\u003E());\n        if (!savedIds.Contains(_instanceId))\n        {\n            savedIds.Add(_instanceId);\n            ProjectCookie.Set(AllBrowserIdsCookieKey, savedIds);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Restore browser state from cookie\n    /// \u003C/summary\u003E\n    private bool RestoreBrowserState()\n    {\n        var state = ProjectCookie.Get\u003CBrowserState\u003E(BrowserStateCookieKey, null);\n        if (state == null || state.PanelTypes == null || state.PanelTypes.Count == 0)\n            return false;\n\n        // Recreate panels\n        foreach (var panelType in state.PanelTypes)\n        {\n            switch (panelType)\n            {\n                case \u0022Tree\u0022:\n                    AddTreePanel(saveState: false);\n                    break;\n                case \u0022IconGrid\u0022:\n                    AddIconGridPanel(saveState: false);\n                    break;\n                case \u0022Cloud\u0022:\n                    AddCloudAssetPanel(saveState: false);\n                    break;\n                case \u0022CloudIconGrid\u0022:\n                    AddCloudIconGridPanel(saveState: false);\n                    break;\n            }\n        }\n\n        // Restore tab mode\n        _activeTabIndex = Math.Clamp(state.ActiveTabIndex, 0, Math.Max(0, _panels.Count - 1));\n\n        if (state.IsTabMode \u0026\u0026 _panels.Count \u003E 1)\n        {\n            SwitchToTabMode();\n        }\n        else\n        {\n            // Restore manual splitter sizing (only meaningful in side-by-side mode)\n            RestorePanelWidths(state.PanelWidths);\n        }\n\n        return _panels.Count \u003E 0;\n    }\n\n    /// \u003Csummary\u003E\n    /// Reapply saved panel widths. Every panel except the last is pinned; the last one stays\n    /// flexible and fills the remaining space, mirroring how the splitters set sizes.\n    /// \u003C/summary\u003E\n    private void RestorePanelWidths(List\u003Cfloat\u003E widths)\n    {\n        if (widths == null || widths.Count != _panels.Count)\n            return;\n\n        for (int i = 0; i \u003C _panels.Count - 1; i\u002B\u002B)\n        {\n            if (widths[i] \u003E 0)\n                _panels[i].FixedWidth = widths[i];\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Get type name for saving\n    /// \u003C/summary\u003E\n    private string GetPanelTypeName(Widget panel)\n    {\n        return panel switch\n        {\n            AssetBrowserPanel =\u003E \u0022Tree\u0022,\n            IconGridPanel =\u003E \u0022IconGrid\u0022,\n            CloudAssetPanel =\u003E \u0022Cloud\u0022,\n            CloudIconGridPanel =\u003E \u0022CloudIconGrid\u0022,\n            _ =\u003E \u0022Unknown\u0022\n        };\n    }\n\n    private void ShowSettingsPopup()\n    {\n        var popup = new BrowserSettingsPopup();\n        popup.OpenBelowCursor(8);\n    }\n\n    /// \u003Csummary\u003E\n    /// Show context menu to choose panel type\n    /// \u003C/summary\u003E\n    private void ShowAddPanelMenu()\n    {\n        var menu = new ContextMenu(this);\n\n        menu.AddOption(\u0022Tree View\u0022, \u0022account_tree\u0022, () =\u003E AddTreePanel());\n        menu.AddOption(\u0022Icon Grid\u0022, \u0022grid_view\u0022, () =\u003E AddIconGridPanel());\n        menu.AddSeparator();\n        menu.AddOption(\u0022Cloud Assets\u0022, \u0022cloud\u0022, () =\u003E AddCloudAssetPanel());\n\n        menu.OpenAtCursor();\n    }\n\n    /// \u003Csummary\u003E\n    /// Add a new tree view panel\n    /// \u003C/summary\u003E\n    public void AddTreePanel(bool saveState = true)\n    {\n        // Generate unique panel ID within this browser\n        var panelId = $\u0022{_instanceId}_Panel{_panels.Count}\u0022;\n        var panel = new AssetBrowserPanel(_panelsContainer, panelId);\n        panel.OnCloseRequested = () =\u003E RemovePanel(panel);\n        panel.OnMoveLeftRequested = () =\u003E MovePanelLeft(panel);\n        panel.OnMoveRightRequested = () =\u003E MovePanelRight(panel);\n\n        // Forward callbacks\n        panel.OnAssetSelected = (asset) =\u003E OnAssetSelected?.Invoke(asset);\n        panel.OnFileSelected = (path) =\u003E OnFileSelected?.Invoke(path);\n        panel.OnFolderSelected = (path) =\u003E OnFolderSelected?.Invoke(path);\n\n        // Sync folder selection with all IconGridPanels\n        panel.OnFolderClicked = OnFolderSelectedInTree;\n\n        AddPanelToContainer(panel);\n\n        _activeTabIndex = _panels.Count - 1;\n        UpdatePanelButtons();\n\n        if (_isTabMode)\n        {\n            SelectTab(_activeTabIndex);\n        }\n\n        if (saveState)\n        {\n            SaveBrowserState();\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Add a new icon grid panel\n    /// \u003C/summary\u003E\n    public void AddIconGridPanel(bool saveState = true)\n    {\n        var panel = new IconGridPanel(_panelsContainer);\n        panel.OnCloseRequested = () =\u003E RemovePanel(panel);\n        panel.OnMoveLeftRequested = () =\u003E MovePanelLeft(panel);\n        panel.OnMoveRightRequested = () =\u003E MovePanelRight(panel);\n\n        AddPanelToContainer(panel);\n\n        _activeTabIndex = _panels.Count - 1;\n        UpdatePanelButtons();\n\n        if (_isTabMode)\n        {\n            SelectTab(_activeTabIndex);\n        }\n\n        if (saveState)\n        {\n            SaveBrowserState();\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Add a new cloud asset search panel\n    /// \u003C/summary\u003E\n    public void AddCloudAssetPanel(bool saveState = true)\n    {\n        var panel = new CloudAssetPanel(_panelsContainer);\n        panel.OnCloseRequested = () =\u003E RemovePanel(panel);\n        panel.OnMoveLeftRequested = () =\u003E MovePanelLeft(panel);\n        panel.OnMoveRightRequested = () =\u003E MovePanelRight(panel);\n\n        // Sync cloud asset selection with all CloudIconGridPanels\n        panel.OnCloudAssetsLoaded = OnCloudAssetsLoaded;\n\n        AddPanelToContainer(panel);\n\n        _activeTabIndex = _panels.Count - 1;\n        UpdatePanelButtons();\n\n        if (_isTabMode)\n        {\n            SelectTab(_activeTabIndex);\n        }\n\n        if (saveState)\n        {\n            SaveBrowserState();\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Add a new cloud icon grid panel for previewing cloud assets\n    /// \u003C/summary\u003E\n    public void AddCloudIconGridPanel(bool saveState = true)\n    {\n        var panel = new CloudIconGridPanel(_panelsContainer);\n        panel.OnCloseRequested = () =\u003E RemovePanel(panel);\n        panel.OnMoveLeftRequested = () =\u003E MovePanelLeft(panel);\n        panel.OnMoveRightRequested = () =\u003E MovePanelRight(panel);\n\n        AddPanelToContainer(panel);\n\n        _activeTabIndex = _panels.Count - 1;\n        UpdatePanelButtons();\n\n        if (_isTabMode)\n        {\n            SelectTab(_activeTabIndex);\n        }\n\n        if (saveState)\n        {\n            SaveBrowserState();\n        }\n    }\n\n    private void AddPanelToContainer(Widget panel)\n    {\n        // Insert a draggable splitter between the previous panel and the new one\n        if (_panels.Count \u003E 0)\n        {\n            var left = _panels[_panels.Count - 1];\n            var splitter = new PanelSplitter(_panelsContainer, left, panel);\n            splitter.OnResized = SaveBrowserState;\n            _panelsContainer.Layout.Add(splitter);\n            _splitters.Add(splitter);\n        }\n\n        _panelsContainer.Layout.Add(panel);\n        _panels.Add(panel);\n    }\n\n    private static void ClearFixedWidth(Widget panel)\n    {\n        panel.MinimumWidth = 0;\n        panel.MaximumWidth = 1000000;\n    }\n\n    /// \u003Csummary\u003E\n    /// Called when folder is selected in any tree panel - syncs all IconGridPanels\n    /// \u003C/summary\u003E\n    private void OnFolderSelectedInTree(string folderPath)\n    {\n        foreach (var panel in _panels.OfType\u003CIconGridPanel\u003E())\n        {\n            panel.ShowFolder(folderPath);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Called when cloud assets are loaded in any CloudAssetPanel - syncs all grid panels\n    /// \u003C/summary\u003E\n    private void OnCloudAssetsLoaded(List\u003CPackage\u003E packages)\n    {\n        // Update CloudIconGridPanels\n        foreach (var panel in _panels.OfType\u003CCloudIconGridPanel\u003E())\n        {\n            panel.ShowPackages(packages);\n        }\n\n        // Update regular IconGridPanels\n        foreach (var panel in _panels.OfType\u003CIconGridPanel\u003E())\n        {\n            panel.ShowCloudPackages(packages, \u0022Cloud Assets\u0022);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Remove a panel (minimum 1 panel must remain)\n    /// \u003C/summary\u003E\n    public void RemovePanel(Widget panel)\n    {\n        if (_panels.Count \u003C= 1)\n            return; // Keep at least one panel\n\n        var index = _panels.IndexOf(panel);\n        if (index \u003C 0)\n            return;\n\n        // Remove the panel from list first\n        _panels.RemoveAt(index);\n\n        // Destroy the panel widget\n        panel.Destroy();\n\n        // Rebuild splitters so their neighbour references stay valid\n        RebuildPanelsLayout();\n\n        // A single remaining panel should fill the whole container\n        if (_panels.Count == 1)\n        {\n            ClearFixedWidth(_panels[0]);\n        }\n\n        // Adjust active tab index if needed\n        if (_activeTabIndex \u003E= _panels.Count)\n        {\n            _activeTabIndex = _panels.Count - 1;\n        }\n\n        // Update visibility in tab mode\n        if (_isTabMode)\n        {\n            for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n            {\n                _panels[i].Visible = (i == _activeTabIndex);\n            }\n            foreach (var splitter in _splitters)\n            {\n                splitter.Visible = false;\n            }\n            RebuildTabBar();\n\n            // If only one panel left, switch back to normal mode\n            if (_panels.Count \u003C= 1)\n            {\n                SwitchToNormalMode();\n            }\n        }\n\n        UpdatePanelButtons();\n        SaveBrowserState();\n    }\n\n    /// \u003Csummary\u003E\n    /// Move a panel to the left (swap with previous panel)\n    /// \u003C/summary\u003E\n    public void MovePanelLeft(Widget panel)\n    {\n        var index = _panels.IndexOf(panel);\n        if (index \u003C= 0)\n            return; // Already first or not found\n\n        SwapPanels(index - 1, index);\n    }\n\n    /// \u003Csummary\u003E\n    /// Move a panel to the right (swap with next panel)\n    /// \u003C/summary\u003E\n    public void MovePanelRight(Widget panel)\n    {\n        var index = _panels.IndexOf(panel);\n        if (index \u003C 0 || index \u003E= _panels.Count - 1)\n            return; // Already last or not found\n\n        SwapPanels(index, index \u002B 1);\n    }\n\n    /// \u003Csummary\u003E\n    /// Swap two adjacent panels\n    /// \u003C/summary\u003E\n    private void SwapPanels(int indexA, int indexB)\n    {\n        if (indexA \u003C 0 || indexB \u003E= _panels.Count || indexA \u003E= indexB)\n            return;\n\n        // Swap in the list\n        var temp = _panels[indexA];\n        _panels[indexA] = _panels[indexB];\n        _panels[indexB] = temp;\n\n        // Rebuild the layout\n        RebuildPanelsLayout();\n        UpdatePanelButtons();\n\n        if (_isTabMode)\n        {\n            RebuildTabBar();\n        }\n\n        SaveBrowserState();\n    }\n\n    /// \u003Csummary\u003E\n    /// Rebuild the panels container layout after reordering\n    /// \u003C/summary\u003E\n    private void RebuildPanelsLayout()\n    {\n        // Clear current layout (but don\u0027t destroy widgets)\n        _panelsContainer.Layout.Clear(false);\n\n        // Clear old splitters\n        foreach (var splitter in _splitters)\n        {\n            splitter.Destroy();\n        }\n        _splitters.Clear();\n\n        // Re-add panels with splitters\n        for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n        {\n            if (i \u003E 0)\n            {\n                var splitter = new PanelSplitter(_panelsContainer, _panels[i - 1], _panels[i]);\n                splitter.OnResized = SaveBrowserState;\n                _panelsContainer.Layout.Add(splitter);\n                _splitters.Add(splitter);\n            }\n            _panelsContainer.Layout.Add(_panels[i]);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Update close button and move arrows visibility on all panels\n    /// \u003C/summary\u003E\n    private void UpdatePanelButtons()\n    {\n        bool showClose = _panels.Count \u003E 1;\n\n        for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n        {\n            if (_panels[i] is IBrowserPanel browserPanel)\n            {\n                // In tab mode, hide panel buttons (close is on tab)\n                if (_isTabMode)\n                {\n                    browserPanel.ShowCloseButton = false;\n                    browserPanel.ShowMoveLeftButton = false;\n                    browserPanel.ShowMoveRightButton = false;\n                }\n                else\n                {\n                    browserPanel.ShowCloseButton = showClose;\n                    browserPanel.ShowMoveLeftButton = showClose \u0026\u0026 i \u003E 0;\n                    browserPanel.ShowMoveRightButton = showClose \u0026\u0026 i \u003C _panels.Count - 1;\n                }\n            }\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Navigate to and select a specific file in the first tree panel\n    /// \u003C/summary\u003E\n    public void NavigateToFile(string path)\n    {\n        _panels.OfType\u003CAssetBrowserPanel\u003E().FirstOrDefault()?.NavigateToFile(path);\n    }\n\n    /// \u003Csummary\u003E\n    /// Refresh all tree panels\n    /// \u003C/summary\u003E\n    public void RefreshAll()\n    {\n        foreach (var panel in _panels.OfType\u003CAssetBrowserPanel\u003E())\n        {\n            panel.RefreshTree();\n        }\n    }\n\n    [EditorEvent.Frame]\n    public void OnFrame()\n    {\n        // Update toggle button visibility (only show when multiple panels)\n        if (_toggleModeBtn != null)\n        {\n            _toggleModeBtn.Visible = _panels.Count \u003E 1;\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Toggle between tab mode and side-by-side mode\n    /// \u003C/summary\u003E\n    private void ToggleLayoutMode()\n    {\n        if (_panels.Count \u003C= 1)\n            return;\n\n        if (_isTabMode)\n        {\n            SwitchToNormalMode();\n        }\n        else\n        {\n            SwitchToTabMode();\n        }\n\n        SaveBrowserState();\n    }\n\n    /// \u003Csummary\u003E\n    /// Switch to tab mode - show tabs and only one panel at a time\n    /// \u003C/summary\u003E\n    private void SwitchToTabMode()\n    {\n        _isTabMode = true;\n        _titleLabel.Visible = false;\n        _tabsContainer.Visible = true;\n\n        // Update toggle button\n        if (_toggleModeBtn != null)\n        {\n            _toggleModeBtn.Icon = \u0022view_column\u0022;\n            _toggleModeBtn.ToolTip = \u0022Switch to Side-by-Side Mode\u0022;\n        }\n\n        // Hide splitters\n        foreach (var splitter in _splitters)\n        {\n            splitter.Visible = false;\n        }\n\n        // Show only active panel; clear any drag-set widths so it fills the area\n        for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n        {\n            ClearFixedWidth(_panels[i]);\n            _panels[i].Visible = (i == _activeTabIndex);\n        }\n\n        RebuildTabBar();\n        UpdatePanelButtons();\n    }\n\n    /// \u003Csummary\u003E\n    /// Switch to normal side-by-side mode\n    /// \u003C/summary\u003E\n    private void SwitchToNormalMode()\n    {\n        _isTabMode = false;\n        _titleLabel.Visible = true;\n        _tabsContainer.Visible = false;\n\n        // Update toggle button\n        if (_toggleModeBtn != null)\n        {\n            _toggleModeBtn.Icon = \u0022tab\u0022;\n            _toggleModeBtn.ToolTip = \u0022Switch to Tab Mode\u0022;\n        }\n\n        // Show splitters\n        foreach (var splitter in _splitters)\n        {\n            splitter.Visible = true;\n        }\n\n        // Show all panels\n        foreach (var panel in _panels)\n        {\n            panel.Visible = true;\n        }\n\n        UpdatePanelButtons();\n    }\n\n    /// \u003Csummary\u003E\n    /// Rebuild the tab bar with current panels\n    /// \u003C/summary\u003E\n    private void RebuildTabBar()\n    {\n        _tabsContainer.Layout.Clear(true);\n\n        for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n        {\n            var index = i;\n            var panel = _panels[i];\n            var tabName = GetPanelTabName(panel);\n            var tabIcon = GetPanelTabIcon(panel);\n\n            var tab = new TabButton(_tabsContainer, tabIcon, tabName, index == _activeTabIndex);\n            tab.OnClick = () =\u003E SelectTab(index);\n            tab.OnCloseClick = () =\u003E RemovePanel(panel);\n            tab.ShowClose = _panels.Count \u003E 1;\n\n            _tabsContainer.Layout.Add(tab);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Get display name for panel tab\n    /// \u003C/summary\u003E\n    private string GetPanelTabName(Widget panel)\n    {\n        return panel switch\n        {\n            AssetBrowserPanel =\u003E \u0022Tree\u0022,\n            IconGridPanel =\u003E \u0022Grid\u0022,\n            CloudAssetPanel =\u003E \u0022Cloud\u0022,\n            CloudIconGridPanel =\u003E \u0022Cloud Grid\u0022,\n            _ =\u003E \u0022Panel\u0022\n        };\n    }\n\n    /// \u003Csummary\u003E\n    /// Get icon for panel tab\n    /// \u003C/summary\u003E\n    private string GetPanelTabIcon(Widget panel)\n    {\n        return panel switch\n        {\n            AssetBrowserPanel =\u003E \u0022account_tree\u0022,\n            IconGridPanel =\u003E \u0022grid_view\u0022,\n            CloudAssetPanel =\u003E \u0022cloud\u0022,\n            CloudIconGridPanel =\u003E \u0022cloud\u0022,\n            _ =\u003E \u0022tab\u0022\n        };\n    }\n\n    /// \u003Csummary\u003E\n    /// Select a tab by index\n    /// \u003C/summary\u003E\n    private void SelectTab(int index)\n    {\n        if (index \u003C 0 || index \u003E= _panels.Count)\n            return;\n\n        _activeTabIndex = index;\n\n        // Show only selected panel\n        for (int i = 0; i \u003C _panels.Count; i\u002B\u002B)\n        {\n            _panels[i].Visible = (i == _activeTabIndex);\n        }\n\n        RebuildTabBar();\n    }\n}\n\n/// \u003Csummary\u003E\n/// State data for saving/restoring browser configuration\n/// \u003C/summary\u003E\n[Serializable]\ninternal class BrowserState\n{\n    public bool IsTabMode { get; set; }\n    public int ActiveTabIndex { get; set; }\n    public List\u003Cstring\u003E PanelTypes { get; set; } = new();\n\n    // Side-by-side panel widths (one per panel); used to restore manual splitter sizing\n    public List\u003Cfloat\u003E PanelWidths { get; set; } = new();\n}\n\n/// \u003Csummary\u003E\n/// Custom tab button widget for the tab bar\n/// \u003C/summary\u003E\ninternal class TabButton : Widget\n{\n    public Action OnClick;\n    public Action OnCloseClick;\n    public bool ShowClose { get; set; } = true;\n\n    private string _icon;\n    private string _text;\n    private bool _isActive;\n    private bool _isHovered;\n    private bool _isCloseHovered;\n    private Rect _closeRect;\n\n    public TabButton(Widget parent, string icon, string text, bool isActive) : base(parent)\n    {\n        _icon = icon;\n        _text = text;\n        _isActive = isActive;\n        MinimumWidth = 50;\n        MaximumWidth = 150;\n        Cursor = CursorShape.Finger;\n        SetSizeMode(SizeMode.CanGrow, SizeMode.Default);\n    }\n\n    protected override void OnPaint()\n    {\n        var rect = LocalRect;\n\n        // Background\n        if (_isActive)\n        {\n            Paint.SetBrush(Theme.Primary.WithAlpha(0.3f));\n            Paint.SetPen(Theme.Primary);\n        }\n        else if (_isHovered)\n        {\n            Paint.SetBrush(Color.White.WithAlpha(0.05f));\n            Paint.SetPen(Color.White.WithAlpha(0.2f));\n        }\n        else\n        {\n            Paint.SetBrush(Color.White.WithAlpha(0.02f));\n            Paint.SetPen(Color.White.WithAlpha(0.1f));\n        }\n\n        Paint.DrawRect(rect, 4);\n\n        // Icon\n        var iconRect = rect;\n        iconRect.Left \u002B= 6;\n        iconRect.Width = 16;\n        Paint.SetPen(_isActive ? Theme.Primary : Color.White.WithAlpha(0.7f));\n        Paint.DrawIcon(iconRect, _icon, 14, TextFlag.LeftCenter);\n\n        // Text\n        var textRect = rect;\n        textRect.Left \u002B= 24;\n        textRect.Right -= ShowClose ? 22 : 6;\n        Paint.SetPen(_isActive ? Color.White : Color.White.WithAlpha(0.7f));\n        Paint.SetDefaultFont(8, 400);\n        Paint.DrawText(textRect, _text, TextFlag.LeftCenter);\n\n        // Close button\n        if (ShowClose)\n        {\n            _closeRect = rect;\n            _closeRect.Left = rect.Right - 20;\n            _closeRect.Width = 16;\n\n            Paint.SetPen(_isCloseHovered ? Theme.Red : Color.White.WithAlpha(0.5f));\n            Paint.DrawIcon(_closeRect, \u0022close\u0022, 12, TextFlag.Center);\n        }\n    }\n\n    protected override void OnMouseEnter()\n    {\n        _isHovered = true;\n        Update();\n    }\n\n    protected override void OnMouseLeave()\n    {\n        _isHovered = false;\n        _isCloseHovered = false;\n        Update();\n    }\n\n    protected override void OnMouseMove(MouseEvent e)\n    {\n        var wasCloseHovered = _isCloseHovered;\n        _isCloseHovered = ShowClose \u0026\u0026 _closeRect.IsInside(e.LocalPosition);\n\n        if (wasCloseHovered != _isCloseHovered)\n            Update();\n    }\n\n    protected override void OnMousePress(MouseEvent e)\n    {\n        if (e.LeftMouseButton)\n        {\n            if (ShowClose \u0026\u0026 _closeRect.IsInside(e.LocalPosition))\n            {\n                OnCloseClick?.Invoke();\n            }\n            else\n            {\n                OnClick?.Invoke();\n            }\n        }\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/AssetFileNode.cs","FileName":"AssetFileNode.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing Sandbox.Services;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Numerics;\nusing System.Runtime.Intrinsics.X86;\nusing static Sandbox.Connection;\nusing static Sandbox.Internal.IControlSheet;\nusing static System.Runtime.InteropServices.JavaScript.JSType;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Tree node representing a file/asset in the asset browser\n/// \u003C/summary\u003E\npublic class AssetFileNode : TreeNode\n{\n    public string FullPath { get; }\n    public string FileName { get; }\n    public string Extension { get; }\n    public Asset Asset { get; private set; }\n\n    public override bool HasChildren =\u003E false;\n    public override string Name =\u003E Path.GetFileNameWithoutExtension(FileName);\n    public override bool CanEdit =\u003E true;\n\n\n\n\n    private static readonly Dictionary\u003Cstring, string\u003E ExtensionIcons = new()\n    {\n        // Models\n        { \u0022.vmdl\u0022, \u0022view_in_ar\u0022 },\n        { \u0022.fbx\u0022, \u0022view_in_ar\u0022 },\n        { \u0022.obj\u0022, \u0022view_in_ar\u0022 },\n        { \u0022.gltf\u0022, \u0022view_in_ar\u0022 },\n        { \u0022.glb\u0022, \u0022view_in_ar\u0022 },\n        \n        // Textures\n        { \u0022.png\u0022, \u0022image\u0022 },\n        { \u0022.jpg\u0022, \u0022image\u0022 },\n        { \u0022.jpeg\u0022, \u0022image\u0022 },\n        { \u0022.tga\u0022, \u0022image\u0022 },\n        { \u0022.vtex\u0022, \u0022image\u0022 },\n        { \u0022.psd\u0022, \u0022image\u0022 },\n\n        // Materials\n        { \u0022.vmat\u0022, \u0022texture\u0022 },\n\n        // Sounds\n        { \u0022.wav\u0022, \u0022audiotrack\u0022 },\n        { \u0022.mp3\u0022, \u0022audiotrack\u0022 },\n        { \u0022.ogg\u0022, \u0022audiotrack\u0022 },\n        { \u0022.vsnd\u0022, \u0022audiotrack\u0022 },\n\n        // Code\n        { \u0022.cs\u0022, \u0022code\u0022 },\n        { \u0022.razor\u0022, \u0022code\u0022 },\n        { \u0022.scss\u0022, \u0022style\u0022 },\n        { \u0022.css\u0022, \u0022style\u0022 },\n        { \u0022.shader\u0022, \u0022gradient\u0022 },\n        { \u0022.shdrgrph\u0022, \u0022gradient\u0022 },\n\n        // Prefabs \u0026 Scenes\n        { \u0022.prefab\u0022, \u0022inventory_2\u0022 },\n        { \u0022.scene\u0022, \u0022landscape\u0022 },\n\n        // Data\n        { \u0022.json\u0022, \u0022data_object\u0022 },\n        { \u0022.xml\u0022, \u0022data_object\u0022 },\n        { \u0022.txt\u0022, \u0022description\u0022 },\n        { \u0022.md\u0022, \u0022description\u0022 },\n\n        // Resources\n        { \u0022.item\u0022, \u0022category\u0022 },\n        { \u0022.clothing\u0022, \u0022checkroom\u0022 },\n        { \u0022.weapon\u0022, \u0022sports_martial_arts\u0022 },\n\n        // Other\n        { \u0022.particle\u0022, \u0022blur_on\u0022 },\n        { \u0022.vanmgrph\u0022, \u0022animation\u0022 },\n        { \u0022.vpost\u0022, \u0022auto_fix_high\u0022 }\n    };\n\n    private static readonly Dictionary\u003Cstring, Color\u003E ExtensionColors = new()\n    {\n        { \u0022.cs\u0022, new Color(0.4f, 0.7f, 1.0f) },      // Blue for C#\n        { \u0022.razor\u0022, new Color(0.6f, 0.4f, 0.9f) },  // Purple for Razor\n        { \u0022.shader\u0022, new Color(0.3f, 0.9f, 0.5f) }, // Green for shaders\n        { \u0022.vmdl\u0022, new Color(0.9f, 0.6f, 0.3f) },   // Orange for models\n        { \u0022.vmat\u0022, new Color(0.9f, 0.4f, 0.6f) },   // Pink for materials\n        { \u0022.prefab\u0022, new Color(0.3f, 0.8f, 0.9f) }, // Cyan for prefabs\n        { \u0022.scene\u0022, new Color(0.9f, 0.9f, 0.3f) },  // Yellow for scenes\n    };\n\n    public AssetFileNode(string path) : base()\n    {\n        FullPath = Path.GetFullPath(path);\n        FileName = Path.GetFileName(path);\n        Extension = Path.GetExtension(path).ToLowerInvariant();\n        Value = this;\n\n        // Try to find associated asset\n        Asset = AssetSystem.FindByPath(path);\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        // Get icon\n        var icon = GetIcon();\n        var iconColor = GetIconColor();\n\n        // Draw icon\n        Paint.SetPen(iconColor);\n        Paint.DrawIcon(rect, icon, 14, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 20;\n\n        // Optionally draw the asset thumbnail right next to the type icon\n        if (BrowserSettings.ShowTreeIcons)\n        {\n            var thumb = GetThumbnail();\n            if (thumb != null)\n            {\n                const float thumbSize = 16f;\n                var thumbRect = new Rect(rect.Left, rect.Top \u002B (rect.Height - thumbSize) / 2, thumbSize, thumbSize);\n                Paint.Draw(thumbRect, thumb);\n                rect.Left \u002B= thumbSize \u002B 4;\n            }\n        }\n\n        // Draw filename\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont(8, 400);\n\n        var nameWithoutExt = Path.GetFileNameWithoutExtension(FileName);\n        var nameRect = Paint.MeasureText(rect, nameWithoutExt, TextFlag.LeftCenter);\n        Paint.DrawText(rect, nameWithoutExt, TextFlag.LeftCenter);\n\n        // Draw extension in dimmer color\n        rect.Left \u002B= nameRect.Width \u002B 1;\n        Paint.SetPen(Theme.Text.WithAlpha(0.4f));\n        Paint.SetDefaultFont(7, 400);\n        Paint.DrawText(rect, Extension, TextFlag.LeftCenter);\n    }\n\n    private Pixmap _thumbnail;\n    private bool _thumbnailRequested;\n\n    // Lazily fetches the asset thumbnail (only assets have one), cached after the first request.\n    private Pixmap GetThumbnail()\n    {\n        if (!_thumbnailRequested)\n        {\n            _thumbnailRequested = true;\n            if (Asset != null)\n            {\n                try { _thumbnail = Asset.GetAssetThumb(); }\n                catch { _thumbnail = null; }\n            }\n        }\n        return _thumbnail;\n    }\n\n    private string GetIcon()\n    {\n        // Use extension-based icon\n        if (ExtensionIcons.TryGetValue(Extension, out var icon))\n        {\n            return icon;\n        }\n\n        return \u0022description\u0022; // Default file icon\n    }\n\n    private Color GetIconColor()\n    {\n        // Use asset type color if available\n        if (Asset?.AssetType?.Color != null \u0026\u0026 Asset.AssetType.Color != default)\n        {\n            return Asset.AssetType.Color;\n        }\n\n        // Use extension-based color\n        if (ExtensionColors.TryGetValue(Extension, out var color))\n        {\n            return color;\n        }\n\n        return Theme.Text.WithAlpha(0.7f);\n    }\n\n    public override bool OnContextMenu()\n    {\n        var menu = new ContextMenu(null);\n\n        // If several files are selected, show the batch menu (Create Material (N), Delete (N), ...)\n        var selectedFiles = TreeView?.SelectedItems?.OfType\u003CAssetFileNode\u003E().ToList() ?? new List\u003CAssetFileNode\u003E();\n        if (selectedFiles.Count \u003E 1 \u0026\u0026 selectedFiles.Contains(this))\n        {\n            var items = selectedFiles.Select(n =\u003E (n.FullPath, n.Asset)).ToList();\n            AssetContextMenuHelper.BuildMultiFileMenu(menu, items, () =\u003E Parent?.Dirty());\n        }\n        else\n        {\n            AssetContextMenuHelper.BuildFileMenu(\n                menu,\n                FullPath,\n                Asset,\n                onRename: () =\u003E ShowRenameDialog(),\n                onChanged: () =\u003E Parent?.Dirty());\n        }\n\n        menu.OpenAtCursor();\n        return true;\n    }\n\n    private void ShowRenameDialog()\n    {\n        var dialog = new RenameDialog(\u0022Rename File\u0022, Path.GetFileNameWithoutExtension(FileName));\n        dialog.OnConfirm = (newName) =\u003E\n        {\n            if (string.IsNullOrWhiteSpace(newName))\n                return;\n\n            // Preserve extension if not provided\n            if (!Path.HasExtension(newName))\n            {\n                newName \u002B= Extension;\n            }\n\n            if (newName == FileName)\n                return;\n\n            var oldCompiledPath = FullPath \u002B \u0022_c\u0022;\n            var newPath = Path.Combine(Path.GetDirectoryName(FullPath), newName);\n            try\n            {\n                File.Move(FullPath, newPath);\n\n                // Delete old compiled _c file so it doesn\u0027t linger with the old name\n                if (File.Exists(oldCompiledPath))\n                {\n                    File.Delete(oldCompiledPath);\n                }\n\n                Parent?.Dirty();\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to rename file: {ex.Message}\u0022);\n            }\n        };\n        dialog.Show();\n    }\n\n    public override void OnRename(VirtualWidget item, string text, List\u003CTreeNode\u003E selection = null)\n    {\n        if (string.IsNullOrWhiteSpace(text))\n            return;\n\n        // Preserve extension if not provided\n        var newName = text;\n        if (!Path.HasExtension(newName))\n        {\n            newName \u002B= Extension;\n        }\n\n        if (newName == FileName)\n            return;\n\n        var oldCompiledPath = FullPath \u002B \u0022_c\u0022;\n        var newPath = Path.Combine(Path.GetDirectoryName(FullPath), newName);\n\n        try\n        {\n            if (Asset != null)\n            {\n                EditorUtility.MoveAssetToDirectory(Asset, Path.GetDirectoryName(newPath));\n            }\n            else\n            {\n                File.Move(FullPath, newPath);\n            }\n\n            // Delete old compiled _c file so it doesn\u0027t linger with the old name\n            if (File.Exists(oldCompiledPath))\n            {\n                File.Delete(oldCompiledPath);\n            }\n\n            Parent?.Dirty();\n        }\n        catch (Exception ex)\n        {\n            Log.Error($\u0022Failed to rename file: {ex.Message}\u0022);\n        }\n    }\n\n    public override bool OnDragStart()\n    {\n        var drag = new Drag(TreeView);\n\n        if (Asset != null)\n        {\n            drag.Data.Object = Asset;\n        }\n\n        drag.Data.Text = FullPath;\n        drag.Data.Url = new Uri(\u0022file:///\u0022 \u002B FullPath);\n        drag.Execute();\n        return true;\n    }\n\n    public override void OnActivated()\n    {\n        if (Asset != null)\n        {\n            Asset.OpenInEditor();\n        }\n        else\n        {\n            EditorUtility.OpenFolder(FullPath);\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Check if this file matches the search filter\n    /// \u003C/summary\u003E\n    public bool MatchesFilter(string filter)\n    {\n        if (string.IsNullOrEmpty(filter))\n            return true;\n\n        // Check filename\n        if (FileName.ToLowerInvariant().Contains(filter))\n            return true;\n\n        // Check asset type\n        if (Asset?.AssetType?.FriendlyName?.ToLowerInvariant().Contains(filter) == true)\n            return true;\n\n        return false;\n    }\n\n    public override string GetTooltip()\n    {\n        var tip = FullPath;\n\n        if (Asset != null)\n        {\n            tip \u002B= $\u0022\\nType: {Asset.AssetType?.FriendlyName ?? \u0022Unknown\u0022}\u0022;\n        }\n\n        var fileInfo = new FileInfo(FullPath);\n        if (fileInfo.Exists)\n        {\n            tip \u002B= $\u0022\\nSize: {FormatFileSize(fileInfo.Length)}\u0022;\n            tip \u002B= $\u0022\\nModified: {fileInfo.LastWriteTime:g}\u0022;\n        }\n\n        return tip;\n    }\n\n    private static string FormatFileSize(long bytes)\n    {\n        string[] sizes = { \u0022B\u0022, \u0022KB\u0022, \u0022MB\u0022, \u0022GB\u0022 };\n        int order = 0;\n        double size = bytes;\n        while (size \u003E= 1024 \u0026\u0026 order \u003C sizes.Length - 1)\n        {\n            order\u002B\u002B;\n            size /= 1024;\n        }\n        return $\u0022{size:0.##} {sizes[order]}\u0022;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/AssetBrowserPanel.cs","FileName":"AssetBrowserPanel.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Individual asset browser panel with its own toolbar and tree view.\n/// Multiple panels can be displayed side by side in TreeAssetBrowser.\n/// \u003C/summary\u003E\npublic class AssetBrowserPanel : Widget, IBrowserPanel\n{\n    private AssetTreeView _treeView;\n    private LineEdit _searchEdit;\n    private IconButton _searchBtn;\n    private IconButton _clearSearchBtn;\n    private string _searchFilter = \u0022\u0022;\n    private Widget _toolbar;\n    private IconButton _closeBtn;\n    private IconButton _moveLeftBtn;\n    private IconButton _moveRightBtn;\n    private IconButton _expandAllBtn;\n    private IconButton _collapseAllBtn;\n\n    private string _assetsPath;\n    private string _codePath;\n    private string _editorPath;\n\n    // Unique panel ID for this panel instance\n    private string _panelId;\n\n    // Store expanded folder paths to restore state after refresh/search\n    private HashSet\u003Cstring\u003E _expandedPaths = new();\n    private HashSet\u003Cstring\u003E _preSearchExpandedPaths = new();\n    private bool _isSearchActive = false;\n\n    // Cache of paths that match the current search filter (computed once)\n    private HashSet\u003Cstring\u003E _matchingPaths = new();\n\n    // Cookie key for saving expanded state between sessions (unique per panel)\n    private string ExpandedPathsCookieKey =\u003E $\u0022TreeAssetBrowser.{_panelId}.ExpandedPaths\u0022;\n\n    /// \u003Csummary\u003E\n    /// Callback when user requests to close this panel\n    /// \u003C/summary\u003E\n    public Action OnCloseRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Callback when user requests to move this panel left\n    /// \u003C/summary\u003E\n    public Action OnMoveLeftRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Callback when user requests to move this panel right\n    /// \u003C/summary\u003E\n    public Action OnMoveRightRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Selected asset callback\n    /// \u003C/summary\u003E\n    public Action\u003CAsset\u003E OnAssetSelected;\n    public Action\u003Cstring\u003E OnFileSelected;\n    public Action\u003Cstring\u003E OnFolderSelected;\n\n    /// \u003Csummary\u003E\n    /// Called when a folder is clicked (for syncing with IconGridPanel)\n    /// \u003C/summary\u003E\n    public Action\u003Cstring\u003E OnFolderClicked;\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of close button (hide if this is the only panel)\n    /// \u003C/summary\u003E\n    public bool ShowCloseButton\n    {\n        get =\u003E _closeBtn?.Visible ?? false;\n        set\n        {\n            if (_closeBtn != null)\n                _closeBtn.Visible = value;\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of move left button\n    /// \u003C/summary\u003E\n    public bool ShowMoveLeftButton\n    {\n        get =\u003E _moveLeftBtn?.Visible ?? false;\n        set\n        {\n            if (_moveLeftBtn != null)\n                _moveLeftBtn.Visible = value;\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of move right button\n    /// \u003C/summary\u003E\n    public bool ShowMoveRightButton\n    {\n        get =\u003E _moveRightBtn?.Visible ?? false;\n        set\n        {\n            if (_moveRightBtn != null)\n                _moveRightBtn.Visible = value;\n        }\n    }\n\n    public AssetBrowserPanel(Widget parent, string panelId = null) : base(parent)\n    {\n        // Use provided panel ID or generate a default one\n        _panelId = panelId ?? $\u0022Default_{Guid.NewGuid():N}\u0022;\n\n        SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n\n        _assetsPath = Project.Current?.GetAssetsPath();\n        _codePath = Project.Current?.GetCodePath();\n\n        var rootPath = Project.Current?.GetRootPath();\n        if (!string.IsNullOrEmpty(rootPath))\n        {\n            _editorPath = Path.Combine(rootPath, \u0022Editor\u0022);\n        }\n\n        // Load saved expanded state from previous session\n        LoadExpandedState();\n        _lastSavedExpandedPaths = new HashSet\u003Cstring\u003E(_expandedPaths);\n\n        // Subscribe to folder state changes\n        AssetFolderNode.OnExpandedStateChanged \u002B= OnFolderExpandedStateChanged;\n\n        // Repaint the tree when browser settings (e.g. icon visibility) change\n        BrowserSettings.OnChanged \u002B= OnBrowserSettingsChanged;\n\n        CreateUI();\n        RefreshTree();\n    }\n\n    public override void OnDestroyed()\n    {\n        base.OnDestroyed();\n        AssetFolderNode.OnExpandedStateChanged -= OnFolderExpandedStateChanged;\n        BrowserSettings.OnChanged -= OnBrowserSettingsChanged;\n        AssetFolderNode.PathsToAutoExpandByPanel.Remove(this);\n    }\n\n    private void OnBrowserSettingsChanged()\n    {\n        _treeView?.Update();\n    }\n\n    private void OnFolderExpandedStateChanged(object panelKey, string fullPath, bool isExpanded)\n    {\n        // Only handle events from this panel\u0027s tree view\n        if (panelKey != this)\n            return;\n\n        if (isExpanded)\n        {\n            _expandedPaths.Add(fullPath);\n        }\n        else\n        {\n            _expandedPaths.Remove(fullPath);\n\n            // When a folder is collapsed, its children stop being painted,\n            // so their OnPaint never fires to report them as closed.\n            // Remove all descendant paths so they don\u0027t persist as \u0022expanded\u0022.\n            var prefix1 = fullPath \u002B Path.DirectorySeparatorChar;\n            var prefix2 = fullPath \u002B \u0022/\u0022;\n            _expandedPaths.RemoveWhere(p =\u003E\n                p.StartsWith(prefix1, StringComparison.OrdinalIgnoreCase) ||\n                p.StartsWith(prefix2, StringComparison.OrdinalIgnoreCase));\n        }\n    }\n\n    private void CreateUI()\n    {\n        Layout = Layout.Column();\n        Layout.Spacing = 4;\n        Layout.Margin = 4;\n\n        // Toolbar\n        _toolbar = Layout.Add(new Widget(this));\n        _toolbar.Layout = Layout.Row();\n        _toolbar.Layout.Spacing = 4;\n        _toolbar.FixedHeight = 28;\n\n        // Search input\n        _searchEdit = _toolbar.Layout.Add(new LineEdit(this));\n        _searchEdit.PlaceholderText = \u0022Search...\u0022;\n        _searchEdit.TextEdited \u002B= OnSearchTextChanged;\n        _searchEdit.ReturnPressed \u002B= () =\u003E DoSearch();\n\n        // Search button\n        _searchBtn = _toolbar.Layout.Add(new IconButton(\u0022search\u0022));\n        _searchBtn.ToolTip = \u0022Search\u0022;\n        _searchBtn.Background = Color.Transparent;\n        _searchBtn.OnClick = () =\u003E DoSearch();\n\n        // Clear search button\n        _clearSearchBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _clearSearchBtn.ToolTip = \u0022Clear Search\u0022;\n        _clearSearchBtn.Background = Color.Transparent;\n        _clearSearchBtn.OnClick = ClearSearch;\n        _clearSearchBtn.Visible = false;\n\n        // Refresh button\n        var refreshBtn = _toolbar.Layout.Add(new IconButton(\u0022refresh\u0022));\n        refreshBtn.ToolTip = \u0022Refresh\u0022;\n        refreshBtn.Background = Color.Transparent;\n        refreshBtn.OnClick = RefreshTree;\n\n        // Expand all button (only visible during search)\n        _expandAllBtn = _toolbar.Layout.Add(new IconButton(\u0022unfold_more\u0022));\n        _expandAllBtn.ToolTip = \u0022Expand All\u0022;\n        _expandAllBtn.Background = Color.Transparent;\n        _expandAllBtn.OnClick = ExpandAll;\n        _expandAllBtn.Visible = false;\n\n        // Collapse all button (only visible during search)\n        _collapseAllBtn = _toolbar.Layout.Add(new IconButton(\u0022unfold_less\u0022));\n        _collapseAllBtn.ToolTip = \u0022Collapse All\u0022;\n        _collapseAllBtn.Background = Color.Transparent;\n        _collapseAllBtn.OnClick = CollapseAll;\n        _collapseAllBtn.Visible = false;\n\n        // Move left button\n        _moveLeftBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_left\u0022));\n        _moveLeftBtn.ToolTip = \u0022Move Panel Left\u0022;\n        _moveLeftBtn.Background = Color.Transparent;\n        _moveLeftBtn.OnClick = () =\u003E OnMoveLeftRequested?.Invoke();\n        _moveLeftBtn.Visible = false;\n\n        // Move right button\n        _moveRightBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_right\u0022));\n        _moveRightBtn.ToolTip = \u0022Move Panel Right\u0022;\n        _moveRightBtn.Background = Color.Transparent;\n        _moveRightBtn.OnClick = () =\u003E OnMoveRightRequested?.Invoke();\n        _moveRightBtn.Visible = false;\n\n        // Close button\n        _closeBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _closeBtn.ToolTip = \u0022Close Panel\u0022;\n        _closeBtn.Background = Color.Transparent;\n        _closeBtn.OnClick = () =\u003E OnCloseRequested?.Invoke();\n        _closeBtn.Visible = false; // Hidden by default, shown when multiple panels exist\n\n        // Tree view with drag-drop support\n        _treeView = Layout.Add(new AssetTreeView(this));\n        _treeView.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n        _treeView.MultiSelect = true;\n        _treeView.ItemSpacing = 1;\n        _treeView.IndentWidth = 16;\n\n        _treeView.ItemActivated \u002B= OnItemActivated;\n        _treeView.OnSelectionChanged \u002B= OnSelectionChanged;\n    }\n\n    private void OnSearchTextChanged(string text)\n    {\n        // Save expanded state when user starts typing (before any search)\n        if (!string.IsNullOrEmpty(text) \u0026\u0026 !_isSearchActive)\n        {\n            _preSearchExpandedPaths = GetExpandedPaths();\n            _isSearchActive = true;\n        }\n    }\n\n    private void DoSearch()\n    {\n        var text = _searchEdit.Text;\n        _searchFilter = text?.ToLowerInvariant() ?? \u0022\u0022;\n\n        if (string.IsNullOrEmpty(_searchFilter))\n        {\n            ClearSearch();\n            return;\n        }\n\n        // Ensure expanded state is saved (in case search was triggered without typing)\n        if (!_isSearchActive)\n        {\n            _preSearchExpandedPaths = GetExpandedPaths();\n            _isSearchActive = true;\n        }\n\n        _clearSearchBtn.Visible = true;\n        _expandAllBtn.Visible = true;\n        _collapseAllBtn.Visible = true;\n        ApplySearchFilter();\n    }\n\n    private void ApplySearchFilter()\n    {\n        // Pre-compute matching paths by scanning filesystem (done ONCE)\n        _matchingPaths.Clear();\n\n        // Scan Assets folder\n        if (!string.IsNullOrEmpty(_assetsPath) \u0026\u0026 Directory.Exists(_assetsPath))\n        {\n            ScanDirectoryForMatches(_assetsPath, _searchFilter);\n        }\n\n        // Scan Code folder\n        if (!string.IsNullOrEmpty(_codePath) \u0026\u0026 Directory.Exists(_codePath))\n        {\n            ScanDirectoryForMatches(_codePath, _searchFilter);\n        }\n\n        // Scan Editor folder\n        if (!string.IsNullOrEmpty(_editorPath) \u0026\u0026 Directory.Exists(_editorPath))\n        {\n            ScanDirectoryForMatches(_editorPath, _searchFilter);\n        }\n\n        // Scan Libraries (other projects in the workspace)\n        foreach (var project in EditorUtility.Projects.GetAll())\n        {\n            if (project == Project.Current || project.Config.Ident == \u0022menu\u0022)\n                continue;\n\n            var projectRoot = project.GetRootPath();\n            if (!string.IsNullOrEmpty(projectRoot) \u0026\u0026 Directory.Exists(projectRoot))\n            {\n                ScanDirectoryForMatches(projectRoot, _searchFilter);\n            }\n        }\n\n        // Scan Core folder\n        var corePath = global::Editor.FileSystem.Root.GetFullPath(\u0022/core/\u0022);\n        if (!string.IsNullOrEmpty(corePath) \u0026\u0026 Directory.Exists(corePath))\n        {\n            ScanDirectoryForMatches(corePath, _searchFilter);\n        }\n\n        // Scan Citizen folder\n        var citizenPath = global::Editor.FileSystem.Root.GetFullPath(\u0022/addons/citizen/assets/\u0022);\n        if (!string.IsNullOrEmpty(citizenPath) \u0026\u0026 Directory.Exists(citizenPath))\n        {\n            ScanDirectoryForMatches(citizenPath, _searchFilter);\n        }\n\n        // Set filter to check the pre-computed cache (fast O(1) lookup)\n        _treeView.ShouldDisplayChild = (obj) =\u003E\n        {\n            if (obj is AssetFolderNode folder)\n                return _matchingPaths.Contains(folder.FullPath);\n            if (obj is AssetFileNode file)\n                return _matchingPaths.Contains(file.FullPath);\n            // Headers and other nodes - always show\n            return true;\n        };\n\n        // Clear and rebuild tree\n        _treeView.Clear();\n        BuildTreeItems();\n        _treeView.Update();\n    }\n\n    /// \u003Csummary\u003E\n    /// Scan directory and add all matching file/folder paths to cache.\n    /// Also adds parent folder paths so they remain visible.\n    /// \u003C/summary\u003E\n    private void ScanDirectoryForMatches(string path, string filter, int maxDepth = 15)\n    {\n        if (maxDepth \u003C= 0 || !Directory.Exists(path))\n            return;\n\n        try\n        {\n            bool hasMatchingChild = false;\n\n            // Check files\n            foreach (var file in Directory.EnumerateFiles(path))\n            {\n                var fileName = Path.GetFileName(file);\n\n                // Skip hidden/generated files\n                if (fileName.StartsWith(\u0022.\u0022) ||\n                    fileName.Contains(\u0022.generated\u0022, StringComparison.OrdinalIgnoreCase) ||\n                    fileName.EndsWith(\u0022.meta\u0022, StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                // Skip compiled assets only if source exists\n                if (fileName.EndsWith(\u0022_c\u0022))\n                {\n                    var sourcePath = file[..^2]; // Remove _c\n                    if (File.Exists(sourcePath))\n                        continue;\n                }\n\n                if (fileName.ToLowerInvariant().Contains(filter))\n                {\n                    _matchingPaths.Add(Path.GetFullPath(file));\n                    hasMatchingChild = true;\n                }\n            }\n\n            // Check subdirectories\n            foreach (var dir in Directory.EnumerateDirectories(path))\n            {\n                var dirName = Path.GetFileName(dir);\n\n                // Skip hidden/system folders\n                if (dirName.StartsWith(\u0022.\u0022) || dirName.Equals(\u0022obj\u0022, StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                // Check if folder name matches\n                if (dirName.ToLowerInvariant().Contains(filter))\n                {\n                    _matchingPaths.Add(Path.GetFullPath(dir));\n                    hasMatchingChild = true;\n                }\n\n                // Recursively scan subdirectory\n                int countBefore = _matchingPaths.Count;\n                ScanDirectoryForMatches(dir, filter, maxDepth - 1);\n\n                // If subdirectory had matches, add it to visible paths\n                if (_matchingPaths.Count \u003E countBefore)\n                {\n                    _matchingPaths.Add(Path.GetFullPath(dir));\n                    hasMatchingChild = true;\n                }\n            }\n\n            // If this folder has matching children, make sure it\u0027s visible\n            if (hasMatchingChild)\n            {\n                _matchingPaths.Add(Path.GetFullPath(path));\n            }\n        }\n        catch\n        {\n            // Ignore filesystem errors\n        }\n    }\n\n    private void ClearSearch()\n    {\n        _searchEdit.Text = \u0022\u0022;\n        _searchFilter = \u0022\u0022;\n        _treeView.ShouldDisplayChild = null;\n        _matchingPaths.Clear();\n        _clearSearchBtn.Visible = false;\n        _expandAllBtn.Visible = false;\n        _collapseAllBtn.Visible = false;\n\n        // Restore expanded state from before search\n        if (_isSearchActive)\n        {\n            _isSearchActive = false;\n\n            // Rebuild tree without filter, then restore expanded state\n            _treeView.Clear();\n            BuildTreeItems();\n            RestoreExpandedPaths(_preSearchExpandedPaths);\n        }\n\n        _treeView.Update();\n    }\n\n    private HashSet\u003Cstring\u003E GetExpandedPaths()\n    {\n        // Return copy of current tracked expanded paths\n        return new HashSet\u003Cstring\u003E(_expandedPaths);\n    }\n\n    private void SaveExpandedState()\n    {\n        // Save expanded paths to ProjectCookie for persistence between sessions\n        var pathsList = _expandedPaths.ToList();\n        ProjectCookie.Set(ExpandedPathsCookieKey, pathsList);\n    }\n\n    private void LoadExpandedState()\n    {\n        // Load expanded paths from ProjectCookie\n        var pathsList = ProjectCookie.Get\u003CList\u003Cstring\u003E\u003E(ExpandedPathsCookieKey, new List\u003Cstring\u003E());\n        _expandedPaths = new HashSet\u003Cstring\u003E(pathsList);\n    }\n\n    private void RestoreExpandedPaths(HashSet\u003Cstring\u003E paths)\n    {\n        _expandedPaths = new HashSet\u003Cstring\u003E(paths);\n\n        // Create panel-specific auto-expand set (keyed by this panel instance)\n        if (!AssetFolderNode.PathsToAutoExpandByPanel.ContainsKey(this))\n        {\n            AssetFolderNode.PathsToAutoExpandByPanel[this] = new HashSet\u003Cstring\u003E();\n        }\n        else\n        {\n            AssetFolderNode.PathsToAutoExpandByPanel[this].Clear();\n        }\n\n        RestoreExpandedPathsRecursive(_treeView.Items, paths, 0);\n    }\n\n    private void RestoreExpandedPathsRecursive(IEnumerable\u003Cobject\u003E items, HashSet\u003Cstring\u003E paths, int depth)\n    {\n        foreach (var item in items)\n        {\n            if (item is AssetFolderNode folder)\n            {\n                bool shouldExpand = paths.Contains(folder.FullPath);\n                bool hasChildToExpand = !shouldExpand \u0026\u0026 paths.Any(p =\u003E\n                    p.StartsWith(folder.FullPath \u002B Path.DirectorySeparatorChar) ||\n                    p.StartsWith(folder.FullPath \u002B \u0022/\u0022));\n\n                if (shouldExpand || hasChildToExpand)\n                {\n                    // Add to panel-specific auto-expand set\n                    if (AssetFolderNode.PathsToAutoExpandByPanel.TryGetValue(this, out var panelPaths))\n                    {\n                        panelPaths.Add(folder.FullPath);\n                    }\n                    folder.EnsureChildrenBuilt();\n                    if (folder.Children != null)\n                    {\n                        RestoreExpandedPathsRecursive(folder.Children, paths, depth \u002B 1);\n                    }\n                }\n            }\n            else if (item is PackageFolderNode packageFolder)\n            {\n                var packagePath = $\u0022__package__{packageFolder.Package.FullIdent}\u0022;\n                if (paths.Contains(packagePath))\n                {\n                    _treeView.Open(packageFolder);\n                    if (packageFolder.Children != null)\n                    {\n                        RestoreExpandedPathsRecursive(packageFolder.Children, paths, depth \u002B 1);\n                    }\n                }\n            }\n            else if (item is PackageSubFolderNode packageSubFolder)\n            {\n                var subPath = $\u0022__packagesub__{packageSubFolder.Package.FullIdent}__{packageSubFolder.FolderName}\u0022;\n                if (paths.Contains(subPath))\n                {\n                    _treeView.Open(packageSubFolder);\n                    if (packageSubFolder.Children != null)\n                    {\n                        RestoreExpandedPathsRecursive(packageSubFolder.Children, paths, depth \u002B 1);\n                    }\n                }\n            }\n            else if (item is TreeNode node)\n            {\n                var headerPath = $\u0022__header__{node.Name}\u0022;\n                if (paths.Contains(headerPath))\n                {\n                    _treeView.Open(node);\n                }\n                // Always check children of headers (they contain folders)\n                if (node.Children != null)\n                {\n                    RestoreExpandedPathsRecursive(node.Children, paths, depth \u002B 1);\n                }\n            }\n        }\n    }\n\n    public void RefreshTree()\n    {\n        // Save expanded state before refresh\n        var savedPaths = GetExpandedPaths();\n        bool hadSavedPaths = savedPaths.Count \u003E 0;\n\n        _treeView.Clear();\n        BuildTreeItems(hadSavedPaths);\n\n        // Restore expanded state - folders will auto-expand on first paint\n        if (hadSavedPaths)\n        {\n            RestoreExpandedPaths(savedPaths);\n        }\n\n        _treeView.Update();\n    }\n\n    private void BuildTreeItems(bool skipDefaultOpen = true)\n    {\n        // Add Assets folder\n        if (!string.IsNullOrEmpty(_assetsPath) \u0026\u0026 Directory.Exists(_assetsPath))\n        {\n            var assetsNode = new AssetFolderNode(_assetsPath, \u0022Assets\u0022, \u0022folder_special\u0022);\n            _treeView.AddItem(assetsNode);\n\n            // Default open Assets on first load\n            if (!skipDefaultOpen)\n            {\n                _treeView.Open(assetsNode);\n                _expandedPaths.Add(assetsNode.FullPath);\n            }\n        }\n\n        // Add Code folder\n        if (!string.IsNullOrEmpty(_codePath) \u0026\u0026 Directory.Exists(_codePath))\n        {\n            var codeNode = new AssetFolderNode(_codePath, \u0022Code\u0022, \u0022code\u0022);\n            _treeView.AddItem(codeNode);\n        }\n\n        // Add Editor folder\n        if (!string.IsNullOrEmpty(_editorPath) \u0026\u0026 Directory.Exists(_editorPath))\n        {\n            var editorNode = new AssetFolderNode(_editorPath, \u0022Editor\u0022, \u0022edit\u0022);\n            _treeView.AddItem(editorNode);\n        }\n\n        // Add Libraries section - shows all other projects in the workspace\n        var libraryProjects = EditorUtility.Projects.GetAll()\n            .Where(p =\u003E p != Project.Current \u0026\u0026 p.Config.Ident != \u0022menu\u0022)\n            .OrderBy(p =\u003E p.Config.Title)\n            .ToList();\n\n        {\n            var librariesHeader = new TreeNode.SmallHeader(\u0022class\u0022, \u0022Libraries\u0022);\n            var addedCount = 0;\n\n            foreach (var project in libraryProjects)\n            {\n                var projectRoot = project.GetRootPath();\n                if (!string.IsNullOrEmpty(projectRoot) \u0026\u0026 Directory.Exists(projectRoot))\n                {\n                    var title = !string.IsNullOrEmpty(project.Config.Title) ? project.Config.Title : project.Config.Ident;\n                    var projectNode = new AssetFolderNode(projectRoot, title, \u0022inventory_2\u0022);\n                    librariesHeader.AddItem(projectNode);\n                    addedCount\u002B\u002B;\n                }\n            }\n\n            if (addedCount \u003E 0)\n            {\n                _treeView.AddItem(librariesHeader);\n            }\n        }\n\n        // Add Parent Package if this is an addon with a parent (e.g. sandbox gamemode)\n        var parentPackageIdent = Project.Current?.Config?.GetMetaOrDefault(\u0022ParentPackage\u0022, \u0022\u0022);\n        if (Project.Current?.Config?.Type == \u0022addon\u0022 \u0026\u0026\n            !string.IsNullOrWhiteSpace(parentPackageIdent) \u0026\u0026\n            Package.TryGetCached(parentPackageIdent, out Package parentPackage))\n        {\n            var parentHeader = new TreeNode.SmallHeader(\u0022cloud\u0022, \u0022Parent\u0022);\n            _treeView.AddItem(parentHeader);\n\n            var packageNode = new PackageFolderNode(parentPackage, \u0022supervisor_account\u0022);\n            parentHeader.AddItem(packageNode);\n\n            // Default open on first load\n            if (!skipDefaultOpen)\n            {\n                _treeView.Open(parentHeader);\n                _expandedPaths.Add(\u0022__header__Parent\u0022);\n            }\n        }\n\n        // Add s\u0026box section header with Core engine assets\n        var sboxHeader = new TreeNode.SmallHeader(\u0022dns\u0022, \u0022s\u0026box\u0022);\n        _treeView.AddItem(sboxHeader);\n\n        // Add Core engine assets folder\n        var corePath = global::Editor.FileSystem.Root.GetFullPath(\u0022/core/\u0022);\n        if (!string.IsNullOrEmpty(corePath) \u0026\u0026 Directory.Exists(corePath))\n        {\n            var coreNode = new AssetFolderNode(corePath, \u0022Core\u0022, \u0022folder\u0022);\n            sboxHeader.AddItem(coreNode);\n        }\n\n        // Add Citizen assets folder (optional DLC content)\n        var citizenPath = global::Editor.FileSystem.Root.GetFullPath(\u0022/addons/citizen/assets/\u0022);\n        if (!string.IsNullOrEmpty(citizenPath) \u0026\u0026 Directory.Exists(citizenPath))\n        {\n            var citizenNode = new AssetFolderNode(citizenPath, \u0022Citizen\u0022, \u0022accessibility_new\u0022);\n            sboxHeader.AddItem(citizenNode);\n        }\n\n        // Default open s\u0026box on first load\n        if (!skipDefaultOpen)\n        {\n            _treeView.Open(sboxHeader);\n            _expandedPaths.Add(\u0022__header__s\u0026box\u0022);\n        }\n    }\n\n    private void ExpandAll()\n    {\n        foreach (var item in _treeView.Items)\n        {\n            if (item is TreeNode node)\n                ExpandNodeRecursive(node);\n        }\n        _treeView.Update();\n    }\n\n    private void ExpandNodeRecursive(TreeNode node)\n    {\n        // Handle different node types\n        if (node is AssetFolderNode folder)\n        {\n            folder.EnsureChildrenBuilt();\n            _treeView.Open(folder);\n\n            foreach (var child in folder.Children)\n            {\n                if (child is TreeNode childNode)\n                    ExpandNodeRecursive(childNode);\n            }\n        }\n        else if (node is PackageFolderNode packageFolder)\n        {\n            _treeView.Open(packageFolder);\n\n            if (packageFolder.Children != null)\n            {\n                foreach (var child in packageFolder.Children)\n                {\n                    if (child is TreeNode childNode)\n                        ExpandNodeRecursive(childNode);\n                }\n            }\n        }\n        else if (node is PackageSubFolderNode packageSubFolder)\n        {\n            _treeView.Open(packageSubFolder);\n\n            if (packageSubFolder.Children != null)\n            {\n                foreach (var child in packageSubFolder.Children)\n                {\n                    if (child is TreeNode childNode)\n                        ExpandNodeRecursive(childNode);\n                }\n            }\n        }\n        else if (node.Children != null)\n        {\n            // For headers and other generic nodes with children\n            _treeView.Open(node);\n\n            foreach (var child in node.Children)\n            {\n                if (child is TreeNode childNode)\n                    ExpandNodeRecursive(childNode);\n            }\n        }\n    }\n\n    private void CollapseAll()\n    {\n        foreach (var item in _treeView.Items)\n        {\n            if (item is TreeNode node)\n                CollapseNodeRecursive(node);\n        }\n        _treeView.Update();\n    }\n\n    private void CollapseNodeRecursive(TreeNode node)\n    {\n        // Collapse children first (depth-first)\n        if (node.Children != null)\n        {\n            foreach (var child in node.Children)\n            {\n                if (child is TreeNode childNode)\n                    CollapseNodeRecursive(childNode);\n            }\n        }\n\n        // Then collapse this node\n        _treeView.Close(node);\n    }\n\n    private void OnItemActivated(object item)\n    {\n        if (item is AssetFileNode fileNode)\n        {\n            var asset = AssetSystem.FindByPath(fileNode.FullPath);\n            if (asset != null)\n            {\n                OnAssetSelected?.Invoke(asset);\n                asset.OpenInEditor();\n            }\n            else\n            {\n                OnFileSelected?.Invoke(fileNode.FullPath);\n                EditorUtility.OpenFolder(fileNode.FullPath);\n            }\n        }\n        // Folder and header toggle is handled automatically by TreeView\n        // State tracking is done via OnFrame periodic sync\n    }\n\n    private void OnSelectionChanged(object[] items)\n    {\n        var item = items.FirstOrDefault();\n\n        if (item is AssetFileNode fileNode)\n        {\n            var asset = AssetSystem.FindByPath(fileNode.FullPath);\n            if (asset != null)\n            {\n                EditorUtility.InspectorObject = asset;\n            }\n        }\n        else if (item is AssetFolderNode folderNode)\n        {\n            OnFolderSelected?.Invoke(folderNode.FullPath);\n            OnFolderClicked?.Invoke(folderNode.FullPath);\n        }\n    }\n\n    private HashSet\u003Cstring\u003E _lastSavedExpandedPaths = new();\n    private float _saveTimer = 0;\n\n    [EditorEvent.Frame]\n    public void OnFrame()\n    {\n        // Periodically save if state changed\n        _saveTimer \u002B= Time.Delta;\n        if (_saveTimer \u003E= 2.0f)\n        {\n            _saveTimer = 0;\n\n            if (!_expandedPaths.SetEquals(_lastSavedExpandedPaths))\n            {\n                SaveExpandedState();\n                _lastSavedExpandedPaths = new HashSet\u003Cstring\u003E(_expandedPaths);\n            }\n        }\n    }\n\n\n    /// \u003Csummary\u003E\n    /// Navigate to and select a specific file in the tree\n    /// \u003C/summary\u003E\n    public void NavigateToFile(string path)\n    {\n        var normalizedPath = Path.GetFullPath(path);\n\n        foreach (var rootItem in _treeView.Items)\n        {\n            if (rootItem is AssetFolderNode rootFolder)\n            {\n                var node = rootFolder.FindNode(normalizedPath);\n                if (node != null)\n                {\n                    _treeView.ExpandPathTo(node);\n                    _treeView.SelectItem(node);\n                    _treeView.ScrollTo(node);\n                    break;\n                }\n            }\n        }\n    }\n}\n\n/// \u003Csummary\u003E\n/// Custom TreeView with drag-drop support for asset folders\n/// \u003C/summary\u003E\ninternal class AssetTreeView : TreeView\n{\n    public AssetTreeView(Widget parent) : base(parent)\n    {\n        AcceptDrops = true;\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/AssetCreator.cs","FileName":"AssetCreator.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Helper class for creating assets in the tree browser.\n/// Based on the built-in CreateAsset functionality.\n/// \u003C/summary\u003E\npublic static class AssetCreator\n{\n    public struct Entry\n    {\n        public string Name { get; init; }\n        public string Icon { get; init; }\n        public Pixmap IconImage { get; init; }\n        public string Category { get; init; }\n        public bool Pinned { get; init; }\n        public Action\u003CDirectoryInfo\u003E Action { get; init; }\n        public string Default { get; init; }\n\n        public void Execute(DirectoryInfo folder)\n        {\n            if (Action is not null)\n            {\n                Action(folder);\n                return;\n            }\n\n            if (!string.IsNullOrEmpty(Default))\n            {\n                CreateFromTemplate(Name, Default, folder);\n            }\n        }\n    }\n\n    public static void AddOptions(Menu parent, string folderPath)\n    {\n        var folder = new DirectoryInfo(folderPath);\n        var locationType = GetLocationType(folderPath);\n\n        parent.AddOption(\u0022Folder\u0022, \u0022folder\u0022, () =\u003E\n        {\n            ShowNameDialog(\u0022New Folder\u0022, \u0022New Folder\u0022, (name) =\u003E\n            {\n                var newFolderPath = Path.Combine(folderPath, name);\n                if (Directory.Exists(newFolderPath))\n                {\n                    Log.Warning($\u0022Folder already exists: {newFolderPath}\u0022);\n                    return;\n                }\n                Directory.CreateDirectory(newFolderPath);\n            });\n        });\n\n        parent.AddSeparator();\n\n        var gameResources = EditorTypeLibrary.GetAttributes\u003CAssetTypeAttribute\u003E().Select(\n            x =\u003E new Entry()\n            {\n                Name = x.Name,\n                Category = x.Category,\n                IconImage = AssetType.FromType(x.TargetType)?.Icon64,\n                Action = (DirectoryInfo d) =\u003E CreateGameResource(x, d),\n                Pinned = x.Extension == \u0022sound\u0022 || x.Extension == \u0022prefab\u0022 || x.Extension == \u0022scene\u0022\n            }\n        );\n\n        var entries = new List\u003CEntry\u003E();\n\n        if (locationType == LocationType.Code)\n        {\n            entries.Add(new Entry { Name = \u0022Empty C# File\u0022, Icon = \u0022description\u0022, Default = \u0022default.cs\u0022, Category = \u0022Code\u0022, Pinned = true });\n            entries.Add(new Entry { Name = \u0022Component\u0022, Icon = \u0022sports_esports\u0022, Default = \u0022component.cs\u0022, Category = \u0022Code\u0022, Pinned = true });\n            entries.Add(new Entry { Name = \u0022Panel Component\u0022, Icon = \u0022desktop_windows\u0022, Default = \u0022default.razor\u0022, Category = \u0022Razor\u0022 });\n            entries.Add(new Entry { Name = \u0022Style Sheet\u0022, Icon = \u0022brush\u0022, Default = \u0022default.scss\u0022, Category = \u0022Razor\u0022 });\n        }\n        else if (locationType == LocationType.Assets)\n        {\n            entries.Add(new Entry { Name = \u0022Material\u0022, IconImage = AssetType.FromType(typeof(Material))?.Icon64, Default = \u0022default.vmat\u0022, Category = \u0022Rendering\u0022, Pinned = true });\n            entries.Add(new Entry { Name = \u0022Model\u0022, IconImage = AssetType.FromType(typeof(Model))?.Icon64, Default = \u0022default.vmdl\u0022, Category = \u0022Rendering\u0022, Pinned = true });\n            entries.Add(new Entry { Name = \u0022Map\u0022, Icon = \u0022hardware\u0022, Default = \u0022default.vmap\u0022, Category = \u0022World\u0022 });\n\n            entries.Add(new Entry { Name = \u0022Standard Material Shader\u0022, Icon = \u0022brush\u0022, Default = \u0022material.shader\u0022, Category = \u0022Shader\u0022 });\n            entries.Add(new Entry { Name = \u0022Unlit Shader\u0022, Icon = \u0022brush\u0022, Default = \u0022unlit.shader\u0022, Category = \u0022Shader\u0022 });\n            entries.Add(new Entry { Name = \u0022Compute Shader\u0022, Icon = \u0022brush\u0022, Default = \u0022compute.shader\u0022, Category = \u0022Shader\u0022 });\n            entries.Add(new Entry { Name = \u0022Shader Graph\u0022, Icon = \u0022account_tree\u0022, Default = \u0022default.shdrgrph\u0022, Category = \u0022Shader\u0022 });\n            entries.Add(new Entry { Name = \u0022Shader Graph Function\u0022, Icon = \u0022account_tree\u0022, Default = \u0022subgraph.shdrfunc\u0022, Category = \u0022Shader\u0022 });\n\n            entries.AddRange(gameResources);\n        }\n\n        // Add pinned entries first\n        foreach (var entry in entries.Where(x =\u003E x.Pinned).OrderBy(x =\u003E x.Name))\n        {\n            if (entry.IconImage != null)\n                parent.AddOptionWithImage(entry.Name, entry.IconImage, () =\u003E entry.Execute(folder));\n            else\n                parent.AddOption(entry.Name, entry.Icon, () =\u003E entry.Execute(folder));\n        }\n\n        parent.AddSeparator();\n\n        // Group remaining by category\n        var grouped = entries.OrderBy(x =\u003E x.Name).GroupBy(x =\u003E x.Category).OrderBy(x =\u003E x.Key);\n        foreach (var group in grouped.Where(x =\u003E x.Key is not null))\n        {\n            var menu = parent.FindOrCreateMenu(group.Key);\n\n            foreach (var entry in group)\n            {\n                if (entry.IconImage != null)\n                    menu.AddOptionWithImage(entry.Name, entry.IconImage, () =\u003E entry.Execute(folder));\n                else\n                    menu.AddOption(entry.Name, entry.Icon, () =\u003E entry.Execute(folder));\n            }\n        }\n    }\n\n    private enum LocationType\n    {\n        Unknown,\n        Assets,\n        Code,\n        Localization\n    }\n\n    private static LocationType GetLocationType(string path)\n    {\n        var assetsPath = Project.Current?.GetAssetsPath();\n        var codePath = Project.Current?.GetCodePath();\n\n        if (!string.IsNullOrEmpty(assetsPath) \u0026\u0026 path.StartsWith(assetsPath, StringComparison.OrdinalIgnoreCase))\n            return LocationType.Assets;\n\n        if (!string.IsNullOrEmpty(codePath) \u0026\u0026 path.StartsWith(codePath, StringComparison.OrdinalIgnoreCase))\n            return LocationType.Code;\n\n        return LocationType.Unknown;\n    }\n\n    private static string GetNewFilename(DirectoryInfo folder, string typeName, string extension)\n    {\n        typeName = typeName.ToLower();\n        string destName = $\u0022new {typeName}{extension}\u0022;\n\n        int i = 1;\n        while (File.Exists(Path.Combine(folder.FullName, destName)))\n        {\n            destName = $\u0022new {typeName} {i\u002B\u002B}{extension}\u0022;\n        }\n\n        return destName;\n    }\n\n    private static void CreateFromTemplate(string name, string defaultFile, DirectoryInfo folder)\n    {\n        var extension = Path.GetExtension(defaultFile);\n        var defaultName = $\u0022new {name.ToLower()}\u0022;\n\n        ShowNameDialog($\u0022Create {name}\u0022, defaultName, (chosenName) =\u003E\n        {\n            var sourceFile = global::Editor.FileSystem.Root.GetFullPath($\u0022/templates/{defaultFile}\u0022);\n            if (!File.Exists(sourceFile))\n            {\n                Log.Error($\u0022Can\u0027t create asset! Missing template: {defaultFile}\u0022);\n                return;\n            }\n\n            // Ensure correct extension\n            if (!chosenName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))\n            {\n                chosenName \u002B= extension;\n            }\n\n            string destPath = Path.Combine(folder.FullName, chosenName);\n            if (File.Exists(destPath))\n            {\n                Log.Warning($\u0022File already exists: {destPath}\u0022);\n                return;\n            }\n\n            File.Copy(sourceFile, destPath);\n            AssetSystem.RegisterFile(destPath);\n        });\n    }\n\n    public static void CreateGameResource(AssetTypeAttribute gameResource, DirectoryInfo folder)\n    {\n        int slash = gameResource.Name.LastIndexOf(\u0027/\u0027);\n        string name = slash == -1 ? gameResource.Name : gameResource.Name.Substring(slash \u002B 1, gameResource.Name.Length - slash - 1);\n        var extension = $\u0022.{gameResource.Extension}\u0022;\n        var defaultName = $\u0022new {name.ToLower()}\u0022;\n\n        ShowNameDialog($\u0022Create {name}\u0022, defaultName, (chosenName) =\u003E\n        {\n            // Ensure correct extension\n            if (!chosenName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))\n            {\n                chosenName \u002B= extension;\n            }\n\n            string destPath = Path.Combine(folder.FullName, chosenName);\n            if (File.Exists(destPath))\n            {\n                Log.Warning($\u0022File already exists: {destPath}\u0022);\n                return;\n            }\n\n            AssetSystem.CreateResource(gameResource.Extension, destPath);\n        });\n    }\n\n    /// \u003Csummary\u003E\n    /// Show a dialog asking the user for a name before creating a file/folder.\n    /// \u003C/summary\u003E\n    private static void ShowNameDialog(string title, string defaultName, Action\u003Cstring\u003E onCreate)\n    {\n        var dialog = new RenameDialog(title, defaultName);\n        dialog.OnConfirm = (name) =\u003E\n        {\n            if (string.IsNullOrWhiteSpace(name))\n                return;\n\n            onCreate(name);\n        };\n        dialog.Show();\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/IBrowserPanel.cs","FileName":"IBrowserPanel.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using System;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Common interface for all browser panel types (tree view, icon grid, etc.)\n/// \u003C/summary\u003E\npublic interface IBrowserPanel\n{\n    /// \u003Csummary\u003E\n    /// Callback when user requests to close this panel\n    /// \u003C/summary\u003E\n    Action OnCloseRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Callback when user requests to move this panel left\n    /// \u003C/summary\u003E\n    Action OnMoveLeftRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Callback when user requests to move this panel right\n    /// \u003C/summary\u003E\n    Action OnMoveRightRequested { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of close button (hide if this is the only panel)\n    /// \u003C/summary\u003E\n    bool ShowCloseButton { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of move left button\n    /// \u003C/summary\u003E\n    bool ShowMoveLeftButton { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Controls visibility of move right button\n    /// \u003C/summary\u003E\n    bool ShowMoveRightButton { get; set; }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/IconGridPanel.cs","FileName":"IconGridPanel.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Panel displaying folder contents or cloud assets as large icons in a grid layout.\n/// \u003C/summary\u003E\npublic class IconGridPanel : Widget, IBrowserPanel\n{\n    private Widget _toolbar;\n    private Label _pathLabel;\n    private IconButton _closeBtn;\n    private IconButton _upBtn;\n    private IconButton _moveLeftBtn;\n    private IconButton _moveRightBtn;\n    private ScrollArea _scrollArea;\n    private IconGridCanvas _gridCanvas;\n\n    private string _currentFolder;\n    private bool _isShowingCloud;\n    private FileSystemWatcher _watcher;\n\n    public Action OnCloseRequested { get; set; }\n    public Action OnMoveLeftRequested { get; set; }\n    public Action OnMoveRightRequested { get; set; }\n\n    public bool ShowCloseButton\n    {\n        get =\u003E _closeBtn?.Visible ?? false;\n        set\n        {\n            if (_closeBtn != null)\n                _closeBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveLeftButton\n    {\n        get =\u003E _moveLeftBtn?.Visible ?? false;\n        set\n        {\n            if (_moveLeftBtn != null)\n                _moveLeftBtn.Visible = value;\n        }\n    }\n\n    public bool ShowMoveRightButton\n    {\n        get =\u003E _moveRightBtn?.Visible ?? false;\n        set\n        {\n            if (_moveRightBtn != null)\n                _moveRightBtn.Visible = value;\n        }\n    }\n\n    public IconGridPanel(Widget parent) : base(parent)\n    {\n        SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n        CreateUI();\n        SetupFileWatcher();\n    }\n\n    private void SetupFileWatcher()\n    {\n        _watcher = new FileSystemWatcher();\n        _watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;\n        _watcher.Changed \u002B= OnFileSystemChanged;\n        _watcher.Created \u002B= OnFileSystemChanged;\n        _watcher.Deleted \u002B= OnFileSystemChanged;\n        _watcher.Renamed \u002B= OnFileSystemChanged;\n    }\n\n    private void OnFileSystemChanged(object sender, FileSystemEventArgs e)\n    {\n        // Queue refresh on main thread\n        MainThread.Queue(() =\u003E\n        {\n            if (!string.IsNullOrEmpty(_currentFolder) \u0026\u0026 Directory.Exists(_currentFolder))\n            {\n                _gridCanvas?.LoadFolder(_currentFolder);\n            }\n        });\n    }\n\n    public override void OnDestroyed()\n    {\n        base.OnDestroyed();\n        _watcher?.Dispose();\n    }\n\n    private void CreateUI()\n    {\n        Layout = Layout.Column();\n        Layout.Spacing = 4;\n        Layout.Margin = 4;\n\n        // Toolbar\n        _toolbar = Layout.Add(new Widget(this));\n        _toolbar.Layout = Layout.Row();\n        _toolbar.Layout.Spacing = 4;\n        _toolbar.FixedHeight = 28;\n\n        _upBtn = _toolbar.Layout.Add(new IconButton(\u0022arrow_upward\u0022));\n        _upBtn.ToolTip = \u0022Go to Parent Folder\u0022;\n        _upBtn.Background = Color.Transparent;\n        _upBtn.OnClick = GoUp;\n        _upBtn.Enabled = false;\n\n        _pathLabel = _toolbar.Layout.Add(new Label(\u0022Select a folder...\u0022, this));\n        _pathLabel.SetStyles(\u0022color: #888; font-size: 11px;\u0022);\n\n        _toolbar.Layout.AddStretchCell();\n\n        _moveLeftBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_left\u0022));\n        _moveLeftBtn.ToolTip = \u0022Move Panel Left\u0022;\n        _moveLeftBtn.Background = Color.Transparent;\n        _moveLeftBtn.OnClick = () =\u003E OnMoveLeftRequested?.Invoke();\n        _moveLeftBtn.Visible = false;\n\n        _moveRightBtn = _toolbar.Layout.Add(new IconButton(\u0022chevron_right\u0022));\n        _moveRightBtn.ToolTip = \u0022Move Panel Right\u0022;\n        _moveRightBtn.Background = Color.Transparent;\n        _moveRightBtn.OnClick = () =\u003E OnMoveRightRequested?.Invoke();\n        _moveRightBtn.Visible = false;\n\n        _closeBtn = _toolbar.Layout.Add(new IconButton(\u0022close\u0022));\n        _closeBtn.ToolTip = \u0022Close Panel\u0022;\n        _closeBtn.Background = Color.Transparent;\n        _closeBtn.OnClick = () =\u003E OnCloseRequested?.Invoke();\n        _closeBtn.Visible = false;\n\n        // Scroll area with custom canvas\n        _scrollArea = Layout.Add(new ScrollArea(this));\n        _scrollArea.SetSizeMode(SizeMode.CanGrow, SizeMode.CanGrow);\n\n        _gridCanvas = new IconGridCanvas(_scrollArea);\n        _gridCanvas.OnFolderNavigate = ShowFolder;\n        _scrollArea.Canvas = _gridCanvas;\n    }\n\n    /// \u003Csummary\u003E\n    /// Show local folder contents\n    /// \u003C/summary\u003E\n    public void ShowFolder(string folderPath)\n    {\n        if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))\n            return;\n\n        _currentFolder = Path.GetFullPath(folderPath);\n        _isShowingCloud = false;\n\n        // Update file watcher to monitor this folder\n        try\n        {\n            _watcher.EnableRaisingEvents = false;\n            _watcher.Path = _currentFolder;\n            _watcher.EnableRaisingEvents = true;\n        }\n        catch { /* Ignore watcher errors */ }\n\n        // Update path label\n        var displayPath = _currentFolder;\n        var assetsPath = Project.Current?.GetAssetsPath();\n        var codePath = Project.Current?.GetCodePath();\n        var corePath = global::Editor.FileSystem.Root?.GetFullPath(\u0022/core/\u0022);\n        var citizenPath = global::Editor.FileSystem.Root?.GetFullPath(\u0022/addons/citizen/assets/\u0022);\n\n        if (!string.IsNullOrEmpty(assetsPath) \u0026\u0026 displayPath.StartsWith(assetsPath, StringComparison.OrdinalIgnoreCase))\n            displayPath = \u0022Assets\u0022 \u002B displayPath.Substring(assetsPath.Length);\n        else if (!string.IsNullOrEmpty(codePath) \u0026\u0026 displayPath.StartsWith(codePath, StringComparison.OrdinalIgnoreCase))\n            displayPath = \u0022Code\u0022 \u002B displayPath.Substring(codePath.Length);\n        else if (!string.IsNullOrEmpty(corePath) \u0026\u0026 displayPath.StartsWith(corePath, StringComparison.OrdinalIgnoreCase))\n            displayPath = \u0022Core\u0022 \u002B displayPath.Substring(corePath.Length);\n        else if (!string.IsNullOrEmpty(citizenPath) \u0026\u0026 displayPath.StartsWith(citizenPath, StringComparison.OrdinalIgnoreCase))\n            displayPath = \u0022Citizen\u0022 \u002B displayPath.Substring(citizenPath.Length);\n\n        _pathLabel.Text = displayPath.Replace(\u0022\\\\\u0022, \u0022/\u0022);\n\n        // Enable up button - allow navigation up unless we\u0027re at a root folder\n        var parentDir = Directory.GetParent(_currentFolder);\n        bool isAtRoot = false;\n\n        if (!string.IsNullOrEmpty(assetsPath) \u0026\u0026 _currentFolder.Equals(assetsPath.TrimEnd(\u0027\\\\\u0027, \u0027/\u0027), StringComparison.OrdinalIgnoreCase))\n            isAtRoot = true;\n        else if (!string.IsNullOrEmpty(codePath) \u0026\u0026 _currentFolder.Equals(codePath.TrimEnd(\u0027\\\\\u0027, \u0027/\u0027), StringComparison.OrdinalIgnoreCase))\n            isAtRoot = true;\n        else if (!string.IsNullOrEmpty(corePath) \u0026\u0026 _currentFolder.Equals(corePath.TrimEnd(\u0027\\\\\u0027, \u0027/\u0027), StringComparison.OrdinalIgnoreCase))\n            isAtRoot = true;\n        else if (!string.IsNullOrEmpty(citizenPath) \u0026\u0026 _currentFolder.Equals(citizenPath.TrimEnd(\u0027\\\\\u0027, \u0027/\u0027), StringComparison.OrdinalIgnoreCase))\n            isAtRoot = true;\n\n        _upBtn.Enabled = parentDir != null \u0026\u0026 !isAtRoot;\n\n        _gridCanvas.LoadFolder(_currentFolder);\n    }\n\n    /// \u003Csummary\u003E\n    /// Show cloud packages\n    /// \u003C/summary\u003E\n    public void ShowCloudPackages(List\u003CPackage\u003E packages, string title = \u0022Cloud Assets\u0022)\n    {\n        _currentFolder = null;\n        _isShowingCloud = true;\n        _upBtn.Enabled = false;\n        _pathLabel.Text = $\u0022Cloud: {title} ({packages.Count})\u0022;\n\n        // Disable file watcher for cloud view\n        _watcher.EnableRaisingEvents = false;\n\n        _gridCanvas.LoadCloudPackages(packages);\n    }\n\n    private void GoUp()\n    {\n        if (_isShowingCloud || string.IsNullOrEmpty(_currentFolder)) return;\n        var parentDir = Directory.GetParent(_currentFolder);\n        if (parentDir != null)\n            ShowFolder(parentDir.FullName);\n    }\n}\n\n/// \u003Csummary\u003E\n/// Canvas that draws all icons itself - supports both local files and cloud packages\n/// \u003C/summary\u003E\ninternal class IconGridCanvas : Widget\n{\n    private List\u003CGridItem\u003E _items = new();\n    private int _hoveredIndex = -1;\n    private int _selectedIndex = -1;\n    private HashSet\u003Cint\u003E _selectedIndices = new();\n\n    // Anchor for shift range-selection (like the tree view)\n    private int _selectionAnchor = -1;\n\n    // Item whose asset should open in the inspector on mouse release (set on a plain click, cleared on drag)\n    private int _pendingInspectorIndex = -1;\n\n    public Action\u003Cstring\u003E OnFolderNavigate;\n\n    private const float ItemWidth = 80;\n    private const float ItemHeight = 100;\n    private const float IconSize = 64;\n    private const float Spacing = 8;\n    private const float Padding = 8;\n\n    public IconGridCanvas(Widget parent) : base(parent)\n    {\n        MinimumHeight = 100;\n        AcceptDrops = true;\n    }\n\n    /// \u003Csummary\u003E\n    /// Load local folder contents\n    /// \u003C/summary\u003E\n    public void LoadFolder(string folderPath)\n    {\n        _currentFolder = folderPath;\n        _items.Clear();\n        _hoveredIndex = -1;\n        _selectedIndex = -1;\n        _selectedIndices.Clear();\n\n        try\n        {\n            // Folders\n            foreach (var dir in Directory.GetDirectories(folderPath).OrderBy(d =\u003E Path.GetFileName(d), StringComparer.OrdinalIgnoreCase))\n            {\n                var dirInfo = new DirectoryInfo(dir);\n                if (dirInfo.Attributes.HasFlag(FileAttributes.Hidden)) continue;\n                if (dirInfo.Name.Equals(\u0022obj\u0022, StringComparison.OrdinalIgnoreCase)) continue;\n                if (dirInfo.Name.StartsWith(\u0022.\u0022)) continue;\n\n                _items.Add(new GridItem\n                {\n                    Path = dir,\n                    Name = dirInfo.Name,\n                    IsFolder = true,\n                    IsCloud = false\n                });\n            }\n\n            // Files\n            foreach (var file in Directory.GetFiles(folderPath).OrderBy(f =\u003E Path.GetFileName(f), StringComparer.OrdinalIgnoreCase))\n            {\n                var fileInfo = new FileInfo(file);\n                if (fileInfo.Attributes.HasFlag(FileAttributes.Hidden)) continue;\n                if (fileInfo.Name.Contains(\u0022.generated\u0022, StringComparison.OrdinalIgnoreCase)) continue;\n                if (fileInfo.Name.EndsWith(\u0022.meta\u0022, StringComparison.OrdinalIgnoreCase)) continue;\n                if (fileInfo.Name.StartsWith(\u0022.\u0022)) continue;\n                if (fileInfo.Name.EndsWith(\u0022_c\u0022) \u0026\u0026 File.Exists(file[..^2])) continue;\n\n                var asset = AssetSystem.FindByPath(file);\n                Pixmap thumb = null;\n                try { thumb = asset?.GetAssetThumb(); } catch { }\n\n                _items.Add(new GridItem\n                {\n                    Path = file,\n                    Name = fileInfo.Name,\n                    IsFolder = false,\n                    IsCloud = false,\n                    Asset = asset,\n                    Thumbnail = thumb,\n                    Extension = fileInfo.Extension.ToLowerInvariant()\n                });\n            }\n        }\n        catch (Exception ex)\n        {\n            Log.Warning($\u0022Error loading folder: {ex.Message}\u0022);\n        }\n\n        UpdateSize();\n        Update();\n    }\n\n    /// \u003Csummary\u003E\n    /// Load cloud packages\n    /// \u003C/summary\u003E\n    public void LoadCloudPackages(List\u003CPackage\u003E packages)\n    {\n        _items.Clear();\n        _hoveredIndex = -1;\n        _selectedIndex = -1;\n        _selectedIndices.Clear();\n\n        foreach (var pkg in packages)\n        {\n            _items.Add(new GridItem\n            {\n                Name = pkg.Title ?? pkg.FullIdent,\n                IsFolder = false,\n                IsCloud = true,\n                Package = pkg,\n                Author = pkg.Org?.Title ?? \u0022Unknown\u0022,\n                CloudThumb = pkg.Thumb\n            });\n        }\n\n        UpdateSize();\n        Update();\n    }\n\n    private void UpdateSize()\n    {\n        if (_items == null || _items.Count == 0)\n        {\n            MinimumHeight = 100;\n            return;\n        }\n\n        float width = 400;\n        try { width = Parent?.Width ?? 400; } catch { }\n        if (width \u003C= 0) width = 400;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n        int rows = (_items.Count \u002B columns - 1) / columns;\n\n        float height = Padding * 2 \u002B rows * ItemHeight \u002B Math.Max(0, rows - 1) * Spacing;\n        MinimumHeight = Math.Max(100, height);\n    }\n\n    protected override void OnPaint()\n    {\n        if (_items == null || _items.Count == 0)\n        {\n            Paint.SetPen(Theme.Text.WithAlpha(0.3f));\n            Paint.SetDefaultFont(10, 400);\n            Paint.DrawText(LocalRect, \u0022Select a folder or cloud category\u0022, TextFlag.Center);\n            return;\n        }\n\n        float width = Width;\n        if (width \u003C= 0) width = 400;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n\n        for (int i = 0; i \u003C _items.Count; i\u002B\u002B)\n        {\n            int col = i % columns;\n            int row = i / columns;\n\n            float x = Padding \u002B col * (ItemWidth \u002B Spacing);\n            float y = Padding \u002B row * (ItemHeight \u002B Spacing);\n\n            var itemRect = new Rect(x, y, ItemWidth, ItemHeight);\n            DrawItem(i, itemRect);\n        }\n    }\n\n    private void DrawItem(int index, Rect rect)\n    {\n        var item = _items[index];\n\n        // Background\n        if (_selectedIndices.Contains(index))\n        {\n            Paint.SetBrush(Theme.Primary.WithAlpha(0.3f));\n            Paint.DrawRect(rect, 4);\n        }\n        else if (index == _hoveredIndex)\n        {\n            Paint.SetBrush(Color.White.WithAlpha(0.05f));\n            Paint.DrawRect(rect, 4);\n        }\n\n        // Icon area\n        var iconRect = new Rect(\n            rect.Left \u002B (rect.Width - IconSize) / 2,\n            rect.Top \u002B 4,\n            IconSize,\n            IconSize\n        );\n\n        if (item.IsCloud)\n        {\n            // Cloud item - draw thumbnail if available, otherwise icon\n            if (!string.IsNullOrEmpty(item.CloudThumb) \u0026\u0026 item.CloudThumb.StartsWith(\u0022http\u0022))\n            {\n                Paint.Draw(iconRect, item.CloudThumb);\n            }\n            else\n            {\n                Paint.SetBrush(Theme.WidgetBackground);\n                Paint.DrawRect(iconRect, 4);\n\n                var icon = GetIconForPackageType(item.Package?.TypeName ?? \u0022model\u0022);\n                var color = GetColorForPackageType(item.Package?.TypeName ?? \u0022model\u0022);\n                Paint.SetPen(color);\n                Paint.DrawIcon(iconRect, icon, 48, TextFlag.Center);\n            }\n        }\n        else if (item.Thumbnail != null)\n        {\n            // Local file with thumbnail\n            Paint.Draw(iconRect, item.Thumbnail);\n        }\n        else\n        {\n            // Local file/folder without thumbnail\n            var icon = item.IsFolder ? \u0022folder\u0022 : GetIconForExtension(item.Extension);\n            var color = item.IsFolder ? Theme.Yellow : GetColorForExtension(item.Extension, item.Asset);\n            Paint.SetPen(color);\n            Paint.DrawIcon(iconRect, icon, IconSize, TextFlag.Center);\n        }\n\n        // Name\n        var textRect = new Rect(rect.Left \u002B 2, iconRect.Bottom \u002B 2, rect.Width - 4, 16);\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont(8, 400);\n\n        var name = item.Name;\n        if (name.Length \u003E 12) name = name.Substring(0, 10) \u002B \u0022..\u0022;\n        Paint.DrawText(textRect, name, TextFlag.Center);\n\n        // Author for cloud items\n        if (item.IsCloud \u0026\u0026 !string.IsNullOrEmpty(item.Author))\n        {\n            var authorRect = new Rect(rect.Left \u002B 2, textRect.Bottom, rect.Width - 4, 12);\n            Paint.SetPen(Theme.Text.WithAlpha(0.5f));\n            Paint.SetDefaultFont(7, 400);\n\n            var author = item.Author;\n            if (author.Length \u003E 14) author = author.Substring(0, 12) \u002B \u0022..\u0022;\n            Paint.DrawText(authorRect, author, TextFlag.Center);\n        }\n    }\n\n    private int GetItemAtPosition(Vector2 pos)\n    {\n        if (_items == null || _items.Count == 0)\n            return -1;\n\n        float width = Width;\n        if (width \u003C= 0) return -1;\n\n        int columns = Math.Max(1, (int)((width - Padding * 2 \u002B Spacing) / (ItemWidth \u002B Spacing)));\n\n        int col = (int)((pos.x - Padding) / (ItemWidth \u002B Spacing));\n        int row = (int)((pos.y - Padding) / (ItemHeight \u002B Spacing));\n\n        if (col \u003C 0 || col \u003E= columns) return -1;\n\n        int index = row * columns \u002B col;\n        if (index \u003C 0 || index \u003E= _items.Count) return -1;\n\n        // Check if actually inside item bounds\n        float x = Padding \u002B col * (ItemWidth \u002B Spacing);\n        float y = Padding \u002B row * (ItemHeight \u002B Spacing);\n        var itemRect = new Rect(x, y, ItemWidth, ItemHeight);\n        if (!itemRect.IsInside(pos)) return -1;\n\n        return index;\n    }\n\n    private Vector2 _dragStartPos;\n    private bool _isDragging;\n    private int _dragItemIndex = -1;\n\n    protected override void OnMouseMove(MouseEvent e)\n    {\n        base.OnMouseMove(e);\n        int newHover = GetItemAtPosition(e.LocalPosition);\n        if (newHover != _hoveredIndex)\n        {\n            _hoveredIndex = newHover;\n            Update();\n        }\n\n        // Handle drag\n        if (e.ButtonState.HasFlag(MouseButtons.Left) \u0026\u0026 !_isDragging \u0026\u0026 _dragItemIndex \u003E= 0)\n        {\n            var delta = e.LocalPosition - _dragStartPos;\n            if (delta.Length \u003E 5)\n            {\n                _isDragging = true;\n                _pendingInspectorIndex = -1; // a drag started, so don\u0027t open the inspector on release\n                StartDrag(_dragItemIndex);\n            }\n        }\n    }\n\n    protected override void OnMouseLeave()\n    {\n        base.OnMouseLeave();\n        _hoveredIndex = -1;\n        Update();\n    }\n\n    protected override void OnMousePress(MouseEvent e)\n    {\n        base.OnMousePress(e);\n        if (e.LeftMouseButton)\n        {\n            int index = GetItemAtPosition(e.LocalPosition);\n            _dragStartPos = e.LocalPosition;\n            _isDragging = false;\n            _dragItemIndex = index;\n            _pendingInspectorIndex = -1;\n\n            if (index \u003E= 0)\n            {\n                if (e.HasShift \u0026\u0026 _selectionAnchor \u003E= 0)\n                {\n                    // Shift\u002Bclick: select the contiguous range from the anchor to here\n                    _selectedIndices.Clear();\n                    int from = Math.Min(_selectionAnchor, index);\n                    int to = Math.Max(_selectionAnchor, index);\n                    for (int i = from; i \u003C= to; i\u002B\u002B)\n                        _selectedIndices.Add(i);\n\n                    _selectedIndex = index;\n                }\n                else if (e.HasCtrl)\n                {\n                    // Ctrl\u002Bclick: toggle selection\n                    if (_selectedIndices.Contains(index))\n                        _selectedIndices.Remove(index);\n                    else\n                        _selectedIndices.Add(index);\n\n                    _selectedIndex = index;\n                    _selectionAnchor = index;\n                }\n                else\n                {\n                    // Normal click: single selection\n                    _selectedIndices.Clear();\n                    _selectedIndices.Add(index);\n                    _selectedIndex = index;\n                    _selectionAnchor = index;\n\n                    // Open in inspector only on a real click (deferred to release so a drag doesn\u0027t trigger it)\n                    var item = _items[index];\n                    if (!item.IsCloud \u0026\u0026 !item.IsFolder \u0026\u0026 item.Asset != null)\n                        _pendingInspectorIndex = index;\n                }\n\n                Update();\n            }\n            else\n            {\n                // Click on empty space: clear selection\n                _selectedIndices.Clear();\n                _selectedIndex = -1;\n                _selectionAnchor = -1;\n                Update();\n            }\n        }\n    }\n\n    protected override void OnMouseReleased(MouseEvent e)\n    {\n        base.OnMouseReleased(e);\n\n        if (e.LeftMouseButton \u0026\u0026 !_isDragging \u0026\u0026 _pendingInspectorIndex \u003E= 0 \u0026\u0026 _pendingInspectorIndex \u003C _items.Count)\n        {\n            var item = _items[_pendingInspectorIndex];\n            if (!item.IsCloud \u0026\u0026 !item.IsFolder \u0026\u0026 item.Asset != null)\n                EditorUtility.InspectorObject = item.Asset;\n        }\n\n        _pendingInspectorIndex = -1;\n    }\n\n    private void StartDrag(int index)\n    {\n        if (index \u003C 0 || index \u003E= _items.Count) return;\n        var item = _items[index];\n\n        var drag = new Drag(this);\n\n        if (item.IsCloud)\n        {\n            // Cloud item - set package FullIdent for scene drop\n            drag.Data.Text = item.Package?.FullIdent ?? \u0022\u0022;\n\n            // Set thumbnail URL if available\n            var thumb = item.Package?.Thumb;\n            if (!string.IsNullOrEmpty(thumb))\n            {\n                drag.Data.Url = new Uri(thumb);\n            }\n        }\n        else if (item.IsFolder)\n        {\n            drag.Data.Url = new Uri(\u0022file:///\u0022 \u002B item.Path);\n        }\n        else if (item.Asset != null)\n        {\n            drag.Data.Text = item.Asset.RelativePath;\n            drag.Data.Url = new Uri(\u0022file:///\u0022 \u002B item.Asset.AbsolutePath);\n        }\n        else\n        {\n            drag.Data.Text = item.Path;\n            drag.Data.Url = new Uri(\u0022file:///\u0022 \u002B item.Path);\n        }\n\n        drag.Execute();\n    }\n\n    protected override void OnDoubleClick(MouseEvent e)\n    {\n        base.OnDoubleClick(e);\n        if (e.LeftMouseButton)\n        {\n            int index = GetItemAtPosition(e.LocalPosition);\n            if (index \u003E= 0)\n            {\n                var item = _items[index];\n\n                if (item.IsCloud)\n                {\n                    // Open cloud package in browser\n                    var url = $\u0022https://sbox.game/{item.Package?.FullIdent}\u0022;\n                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n                    {\n                        FileName = url,\n                        UseShellExecute = true\n                    });\n                }\n                else if (item.IsFolder)\n                {\n                    OnFolderNavigate?.Invoke(item.Path);\n                }\n                else if (item.Asset != null)\n                {\n                    item.Asset.OpenInEditor();\n                }\n            }\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Handle drag hover - show appropriate drop cursor\n    /// \u003C/summary\u003E\n    public override void OnDragHover(DragEvent ev)\n    {\n        base.OnDragHover(ev);\n\n        ev.Action = DropAction.Ignore;\n\n        // Only accept drops if we have a current folder to drop into\n        if (string.IsNullOrEmpty(_currentFolder) || !Directory.Exists(_currentFolder))\n            return;\n\n        // Dragging GameObject(s) from the hierarchy: drop creates a prefab here\n        if (ev.Data.Object is GameObject[] gos \u0026\u0026 gos.Length \u003E 0)\n        {\n            ev.Action = DropAction.Copy;\n\n            int folderIdx = GetItemAtPosition(ev.LocalPosition);\n            if (folderIdx \u003E= 0 \u0026\u0026 _items[folderIdx].IsFolder \u0026\u0026 _hoveredIndex != folderIdx)\n            {\n                _hoveredIndex = folderIdx;\n                Update();\n            }\n            return;\n        }\n\n        // Report Copy for external (Explorer) sources, otherwise Windows deletes the originals\n        var effect = DragEffectFor(ev);\n\n        // Check if dragging over a folder item\n        int index = GetItemAtPosition(ev.LocalPosition);\n        if (index \u003E= 0 \u0026\u0026 _items[index].IsFolder)\n        {\n            // Dropping onto a folder\n            ev.Action = effect;\n            if (_hoveredIndex != index)\n            {\n                _hoveredIndex = index;\n                Update();\n            }\n        }\n        else if (ev.Data.HasFileOrFolder)\n        {\n            // Dropping into current folder\n            ev.Action = effect;\n        }\n    }\n\n    // The drop effect to report back to the OS: copying external (Explorer) files prevents Windows\n    // from deleting the originals as part of a \u0022move\u0022.\n    private static DropAction DragEffectFor(DragEvent ev)\n    {\n        if (ev.HasCtrl)\n            return DropAction.Copy;\n\n        foreach (var file in ev.Data.Files)\n        {\n            if (AssetContextMenuHelper.IsExternalSource(file))\n                return DropAction.Copy;\n        }\n\n        return DropAction.Move;\n    }\n\n    /// \u003Csummary\u003E\n    /// Handle dropping files from Windows Explorer or other sources\n    /// \u003C/summary\u003E\n    public override void OnDragDrop(DragEvent ev)\n    {\n        base.OnDragDrop(ev);\n\n        if (string.IsNullOrEmpty(_currentFolder) || !Directory.Exists(_currentFolder))\n            return;\n\n        // Check if dropping onto a folder item\n        int index = GetItemAtPosition(ev.LocalPosition);\n        string targetFolder = _currentFolder;\n\n        if (index \u003E= 0 \u0026\u0026 _items[index].IsFolder)\n        {\n            targetFolder = _items[index].Path;\n        }\n\n        // Dragging GameObject(s) from the hierarchy: create a prefab from them\n        if (ev.Data.Object is GameObject[] gos \u0026\u0026 gos.Length \u003E 0)\n        {\n            ev.Action = DropAction.Copy;\n            AssetContextMenuHelper.CreatePrefabFromGameObjects(gos, targetFolder, () =\u003E LoadFolder(_currentFolder));\n            return;\n        }\n\n        if (!ev.Data.HasFileOrFolder)\n            return;\n\n        // Process the drop. Report Copy for external sources so Windows doesn\u0027t delete the originals.\n        bool isCopy = DragEffectFor(ev) == DropAction.Copy;\n        ev.Action = isCopy ? DropAction.Copy : DropAction.Move;\n\n        // Backward compatibility: moving a single asset opens a modal to update references to its old path\n        var droppedFiles = ev.Data.Files.Where(f =\u003E !string.IsNullOrEmpty(f)).ToList();\n        if (AssetContextMenuHelper.IsBackwardCompatMove(droppedFiles, isCopy))\n        {\n            AssetContextMenuHelper.MoveAssetWithReferenceCheck(droppedFiles[0], targetFolder, () =\u003E LoadFolder(_currentFolder));\n            return;\n        }\n\n        foreach (var file in ev.Data.Files)\n        {\n            if (string.IsNullOrEmpty(file))\n                continue;\n\n            // Don\u0027t drop onto itself\n            if (file.Equals(targetFolder, StringComparison.OrdinalIgnoreCase))\n                continue;\n\n            // Files dragged in from outside the project must always be copied, never moved\n            bool copyThis = isCopy || AssetContextMenuHelper.IsExternalSource(file);\n\n            try\n            {\n                var fileName = Path.GetFileName(file);\n                var destPath = Path.Combine(targetFolder, fileName);\n\n                // Don\u0027t overwrite if destination is same as source\n                if (Path.GetFullPath(file).Equals(Path.GetFullPath(destPath), StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                if (Directory.Exists(file))\n                {\n                    // It\u0027s a directory\n                    if (copyThis)\n                        CopyDirectory(file, destPath);\n                    else\n                        EditorUtility.RenameDirectory(file, destPath);\n\n                    // Register the dropped files so they compile immediately\n                    AssetContextMenuHelper.RegisterNewPath(destPath);\n                }\n                else if (File.Exists(file))\n                {\n                    // Check if it\u0027s a registered asset\n                    var asset = AssetSystem.FindByPath(file);\n\n                    if (asset != null \u0026\u0026 !asset.IsDeleted)\n                    {\n                        // Use EditorUtility for proper asset handling\n                        if (copyThis)\n                            EditorUtility.CopyAssetToDirectory(asset, targetFolder);\n                        else\n                            EditorUtility.MoveAssetToDirectory(asset, targetFolder);\n                    }\n                    else\n                    {\n                        // Regular file, not an asset yet\n                        if (copyThis)\n                            File.Copy(file, destPath, overwrite: false);\n                        else\n                            File.Move(file, destPath, overwrite: false);\n\n                        // Register it so it compiles immediately instead of appearing uncompiled\n                        AssetContextMenuHelper.RegisterNewPath(destPath);\n                    }\n                }\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to {(copyThis ? \u0022copy\u0022 : \u0022move\u0022)} \u0027{file}\u0027: {ex.Message}\u0022);\n            }\n        }\n\n        // Refresh the view\n        LoadFolder(_currentFolder);\n    }\n\n    /// \u003Csummary\u003E\n    /// Recursively copy a directory\n    /// \u003C/summary\u003E\n    private static void CopyDirectory(string sourceDir, string destDir)\n    {\n        Directory.CreateDirectory(destDir);\n\n        foreach (var file in Directory.GetFiles(sourceDir))\n        {\n            File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)));\n        }\n\n        foreach (var dir in Directory.GetDirectories(sourceDir))\n        {\n            CopyDirectory(dir, Path.Combine(destDir, Path.GetFileName(dir)));\n        }\n    }\n\n    protected override void OnContextMenu(ContextMenuEvent e)\n    {\n        int index = GetItemAtPosition(e.LocalPosition);\n        var menu = new ContextMenu(this);\n\n        // If clicking on empty space, show folder-level context menu\n        if (index \u003C 0)\n        {\n            if (!string.IsNullOrEmpty(_currentFolder))\n            {\n                var createMenu = menu.AddMenu(\u0022Create\u0022, \u0022add\u0022);\n                AssetCreator.AddOptions(createMenu, _currentFolder);\n\n                // Paste files copied from Windows Explorer into the current folder\n                if (WindowsClipboard.HasFiles())\n                {\n                    menu.AddOption(\u0022Paste\u0022, \u0022content_paste\u0022, () =\u003E\n                    {\n                        AssetContextMenuHelper.PasteFromClipboard(_currentFolder);\n                        LoadFolder(_currentFolder);\n                    });\n                }\n\n                menu.AddSeparator();\n                menu.AddOption(\u0022Open in Explorer\u0022, \u0022folder_open\u0022, () =\u003E EditorUtility.OpenFolder(_currentFolder));\n                menu.AddOption(\u0022Refresh\u0022, \u0022refresh\u0022, () =\u003E LoadFolder(_currentFolder));\n            }\n            menu.OpenAtCursor();\n            e.Accepted = true;\n            return;\n        }\n\n        // If right-clicking on a selected item and multiple items are selected, show multi-select menu\n        if (_selectedIndices.Contains(index) \u0026\u0026 _selectedIndices.Count \u003E 1)\n        {\n            var selectedFiles = _selectedIndices\n                .Where(i =\u003E i \u003E= 0 \u0026\u0026 i \u003C _items.Count)\n                .Select(i =\u003E _items[i])\n                .Where(i =\u003E !i.IsCloud \u0026\u0026 !i.IsFolder)\n                .Select(i =\u003E (i.Path, i.Asset))\n                .ToList();\n\n            if (selectedFiles.Count \u003E 0)\n            {\n                AssetContextMenuHelper.BuildMultiFileMenu(menu, selectedFiles, () =\u003E LoadFolder(_currentFolder));\n            }\n\n            menu.OpenAtCursor();\n            e.Accepted = true;\n            return;\n        }\n\n        var item = _items[index];\n\n        if (item.IsCloud)\n        {\n            menu.AddOption(\u0022Open in Browser\u0022, \u0022open_in_new\u0022, () =\u003E\n            {\n                var url = $\u0022https://sbox.game/{item.Package?.FullIdent}\u0022;\n                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n                {\n                    FileName = url,\n                    UseShellExecute = true\n                });\n            });\n\n            menu.AddOption(\u0022Copy Identifier\u0022, \u0022content_copy\u0022, () =\u003E\n            {\n                EditorUtility.Clipboard.Copy(item.Package?.FullIdent ?? \u0022\u0022);\n            });\n        }\n        else if (item.IsFolder)\n        {\n            AssetContextMenuHelper.BuildFolderMenu(\n                menu,\n                item.Path,\n                item.Name,\n                isRoot: false,\n                onOpen: () =\u003E OnFolderNavigate?.Invoke(item.Path),\n                onRename: () =\u003E StartRename(index),\n                onRefresh: () =\u003E LoadFolder(_currentFolder),\n                onDeleted: () =\u003E LoadFolder(_currentFolder));\n        }\n        else\n        {\n            AssetContextMenuHelper.BuildFileMenu(\n                menu,\n                item.Path,\n                item.Asset,\n                onRename: () =\u003E StartRename(_items.IndexOf(item)),\n                onChanged: () =\u003E LoadFolder(_currentFolder));\n        }\n\n        menu.OpenAtCursor();\n        e.Accepted = true;\n    }\n\n    private string _currentFolder;\n\n    private void StartRename(int index)\n    {\n        // For now, use a simple input dialog approach\n        // In a full implementation, you\u0027d want inline renaming\n        if (index \u003C 0 || index \u003E= _items.Count) return;\n        var item = _items[index];\n\n        var dialog = new LineEditDialog(\u0022Rename\u0022, item.Name);\n        dialog.OnConfirm = (newName) =\u003E\n        {\n            if (string.IsNullOrWhiteSpace(newName) || newName == item.Name)\n                return;\n\n            try\n            {\n                var directory = Path.GetDirectoryName(item.Path);\n                var newPath = Path.Combine(directory, newName);\n\n                if (item.IsFolder)\n                {\n                    Directory.Move(item.Path, newPath);\n                }\n                else\n                {\n                    // Preserve extension if not provided\n                    if (!Path.HasExtension(newName))\n                    {\n                        newName \u002B= item.Extension;\n                        newPath = Path.Combine(directory, newName);\n                    }\n                    File.Move(item.Path, newPath);\n                }\n\n                LoadFolder(_currentFolder);\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to rename: {ex.Message}\u0022);\n            }\n        };\n        dialog.Show();\n    }\n\n\n    private static string GetIconForExtension(string ext)\n    {\n        return ext switch\n        {\n            \u0022.vmdl\u0022 or \u0022.fbx\u0022 or \u0022.obj\u0022 or \u0022.gltf\u0022 or \u0022.glb\u0022 =\u003E \u0022view_in_ar\u0022,\n            \u0022.png\u0022 or \u0022.jpg\u0022 or \u0022.jpeg\u0022 or \u0022.tga\u0022 or \u0022.vtex\u0022 or \u0022.psd\u0022 =\u003E \u0022image\u0022,\n            \u0022.vmat\u0022 =\u003E \u0022texture\u0022,\n            \u0022.wav\u0022 or \u0022.mp3\u0022 or \u0022.ogg\u0022 or \u0022.vsnd\u0022 =\u003E \u0022audiotrack\u0022,\n            \u0022.cs\u0022 or \u0022.razor\u0022 =\u003E \u0022code\u0022,\n            \u0022.scss\u0022 or \u0022.css\u0022 =\u003E \u0022style\u0022,\n            \u0022.shader\u0022 or \u0022.shdrgrph\u0022 =\u003E \u0022gradient\u0022,\n            \u0022.prefab\u0022 =\u003E \u0022inventory_2\u0022,\n            \u0022.scene\u0022 =\u003E \u0022landscape\u0022,\n            \u0022.json\u0022 or \u0022.xml\u0022 =\u003E \u0022data_object\u0022,\n            \u0022.txt\u0022 or \u0022.md\u0022 =\u003E \u0022description\u0022,\n            \u0022.item\u0022 =\u003E \u0022category\u0022,\n            _ =\u003E \u0022description\u0022\n        };\n    }\n\n    private static Color GetColorForExtension(string ext, Asset asset)\n    {\n        if (asset?.AssetType?.Color != null \u0026\u0026 asset.AssetType.Color != default)\n            return asset.AssetType.Color;\n\n        return ext switch\n        {\n            \u0022.cs\u0022 =\u003E new Color(0.4f, 0.7f, 1.0f),\n            \u0022.razor\u0022 =\u003E new Color(0.6f, 0.4f, 0.9f),\n            \u0022.shader\u0022 =\u003E new Color(0.3f, 0.9f, 0.5f),\n            \u0022.vmdl\u0022 =\u003E new Color(0.9f, 0.6f, 0.3f),\n            \u0022.vmat\u0022 =\u003E new Color(0.9f, 0.4f, 0.6f),\n            \u0022.prefab\u0022 =\u003E new Color(0.3f, 0.8f, 0.9f),\n            \u0022.scene\u0022 =\u003E new Color(0.9f, 0.9f, 0.3f),\n            _ =\u003E Theme.Text.WithAlpha(0.7f)\n        };\n    }\n\n    private static string GetIconForPackageType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E \u0022view_in_ar\u0022,\n            \u0022material\u0022 =\u003E \u0022texture\u0022,\n            \u0022sound\u0022 =\u003E \u0022audiotrack\u0022,\n            \u0022map\u0022 =\u003E \u0022landscape\u0022,\n            _ =\u003E \u0022cloud_download\u0022\n        };\n    }\n\n    private static Color GetColorForPackageType(string typeName)\n    {\n        return typeName switch\n        {\n            \u0022model\u0022 =\u003E new Color(0.9f, 0.6f, 0.3f),\n            \u0022material\u0022 =\u003E new Color(0.9f, 0.4f, 0.6f),\n            \u0022sound\u0022 =\u003E new Color(0.4f, 0.7f, 1.0f),\n            \u0022map\u0022 =\u003E new Color(0.9f, 0.9f, 0.3f),\n            _ =\u003E Theme.Text.WithAlpha(0.7f)\n        };\n    }\n\n    private class GridItem\n    {\n        public string Path;\n        public string Name;\n        public bool IsFolder;\n        public bool IsCloud;\n        public Asset Asset;\n        public Pixmap Thumbnail;\n        public string Extension;\n        public Package Package;\n        public string Author;\n        public string CloudThumb; // URL for cloud package thumbnail\n    }\n}\n\n/// \u003Csummary\u003E\n/// Simple popup for entering text (used for renaming)\n/// \u003C/summary\u003E\ninternal class LineEditDialog : PopupWidget\n{\n    private LineEdit _lineEdit;\n    public Action\u003Cstring\u003E OnConfirm;\n\n    public LineEditDialog(string title, string initialText) : base(null)\n    {\n        Layout = Layout.Row();\n        Layout.Margin = 4;\n        Layout.Spacing = 4;\n\n        _lineEdit = Layout.Add(new LineEdit(this));\n        _lineEdit.Text = initialText;\n        _lineEdit.MinimumWidth = 200;\n        _lineEdit.SelectAll();\n        _lineEdit.ReturnPressed \u002B= () =\u003E\n        {\n            OnConfirm?.Invoke(_lineEdit.Text);\n            Close();\n        };\n\n        var okBtn = Layout.Add(new Button(\u0022OK\u0022, this));\n        okBtn.Clicked = () =\u003E\n        {\n            OnConfirm?.Invoke(_lineEdit.Text);\n            Close();\n        };\n\n        _lineEdit.Focus();\n    }\n\n    public new void Show()\n    {\n        OpenAtCursor();\n        _lineEdit.Focus();\n    }\n}\n"},{"Ident":"evilinc.treeassetsbrowser","Path":"Editor/AssetFolderNode.cs","FileName":"AssetFolderNode.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":309726,"IsPrivate":false,"Code":"using Editor;\nusing Label = Editor.Label;\nusing Sandbox;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nnamespace GeneralGame.Editor;\n\n/// \u003Csummary\u003E\n/// Tree node representing a folder in the asset browser\n/// \u003C/summary\u003E\npublic class AssetFolderNode : TreeNode\n{\n    public string FullPath { get; }\n    public string DisplayName { get; }\n    public string IconName { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Tracks whether this folder is currently expanded in the tree view.\n    /// Updated during OnPaint.\n    /// \u003C/summary\u003E\n    public bool IsExpanded { get; private set; }\n\n    /// \u003Csummary\u003E\n    /// Set to true to auto-expand this folder on first paint.\n    /// \u003C/summary\u003E\n    public bool ShouldAutoExpand { get; set; }\n\n    /// \u003Csummary\u003E\n    /// Dictionary of paths that should be auto-expanded, keyed by panel identifier.\n    /// Used to persist across node rebuilds while keeping panels separate.\n    /// \u003C/summary\u003E\n    public static Dictionary\u003Cobject, HashSet\u003Cstring\u003E\u003E PathsToAutoExpandByPanel { get; } = new();\n\n    /// \u003Csummary\u003E\n    /// Static event fired when any folder\u0027s expanded state changes.\n    /// Parameters: (panelKey, fullPath, isExpanded)\n    /// panelKey is TreeView.Parent which identifies the panel\n    /// \u003C/summary\u003E\n    public static event Action\u003Cobject, string, bool\u003E OnExpandedStateChanged;\n\n    private FileSystemWatcher _watcher;\n    private bool _isRoot;\n\n    public override bool HasChildren =\u003E Directory.Exists(FullPath) \u0026\u0026\n        (Directory.EnumerateDirectories(FullPath).Any() || Directory.EnumerateFiles(FullPath).Any());\n\n    public override string Name =\u003E DisplayName;\n    public override bool CanEdit =\u003E !_isRoot;\n\n    public AssetFolderNode(string path, string displayName = null, string icon = \u0022folder\u0022) : base()\n    {\n        FullPath = Path.GetFullPath(path);\n        DisplayName = displayName ?? Path.GetFileName(path);\n        IconName = icon;\n        _isRoot = displayName != null;\n        Value = this;\n\n        // Watch for changes\n        if (Directory.Exists(FullPath))\n        {\n            try\n            {\n                _watcher = new FileSystemWatcher(FullPath);\n                _watcher.EnableRaisingEvents = true;\n                _watcher.Created \u002B= OnFileSystemChanged;\n                _watcher.Deleted \u002B= OnFileSystemChanged;\n                _watcher.Renamed \u002B= OnFileSystemChanged;\n            }\n            catch\n            {\n                // Ignore watcher errors\n            }\n        }\n    }\n\n    ~AssetFolderNode()\n    {\n        _watcher?.Dispose();\n    }\n\n    private void OnFileSystemChanged(object sender, FileSystemEventArgs e)\n    {\n        MainThread.Queue(Dirty);\n    }\n\n    /// \u003Csummary\u003E\n    /// Public method to force building children\n    /// \u003C/summary\u003E\n    public void EnsureChildrenBuilt()\n    {\n        if (Children == null || !Children.Any())\n        {\n            BuildChildren();\n        }\n    }\n\n\n    protected override void BuildChildren()\n    {\n        Clear();\n\n        if (!Directory.Exists(FullPath))\n            return;\n\n        try\n        {\n            // Add subdirectories first\n            var directories = Directory.GetDirectories(FullPath)\n                .OrderBy(d =\u003E Path.GetFileName(d), StringComparer.OrdinalIgnoreCase);\n\n            foreach (var dir in directories)\n            {\n                var dirInfo = new DirectoryInfo(dir);\n\n                // Skip hidden folders\n                if (dirInfo.Attributes.HasFlag(FileAttributes.Hidden))\n                    continue;\n\n                // Skip obj folder in code directories\n                if (dirInfo.Name.Equals(\u0022obj\u0022, StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                // Skip .sbox folder\n                if (dirInfo.Name.StartsWith(\u0022.\u0022))\n                    continue;\n\n                AddItem(new AssetFolderNode(dir));\n            }\n\n            // Add files\n            var files = Directory.GetFiles(FullPath)\n                .OrderBy(f =\u003E Path.GetFileName(f), StringComparer.OrdinalIgnoreCase);\n\n            foreach (var file in files)\n            {\n                var fileInfo = new FileInfo(file);\n\n                // Skip hidden files\n                if (fileInfo.Attributes.HasFlag(FileAttributes.Hidden))\n                    continue;\n\n                // Skip generated/meta files\n                var fileName = fileInfo.Name;\n                if (fileName.Contains(\u0022.generated\u0022, StringComparison.OrdinalIgnoreCase) ||\n                    fileName.EndsWith(\u0022.meta\u0022, StringComparison.OrdinalIgnoreCase) ||\n                    fileName.StartsWith(\u0022.\u0022))\n                    continue;\n\n                // Skip compiled assets if source exists\n                if (fileName.EndsWith(\u0022_c\u0022))\n                {\n                    var sourcePath = file[..^2]; // Remove _c\n                    if (File.Exists(sourcePath))\n                        continue;\n                }\n\n                AddItem(new AssetFileNode(file));\n            }\n        }\n        catch (Exception ex)\n        {\n            Log.Warning($\u0022Error building folder tree: {ex.Message}\u0022);\n        }\n    }\n\n    public override void OnPaint(VirtualWidget item)\n    {\n        // Auto-expand if requested (for restoring saved state)\n        // Check both instance flag and panel-specific set\n        var panelKey = TreeView?.Parent;\n        HashSet\u003Cstring\u003E panelPaths = null;\n        bool inPanelSet = panelKey != null \u0026\u0026\n                         PathsToAutoExpandByPanel.TryGetValue(panelKey, out panelPaths) \u0026\u0026\n                         panelPaths.Contains(FullPath);\n\n        bool shouldExpand = ShouldAutoExpand || inPanelSet;\n        if (shouldExpand)\n        {\n            ShouldAutoExpand = false;\n            if (inPanelSet \u0026\u0026 panelPaths != null)\n            {\n                panelPaths.Remove(FullPath);\n            }\n\n            if (!item.IsOpen)\n            {\n                EnsureChildrenBuilt();\n                var tv = TreeView;\n                MainThread.Queue(() =\u003E tv?.Toggle(this));\n            }\n        }\n\n        // Track expanded state and notify if changed\n        if (IsExpanded != item.IsOpen)\n        {\n            IsExpanded = item.IsOpen;\n            OnExpandedStateChanged?.Invoke(panelKey, FullPath, IsExpanded);\n        }\n\n        PaintSelection(item);\n\n        var rect = item.Rect;\n\n        // Folder icon\n        Paint.SetPen(Theme.Yellow);\n        var iconRect = Paint.DrawIcon(rect, item.IsOpen ? \u0022folder_open\u0022 : IconName, 16, TextFlag.LeftCenter);\n\n        rect.Left \u002B= 22;\n\n        // Folder name\n        Paint.SetPen(Theme.Text);\n        Paint.SetDefaultFont();\n        Paint.DrawText(rect, DisplayName, TextFlag.LeftCenter);\n    }\n\n    public override bool OnContextMenu()\n    {\n        var menu = new ContextMenu(null);\n\n        AssetContextMenuHelper.BuildFolderMenu(\n            menu,\n            FullPath,\n            DisplayName,\n            _isRoot,\n            onOpen: () =\u003E\n            {\n                EnsureChildrenBuilt();\n                TreeView?.Open(this);\n            },\n            onRename: () =\u003E ShowRenameDialog(),\n            onRefresh: () =\u003E Dirty(),\n            onDeleted: () =\u003E Parent?.Dirty());\n\n        menu.OpenAtCursor();\n        return true;\n    }\n\n    private void ShowRenameDialog()\n    {\n        var dialog = new RenameDialog(\u0022Rename Folder\u0022, DisplayName);\n        dialog.OnConfirm = (newName) =\u003E\n        {\n            if (string.IsNullOrWhiteSpace(newName) || newName == DisplayName)\n                return;\n\n            var newPath = Path.Combine(Path.GetDirectoryName(FullPath), newName);\n            try\n            {\n                Directory.Move(FullPath, newPath);\n                Parent?.Dirty();\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to rename folder: {ex.Message}\u0022);\n            }\n        };\n        dialog.Show();\n    }\n\n\n    public override void OnRename(VirtualWidget item, string text, List\u003CTreeNode\u003E selection = null)\n    {\n        if (string.IsNullOrWhiteSpace(text) || text == DisplayName)\n            return;\n\n        var newPath = Path.Combine(Path.GetDirectoryName(FullPath), text);\n        try\n        {\n            Directory.Move(FullPath, newPath);\n            Parent?.Dirty();\n        }\n        catch (Exception ex)\n        {\n            Log.Error($\u0022Failed to rename folder: {ex.Message}\u0022);\n        }\n    }\n\n    public override bool OnDragStart()\n    {\n        if (_isRoot)\n            return false;\n\n        var drag = new Drag(TreeView);\n        drag.Data.Text = FullPath;\n        drag.Data.Url = new Uri(\u0022file:///\u0022 \u002B FullPath);\n        drag.Execute();\n        return true;\n    }\n\n    public override DropAction OnDragDrop(BaseItemWidget.ItemDragEvent e)\n    {\n        // Dragging GameObject(s) from the hierarchy: dropping onto a folder creates a prefab there\n        if (e.Data.Object is GameObject[] gos \u0026\u0026 gos.Length \u003E 0)\n        {\n            if (e.IsDrop)\n                AssetContextMenuHelper.CreatePrefabFromGameObjects(gos, FullPath, () =\u003E Dirty());\n\n            return DropAction.Copy;\n        }\n\n        // Report Copy for external (Explorer) sources, otherwise Windows deletes the originals on a \u0022move\u0022\n        bool anyExternal = e.Data.Files.Any(f =\u003E AssetContextMenuHelper.IsExternalSource(f));\n        var dropAction = (e.HasCtrl || anyExternal) ? DropAction.Copy : DropAction.Move;\n\n        // If not actually dropping, just return the action (for hover feedback)\n        if (!e.IsDrop)\n            return dropAction;\n\n        // Backward compatibility: moving a single asset opens a modal to update references to its old path\n        var droppedFiles = e.Data.Files.Where(f =\u003E !string.IsNullOrEmpty(f)).ToList();\n        if (AssetContextMenuHelper.IsBackwardCompatMove(droppedFiles, dropAction == DropAction.Copy))\n        {\n            AssetContextMenuHelper.MoveAssetWithReferenceCheck(droppedFiles[0], FullPath, () =\u003E Dirty());\n            return dropAction;\n        }\n\n        // Check if any directories are being moved (not copied)\n        var foldersToMove = new List\u003Cstring\u003E();\n        var filesToProcess = new List\u003Cstring\u003E();\n\n        foreach (var file in e.Data.Files)\n        {\n            if (file.ToLowerInvariant() == FullPath.ToLowerInvariant())\n                continue;\n\n            var fileName = Path.GetFileName(file);\n            var destPath = Path.Combine(FullPath, fileName);\n\n            if (Path.GetFullPath(file).Equals(Path.GetFullPath(destPath), StringComparison.OrdinalIgnoreCase))\n                continue;\n\n            // External folders (from Explorer) are copied via ProcessFiles; only internal folders get the move-with-confirmation flow\n            if (Directory.Exists(file) \u0026\u0026 dropAction == DropAction.Move \u0026\u0026 !AssetContextMenuHelper.IsExternalSource(file))\n            {\n                foldersToMove.Add(file);\n            }\n            else\n            {\n                filesToProcess.Add(file);\n            }\n        }\n\n        // Process files immediately (no confirmation needed)\n        ProcessFiles(filesToProcess, dropAction);\n\n        // Show confirmation for folder moves\n        if (foldersToMove.Count \u003E 0)\n        {\n            var folderNames = string.Join(\u0022, \u0022, foldersToMove.Select(Path.GetFileName));\n            var message = foldersToMove.Count == 1\n                ? $\u0022Move folder \\\u0022{Path.GetFileName(foldersToMove[0])}\\\u0022 to \\\u0022{DisplayName}\\\u0022?\u0022\n                : $\u0022Move {foldersToMove.Count} folders to \\\u0022{DisplayName}\\\u0022?\u0022;\n\n            var details = foldersToMove.Count == 1\n                ? $\u0022From: {Path.GetDirectoryName(foldersToMove[0])}\\nTo: {FullPath}\u0022\n                : $\u0022Folders: {folderNames}\u0022;\n\n            var targetPath = FullPath;\n            var folderNode = this;\n\n            ConfirmationDialog.Show(\n                \u0022Move Folder\u0022,\n                message,\n                details,\n                onConfirm: () =\u003E\n                {\n                    foreach (var folder in foldersToMove)\n                    {\n                        try\n                        {\n                            var fileName = Path.GetFileName(folder);\n                            var destPath = Path.Combine(targetPath, fileName);\n                            Directory.Move(folder, destPath);\n                        }\n                        catch (Exception ex)\n                        {\n                            Log.Error($\u0022Failed to move folder: {ex.Message}\u0022);\n                        }\n                    }\n                    folderNode.Dirty();\n                }\n            );\n        }\n        else\n        {\n            // Refresh immediately if no folders to move\n            Dirty();\n        }\n\n        return dropAction;\n    }\n\n    /// \u003Csummary\u003E\n    /// Process files and folders (copy operations or file moves)\n    /// \u003C/summary\u003E\n    private void ProcessFiles(List\u003Cstring\u003E files, DropAction action)\n    {\n        foreach (var file in files)\n        {\n            // Files dragged in from outside the project must always be copied, never moved\n            var fileAction = AssetContextMenuHelper.IsExternalSource(file) ? DropAction.Copy : action;\n\n            try\n            {\n                var fileName = Path.GetFileName(file);\n                var destPath = Path.Combine(FullPath, fileName);\n\n                // Skip if same path\n                if (Path.GetFullPath(file).Equals(Path.GetFullPath(destPath), StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                if (Directory.Exists(file))\n                {\n                    // It\u0027s a directory\n                    if (fileAction == DropAction.Copy)\n                        CopyDirectory(file, destPath);\n                    else\n                    {\n                        EditorUtility.RenameDirectory(file, destPath);\n                    }\n\n                    // Register the dropped files so they compile immediately\n                    AssetContextMenuHelper.RegisterNewPath(destPath);\n                }\n                else if (File.Exists(file))\n                {\n                    // Check if it\u0027s a registered asset\n                    var asset = AssetSystem.FindByPath(file);\n\n                    if (asset != null \u0026\u0026 !asset.IsDeleted)\n                    {\n                        // Use EditorUtility for proper asset handling\n                        if (fileAction == DropAction.Copy)\n                            EditorUtility.CopyAssetToDirectory(asset, FullPath);\n                        else\n                            EditorUtility.MoveAssetToDirectory(asset, FullPath);\n                    }\n                    else\n                    {\n                        // Regular file, not an asset yet\n                        if (fileAction == DropAction.Copy)\n                            File.Copy(file, destPath);\n                        else\n                            File.Move(file, destPath);\n\n                        // Register it so it compiles immediately instead of appearing uncompiled\n                        AssetContextMenuHelper.RegisterNewPath(destPath);\n                    }\n                }\n            }\n            catch (Exception ex)\n            {\n                Log.Error($\u0022Failed to {(fileAction == DropAction.Copy ? \u0022copy\u0022 : \u0022move\u0022)}: {ex.Message}\u0022);\n            }\n        }\n    }\n\n    private static void CopyDirectory(string sourceDir, string destDir)\n    {\n        Directory.CreateDirectory(destDir);\n\n        foreach (var file in Directory.GetFiles(sourceDir))\n        {\n            File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)));\n        }\n\n        foreach (var dir in Directory.GetDirectories(sourceDir))\n        {\n            CopyDirectory(dir, Path.Combine(destDir, Path.GetFileName(dir)));\n        }\n    }\n\n    /// \u003Csummary\u003E\n    /// Check if this folder or any of its contents matches the search filter.\n    /// Scans filesystem directly to find matches in unopened folders.\n    /// \u003C/summary\u003E\n    public bool MatchesFilter(string filter)\n    {\n        if (string.IsNullOrEmpty(filter))\n            return true;\n\n        // Check folder name\n        if (DisplayName.ToLowerInvariant().Contains(filter))\n            return true;\n\n        // If children are already built, check them\n        if (Children != null \u0026\u0026 Children.Any())\n        {\n            foreach (var child in Children)\n            {\n                if (child is AssetFolderNode folder \u0026\u0026 folder.MatchesFilter(filter))\n                    return true;\n                if (child is AssetFileNode file \u0026\u0026 file.MatchesFilter(filter))\n                    return true;\n            }\n            return false;\n        }\n\n        // Otherwise scan filesystem directly (without creating node objects)\n        return ScanDirectoryForFilter(FullPath, filter, maxDepth: 5);\n    }\n\n    /// \u003Csummary\u003E\n    /// Scan directory for filter match without creating node objects.\n    /// Limited depth to prevent excessive recursion.\n    /// \u003C/summary\u003E\n    private static bool ScanDirectoryForFilter(string path, string filter, int maxDepth)\n    {\n        if (maxDepth \u003C= 0 || !Directory.Exists(path))\n            return false;\n\n        try\n        {\n            // Check files in this folder\n            foreach (var file in Directory.EnumerateFiles(path))\n            {\n                var fileName = Path.GetFileName(file).ToLowerInvariant();\n                if (fileName.Contains(filter))\n                    return true;\n            }\n\n            // Check subfolders recursively\n            foreach (var dir in Directory.EnumerateDirectories(path))\n            {\n                var dirName = Path.GetFileName(dir);\n\n                // Skip hidden/system folders\n                if (dirName.StartsWith(\u0022.\u0022) || dirName.Equals(\u0022obj\u0022, StringComparison.OrdinalIgnoreCase))\n                    continue;\n\n                // Check folder name\n                if (dirName.ToLowerInvariant().Contains(filter))\n                    return true;\n\n                // Recursively check contents (with depth limit)\n                if (ScanDirectoryForFilter(dir, filter, maxDepth - 1))\n                    return true;\n            }\n        }\n        catch\n        {\n            // Ignore filesystem errors\n        }\n\n        return false;\n    }\n\n    /// \u003Csummary\u003E\n    /// Find a node by its full path\n    /// \u003C/summary\u003E\n    public TreeNode FindNode(string path)\n    {\n        if (Path.GetFullPath(FullPath).Equals(path, StringComparison.OrdinalIgnoreCase))\n            return this;\n\n        // Build children if not built yet\n        if (Children == null || !Children.Any())\n            BuildChildren();\n\n        foreach (var child in Children)\n        {\n            if (child is AssetFolderNode folder)\n            {\n                if (path.StartsWith(folder.FullPath, StringComparison.OrdinalIgnoreCase))\n                {\n                    var result = folder.FindNode(path);\n                    if (result != null)\n                        return result;\n                }\n            }\n            else if (child is AssetFileNode file)\n            {\n                if (Path.GetFullPath(file.FullPath).Equals(path, StringComparison.OrdinalIgnoreCase))\n                    return file;\n            }\n        }\n\n        return null;\n    }\n\n    protected override bool HasDescendant(object obj)\n    {\n        if (obj is AssetFileNode fileNode)\n        {\n            return fileNode.FullPath.StartsWith(FullPath, StringComparison.OrdinalIgnoreCase);\n        }\n        if (obj is AssetFolderNode folderNode)\n        {\n            return folderNode.FullPath.StartsWith(FullPath, StringComparison.OrdinalIgnoreCase);\n        }\n        return false;\n    }\n}\n\n/// \u003Csummary\u003E\n/// Simple popup for renaming files/folders\n/// \u003C/summary\u003E\ninternal class RenameDialog : PopupWidget\n{\n    private LineEdit _lineEdit;\n    public Action\u003Cstring\u003E OnConfirm;\n\n    public RenameDialog(string title, string initialText) : base(null)\n    {\n        Layout = Layout.Row();\n        Layout.Margin = 4;\n        Layout.Spacing = 4;\n\n        _lineEdit = Layout.Add(new LineEdit(this));\n        _lineEdit.Text = initialText;\n        _lineEdit.MinimumWidth = 200;\n        _lineEdit.SelectAll();\n        _lineEdit.ReturnPressed \u002B= () =\u003E\n        {\n            OnConfirm?.Invoke(_lineEdit.Text);\n            Close();\n        };\n\n        var okBtn = Layout.Add(new Button(\u0022OK\u0022, this));\n        okBtn.Clicked = () =\u003E\n        {\n            OnConfirm?.Invoke(_lineEdit.Text);\n            Close();\n        };\n\n        _lineEdit.Focus();\n    }\n\n    public new void Show()\n    {\n        OpenAtCursor();\n        _lineEdit.Focus();\n    }\n}\n\n/// \u003Csummary\u003E\n/// Confirmation dialog for critical actions\n/// \u003C/summary\u003E\ninternal class ConfirmationDialog : Dialog\n{\n    public Action OnConfirm;\n    public Action OnCancel;\n\n    private Label _messageLabel;\n    private Label _detailsLabel;\n\n    public ConfirmationDialog(string title, string message, string details = null, string confirmText = \u0022Confirm\u0022, string cancelText = \u0022Cancel\u0022) : base(null)\n    {\n        Window.WindowTitle = title;\n        Window.Size = new Vector2(400, 180);\n        Window.MinimumSize = new Vector2(350, 150);\n\n        Layout = Layout.Column();\n        Layout.Margin = 16;\n        Layout.Spacing = 12;\n\n        // Warning icon and message\n        var headerRow = Layout.AddRow();\n        headerRow.Spacing = 12;\n\n        var iconLabel = headerRow.Add(new Label(\u0022\u26A0\uFE0F\u0022, this));\n        iconLabel.SetStyles(\u0022font-size: 24px;\u0022);\n\n        var textColumn = headerRow.AddColumn();\n        textColumn.Spacing = 4;\n\n        _messageLabel = textColumn.Add(new Label(message, this));\n        _messageLabel.SetStyles(\u0022font-size: 13px; font-weight: 600;\u0022);\n        _messageLabel.WordWrap = true;\n\n        if (!string.IsNullOrEmpty(details))\n        {\n            _detailsLabel = textColumn.Add(new Label(details, this));\n            _detailsLabel.SetStyles(\u0022font-size: 11px; color: #aaa;\u0022);\n            _detailsLabel.WordWrap = true;\n        }\n\n        headerRow.AddStretchCell();\n\n        Layout.AddStretchCell();\n\n        // Buttons\n        var buttonRow = Layout.AddRow();\n        buttonRow.Spacing = 8;\n        buttonRow.AddStretchCell();\n\n        var cancelBtn = buttonRow.Add(new Button(cancelText, this));\n        cancelBtn.MinimumWidth = 80;\n        cancelBtn.Clicked = () =\u003E\n        {\n            OnCancel?.Invoke();\n            Close();\n        };\n\n        var confirmBtn = buttonRow.Add(new Button.Primary(confirmText, this));\n        confirmBtn.MinimumWidth = 80;\n        confirmBtn.Clicked = () =\u003E\n        {\n            OnConfirm?.Invoke();\n            Close();\n        };\n    }\n\n    /// \u003Csummary\u003E\n    /// Show confirmation dialog and execute action if confirmed\n    /// \u003C/summary\u003E\n    public static void Show(string title, string message, string details, Action onConfirm, Action onCancel = null)\n    {\n        var dialog = new ConfirmationDialog(title, message, details);\n        dialog.OnConfirm = onConfirm;\n        dialog.OnCancel = onCancel;\n        dialog.Show();\n    }\n}\n"}]}