Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: add blender filepicker
nusaturn81a1c71cd394
diff --git a/bindings/python/CMakeLists.txt b/bindings/python/CMakeLists.txtindex 3f0a62b..c90a9c0 100644--- a/bindings/python/CMakeLists.txt+++ b/bindings/python/CMakeLists.txt@@ -93,4 +93,9 @@ if(BUI_BUILD_TESTS)COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_tk_input.py)set_tests_properties(buipy_tk_input PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")+ add_test(+ NAME buipy_filebrowser+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_filebrowser.py+ )+ set_tests_properties(buipy_filebrowser PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")endif()diff --git a/bindings/python/bui/filebrowser.py b/bindings/python/bui/filebrowser.pynew file mode 100644index 0000000..3e2b712--- /dev/null+++ b/bindings/python/bui/filebrowser.py@@ -0,0 +1,113 @@+"""Blender's file browser as a blocking file dialog.++The kit's ``filebrowser`` node (kit/intern/kit_filebrowser.c, a port of+Blender's editors/space_file) shown in its own window, the way Blender opens+a file browser for an operator. ``bui.tksyntax.filedialog`` and+``bui.qtsyntax.QFileDialog`` use it; set ``BUI_FILEDIALOG=native`` to get the+operating system's dialogs (through the stdlib Tk) instead.++ from bui import filebrowser+ path = filebrowser.ask("open", title="Open Image",+ filetypes=[("Images", "*.png *.jpg"), ("All files", "*")])++SPDX-License-Identifier: GPL-2.0-or-later+"""++from __future__ import annotations++import os+import time++import buipy++from bui import host++__all__ = ["ask", "enabled", "tk_filters", "qt_filters"]++_MODES = {"open": 0, "save": 1, "directory": 2}+_TITLES = {"open": "Open", "save": "Save As", "directory": "Select Folder"}+_POLL_SECONDS = 0.004+++def enabled() -> bool:+ """False when ``BUI_FILEDIALOG`` asks for the system dialogs."""+ return os.environ.get("BUI_FILEDIALOG", "").lower() not in ("native", "system", "tk")+++def _tk_entry(item) -> str:+ """One filetypes item: "Label", ("Label", "*.a *.b") or ("Label", ("*.a", "*.b"))."""+ if isinstance(item, str):+ return "%s\t%s" % (item, item)+ pats = item[1] if len(item) > 1 else "*"+ return "%s\t%s" % (item[0], pats if isinstance(pats, str) else " ".join(map(str, pats)))+++def tk_filters(filetypes) -> list:+ """tkinter ``filetypes`` -> the node's "Label\\tpattern ..." entries.++ Accepts ``[("Python", "*.py"), ("Images", ("*.png", "*.jpg")), ("Text", ".txt")]``.+ """+ return [_tk_entry(item) for item in filetypes or ()]+++def _qt_entry(part: str) -> str:+ label, _, rest = part.partition("(")+ pats = rest[:-1] if rest.endswith(")") else part+ return "%s\t%s" % (label.strip() or pats, pats)+++def qt_filters(filter_str) -> list:+ """A Qt name filter ("Images (*.png *.jpg);;All (*)") -> node filter entries."""+ return [_qt_entry(p.strip()) for p in (filter_str or "").split(";;") if p.strip()]+++def _browser(kind, initialdir, initialfile, entries, multiple):+ """A configured ``filebrowser`` node."""+ fb = buipy.KitNode("filebrowser")+ fb.set("mode", _MODES.get(kind, 0))+ fb.set("multiple", int(bool(multiple)))+ for key, value in (("filters", entries), ("dir", initialdir), ("file", initialfile)):+ if value:+ fb.set(key, value if key == "filters" else os.fspath(value))+ return fb+++def _run(fb, title):+ """Show the node in a window until it is answered or closed; the chosen paths."""+ win = host.Window(buipy.KitContext(fb), title,+ (int(fb.get("dialog_width")), int(fb.get("dialog_height"))))+ win.show()+ try:+ while fb.get("state") == 0 and win.is_open:+ host.update()+ time.sleep(_POLL_SECONDS)+ finally:+ if win.is_open:+ win.close()+ return list(fb.strs("result")) if fb.get("state") > 0 else []+++def _with_extension(path, defaultextension):+ """Tk's defaultextension: added when the typed name has none."""+ if not defaultextension or os.path.splitext(path)[1]:+ return path+ return path + ("" if defaultextension.startswith(".") else ".") + defaultextension+++def ask(kind: str = "open", title: str = None, initialdir: str = None,+ initialfile: str = None, filetypes=None, multiple: bool = False,+ defaultextension: str = None, filters: list = None):+ """Show the browser and wait for an answer.++ ``kind`` is "open", "save" or "directory". Returns the chosen path (a list+ with ``multiple``), or None when cancelled. ``filters`` takes node filter+ entries directly ("Label\\tpattern ..."), ``filetypes`` tkinter's form.+ """+ fb = _browser(kind, initialdir, initialfile, list(filters or ()) + tk_filters(filetypes),+ multiple)+ result = _run(fb, title or _TITLES.get(kind, "Open"))+ if not result:+ return None+ if kind == "save":+ result[0] = _with_extension(result[0], defaultextension)+ return result if multiple else result[0]diff --git a/bindings/python/bui/qtsyntax.py b/bindings/python/bui/qtsyntax.pyindex a02764b..7a7d4f9 100644--- a/bindings/python/bui/qtsyntax.py+++ b/bindings/python/bui/qtsyntax.py@@ -22,12 +22,13 @@ SPDX-License-Identifier: GPL-2.0-or-laterfrom __future__ import annotations+import osimport timefrom typing import Callable, List, Optionalimport buipy-from bui import _realtk, host+from bui import _realtk, filebrowser, hostfrom bui.components.core import (EV_ACTIVATE, EV_CHANGE, EV_CLICK, EV_DOUBLE, EV_ENTER, # noqa: F401EV_KEY, EV_LEAVE, EV_MOTION, EV_PRESS, EV_RELEASE,EV_RENAME, EV_SUBMIT, EV_TOGGLE, EV_WHEEL)@@ -2739,8 +2740,30 @@ class QMessageBox:class QFileDialog:+ @staticmethod+ def _blender(kind, caption, directory, filter, multiple=False): # noqa: A002+ """Blender's file browser (bui.filebrowser); None when BUI_FILEDIALOG=native."""+ if not filebrowser.enabled():+ return None+ initialdir, initialfile = (directory, None) if not directory or os.path.isdir(+ directory) else os.path.split(directory)+ result = filebrowser.ask(kind, title=caption or None, initialdir=initialdir or None,+ initialfile=initialfile, multiple=multiple,+ filters=filebrowser.qt_filters(filter))+ if result is None:+ return [] if multiple else ""+ return result++ @staticmethod+ def getOpenFileNames(parent=None, caption="", directory="", filter="", *a): # noqa: N802,A002+ paths = QFileDialog._blender("open", caption, directory, filter, multiple=True)+ return (paths or [], "")+@staticmethoddef getOpenFileName(parent=None, caption="", directory="", filter="", *a): # noqa: N802,A002+ path = QFileDialog._blender("open", caption, directory, filter)+ if path is not None:+ return path, ""try:filedialog = _realtk.module("tkinter.filedialog")return filedialog.askopenfilename(title=caption), ""@@ -2749,6 +2772,9 @@ class QFileDialog:@staticmethoddef getSaveFileName(parent=None, caption="", directory="", filter="", *a): # noqa: N802,A002+ path = QFileDialog._blender("save", caption, directory, filter)+ if path is not None:+ return path, ""try:filedialog = _realtk.module("tkinter.filedialog")return filedialog.asksaveasfilename(title=caption), ""@@ -2757,6 +2783,9 @@ class QFileDialog:@staticmethoddef getExistingDirectory(parent=None, caption="", directory="", *a): # noqa: N802+ path = QFileDialog._blender("directory", caption, directory, "")+ if path is not None:+ return pathtry:filedialog = _realtk.module("tkinter.filedialog")return filedialog.askdirectory(title=caption)diff --git a/bindings/python/bui/tksyntax/filedialog.py b/bindings/python/bui/tksyntax/filedialog.pyindex 7ba8355..1b3337a 100644--- a/bindings/python/bui/tksyntax/filedialog.py+++ b/bindings/python/bui/tksyntax/filedialog.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport os-from bui import _realtk+from bui import _realtk, filebrowserfrom .commondialog import Dialog__all__ = ["FileDialog", "LoadFileDialog", "SaveFileDialog", "Open", "SaveAs", "Directory",@@ -18,8 +18,26 @@ __all__ = ["FileDialog", "LoadFileDialog", "SaveFileDialog", "Open", "SaveAs", ""askopenfiles", "asksaveasfile", "askdirectory"]+_BROWSER_KINDS = {"askdirectory": "directory", "asksaveasfilename": "save"}+++def _blender(kind, options):+ """Blender's file browser (bui.filebrowser) with tkinter's options and return values."""+ multiple = kind == "askopenfilenames"+ result = filebrowser.ask(+ _BROWSER_KINDS.get(kind, "open"),+ title=options.get("title"), initialdir=options.get("initialdir"),+ initialfile=options.get("initialfile"), filetypes=options.get("filetypes"),+ multiple=multiple, defaultextension=options.get("defaultextension"))+ if result is None:+ return () if multiple else ""+ return tuple(result) if multiple else result++def _native(kind, options):"""Call the real tkinter.filedialog function `kind` with our options."""+ if filebrowser.enabled():+ return _blender(kind, options)from bui import hostreal = _realtk.module("tkinter.filedialog")opts = {k: v for k, v in options.items() if k != "parent"}diff --git a/bindings/python/tests/test_filebrowser.py b/bindings/python/tests/test_filebrowser.pynew file mode 100644index 0000000..f11b6d5--- /dev/null+++ b/bindings/python/tests/test_filebrowser.py@@ -0,0 +1,186 @@+"""The "filebrowser" node (kit/intern/kit_filebrowser.c) and bui.filebrowser, headless.++SPDX-License-Identifier: GPL-2.0-or-later+"""+import os+import shutil+import sys+import tempfile++sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))++TMP = tempfile.mkdtemp(prefix="bui_fb_")+os.environ["BUI_BOOKMARKS"] = os.path.join(TMP, "config", "bookmarks.txt")++import bui # noqa: E402,F401+import buipy # noqa: E402+from bui import filebrowser # noqa: E402++W, H = 1000, 600+CTRL = 2+ROOT = os.path.join(TMP, "files")+++def setup_tree():+ os.makedirs(os.path.join(ROOT, "Projects"))+ os.makedirs(os.path.join(ROOT, "renders"))+ sizes = {"b_small.txt": 10, "a_big.py": 5000, "c_mid.blend": 300, ".hidden": 1}+ for name, size in sizes.items():+ with open(os.path.join(ROOT, name), "wb") as fh:+ fh.write(b"x" * size)+++class Browser:+ def __init__(self, **props):+ self.node = buipy.KitNode("filebrowser")+ for k, v in props.items():+ self.node.set(k, v)+ self.ctx = buipy.KitContext(self.node)+ self.raster = buipy.Raster(W, H)+ self.render(True)+ self.list = next(c for c in self.node.children if c.type == "filelist")++ def render(self, full=False):+ self.ctx.render(W, H, self.raster, full)++ def over_list(self):+ x, y, w, h = self.list.rect+ self.ctx.motion(x + w // 3, y + h // 2, 0)++ def key(self, keysym, mods=0, text=""):+ self.over_list()+ self.ctx.key(text, keysym, mods)+ self.render()++ def click_header(self, frac):+ x, y, w, h = self.list.rect+ px, py = x + int(w * frac), y + 4+ self.ctx.motion(px, py, 0)+ self.ctx.press(px, py, 0)+ self.ctx.release(px, py, 0)+ self.render()+++def test_listing_and_sort():+ b = Browser(dir=ROOT)+ assert b.node.get_str("dir") == ROOT + os.sep+ assert b.node.get("count") == 6 # "..", 2 folders, 3 files (.hidden not shown)+ b.click_header(0.95) # Size column: largest first, folders still on top+ assert b.node.get("sort") == 2+ b.key("End")+ assert b.node.get_str("file") == "b_small.txt"+ b.click_header(0.05) # back to Name+ assert b.node.get("sort") == 0 and not b.node.get("invert")+ b.key("End")+ assert b.node.get_str("file") == "c_mid.blend"+++def test_hidden_search_filters():+ b = Browser(dir=ROOT)+ b.key("h", CTRL)+ assert b.node.get("count") == 7 and b.node.get("hidden") == 1+ b.key("h", CTRL)+ b.node.set("search", "MID") # case-insensitive "*mid*"+ assert b.node.get("count") == 2 # ".." + c_mid.blend+ b.node.set("search", "")+ b.node.set("filters", ["Python\t.py", "Text\t*.txt *.blend", "All\t*"])+ assert b.node.get("count") == 4 # "..", folders, a_big.py+ b.node.set("filter", 1)+ assert b.node.get("count") == 5+++def test_navigation_history():+ b = Browser(dir=ROOT)+ b.key("Home")+ b.key("Down") # Projects+ b.key("Return")+ assert b.node.get_str("dir").endswith("Projects" + os.sep)+ b.key("BackSpace")+ assert b.node.get_str("dir") == ROOT + os.sep+ b.key("Left", 4) # Alt+Left: back into Projects+ assert b.node.get_str("dir").endswith("Projects" + os.sep)+ b.key("Right", 4)+ assert b.node.get_str("dir") == ROOT + os.sep+++def test_open_save_directory_cancel():+ b = Browser(dir=ROOT)+ b.node.set("file", "a_big.py")+ b.node.set("execute", 1)+ assert b.node.get("state") == 1+ assert b.node.get_str("path") == os.path.join(ROOT, "a_big.py")++ b = Browser(dir=ROOT, multiple=1)+ b.key("End")+ b.key("Up", 1) # Shift: extend+ b.key("Return")+ assert sorted(os.path.basename(p) for p in b.node.strs("result")) == ["b_small.txt",+ "c_mid.blend"]++ b = Browser(mode=1, dir=ROOT, file="a_big.py")+ exec_button = [c for c in b.node.children if c.type == "button"][-1]+ assert exec_button.get_str("text") == "Overwrite"+ b.node.set("file", "new.txt")+ assert exec_button.get_str("text") == "Save"++ b = Browser(mode=2, dir=ROOT)+ assert b.node.get("count") == 3 # folders only+ b.node.set("execute", 1)+ assert b.node.get_str("path") == ROOT++ b = Browser(dir=ROOT)+ b.key("Escape")+ assert b.node.get("state") == -1 and b.node.strs("result") == []+++def test_typed_paths():+ b = Browser(dir=ROOT)+ b.node.set("file", "")+ fname = [c for c in b.node.children if c.type == "text"][-1]+ fname.set("set_value", os.path.join(ROOT, "Projects")) # an absolute folder: go there+ assert b.node.get_str("dir") == os.path.join(ROOT, "Projects") + os.sep+ fname.set("set_value", "..") # relative to the current folder+ assert b.node.get_str("dir") == ROOT + os.sep+ b.node.set("file", os.path.join(ROOT, "renders", "out.png")) # a path moves the folder+ assert b.node.get_str("dir") == os.path.join(ROOT, "renders") + os.sep+ assert b.node.get_str("file") == "out.png"+++def test_new_folder_rename_bookmarks():+ b = Browser(dir=ROOT)+ b.key("i")+ for ch in "made":+ b.ctx.key(ch, ch, 0)+ b.ctx.key("", "Return", 0)+ assert os.path.isdir(os.path.join(ROOT, "made"))+ os.rmdir(os.path.join(ROOT, "made"))+ b.key("b", CTRL) # bookmark the folder+ with open(os.environ["BUI_BOOKMARKS"]) as fh:+ assert ROOT + os.sep in fh.read().split("\n")+ b.node.set("file", "a_big.py")+ b.node.set("execute", 1) # chosen folders go to Recent+ with open(os.environ["BUI_BOOKMARKS"]) as fh:+ text = fh.read()+ assert text.index("[Recent]") < text.rindex(ROOT + os.sep)+++def test_filter_helpers():+ assert filebrowser.tk_filters([("Images", ("*.png", "*.jpg")), ("Text", ".txt")]) == [+ "Images\t*.png *.jpg", "Text\t.txt"]+ assert filebrowser.qt_filters("Images (*.png *.jpg);;All (*)") == ["Images\t*.png *.jpg",+ "All\t*"]+++def main():+ setup_tree()+ try:+ for name, fn in list(globals().items()):+ if name.startswith("test_"):+ fn()+ print("ok", name)+ finally:+ shutil.rmtree(TMP, ignore_errors=True)+++if __name__ == "__main__":+ main()diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txtindex 004806a..3df5c91 100644--- a/kit/CMakeLists.txt+++ b/kit/CMakeLists.txt@@ -20,6 +20,14 @@ add_library(bui_kit STATICintern/kit_icons_svg.cintern/kit_regions.cintern/kit_nodes.c+ intern/kit_filebrowser.c+ intern/kit_filebrowser_paths.c+ intern/kit_filebrowser_posix.c+ intern/kit_filebrowser_win32.c+ intern/kit_filelist.c+ intern/kit_filelist_view.c+ intern/kit_fileops.c+ intern/kit_fsmenu.cextern/nanosvg/blender_nanosvg.cextern/nanosvg/blender_raster.c)diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.hindex a5d08d0..1629c81 100644--- a/kit/include/BUI_kit.h+++ b/kit/include/BUI_kit.h@@ -399,6 +399,36 @@ void BK_window_set_keep_alive(int on);/* Evaluate Blender-style number input ("2*pi", "1/3 + 2^2"). */int BK_eval_number(const char *expr, double *r_value);+/* -- file browser (Blender's File Browser, editors/space_file) -------------------------------+ * BK_node_new("filebrowser") is the whole browser: bookmark panels (Volumes, System,+ * Bookmarks, Recent), the directory-path bar, the file list (Name / Date Modified / Size,+ * click a header to sort) and the execute bar. Put it in any window; it fills its rect.+ * strings "dir", "file" (a name, or a path whose folder becomes "dir"), "button" (execute+ * label), "search", "bookmarks_file" (default $XDG_CONFIG_HOME/bui/bookmarks.txt,+ * %APPDATA%\bui\bookmarks.txt, or $BUI_BOOKMARKS); get "path" (first result)+ * numbers "mode" (0 open, 1 save, 2 directory), "multiple", "hidden", "filter" (index),+ * "sort" (0 name, 1 date, 2 size), "invert"; get "state" (0 browsing, 1 chosen,+ * -1 cancelled), "count", "selected"; set "execute", "cancel", "refresh" to act+ * lists "filters": one "Label\tpattern pattern ..." per entry ("*.py", or ".py");+ * get "result": the chosen paths+ * events BK_EV_SUBMIT (a = state) when chosen or cancelled, BK_EV_CHANGE on a folder change+ * Keys: Return opens / executes, BackSpace or Alt+Up parent, Alt+Left / Alt+Right history,+ * Ctrl+H hidden files, Ctrl+B bookmark the folder, Delete on a bookmark removes it, I new+ * folder, F2 rename, R refresh, A / Alt+A (de)select all with "multiple", Escape cancels.+ *+ * BK_file_dialog runs one in its own native window until it is answered: returns the number+ * of chosen paths (0 cancelled, -1 no window host), stored NULL-terminated in *r_paths+ * (free with BK_file_dialog_free). `filters` as above. */+int BK_file_dialog(const char *title,+ int mode,+ const char *dir,+ const char *file,+ const char *const *filters,+ int nfilters,+ int multiple,+ char ***r_paths);+void BK_file_dialog_free(char **paths);+#ifdef __cplusplus}#endifdiff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.cindex b14b7d8..26d101d 100644--- a/kit/intern/kit_core.c+++ b/kit/intern/kit_core.c@@ -153,6 +153,7 @@ static const BKClass *const g_classes[] = {&bk_cls_gridview, &bk_cls_ramp, &bk_cls_curve, &bk_cls_normal,&bk_cls_histogram, &bk_cls_frame, &bk_cls_radio, &bk_cls_canvas,&bk_cls_textarea, &bk_cls_image, &bk_cls_meter,+ &bk_cls_filebrowser,};const BKClass *bk_class_find(const char *name)@@ -766,6 +767,7 @@ static const struct {{"viewevents", NF_VIEWEVENTS, false}, {"noscrollbar", NF_NOSCROLLBAR, true},{"opaque", NF_OPAQUE, false},{"html", NF_HTML, true}, /* Chrome's form-control look (kit_widgets.c) */+ {"active_default", NF_ACTIVE_DEFAULT, false},};static int g_view_watchers; /* > 0 once any node asked for view events */@@ -1133,6 +1135,9 @@ static void edit_follow_text(BKNode *n)int BK_set_str(BKNode *n, const char *key, const char *v){+ if (n->cls->set_str && n->cls->set_str(n, key, v)) {+ return 1;+ }if (strcmp(key, "text") == 0 || strcmp(key, "title") == 0) {bk_set_text(&n->text, v);bk_relayout(n);@@ -1213,6 +1218,12 @@ int BK_set_str(BKNode *n, const char *key, const char *v)const char *BK_get_str(BKNode *n, const char *key){+ if (n->cls->get_str) {+ const char *s = n->cls->get_str(n, key);+ if (s) {+ return s;+ }+ }if (strcmp(key, "value") == 0 && n->cls == &bk_cls_textarea) {return bk_textarea_text(n);}@@ -1283,6 +1294,9 @@ int BK_get_color(BKNode *n, const char *key, float r[4])int BK_set_strs(BKNode *n, const char *key, const char *const *v, int count){+ if (n->cls->set_strs && n->cls->set_strs(n, key, v, count)) {+ return 1;+ }if (strcmp(key, "headers") == 0) { /* tree/table column headers */bk_strs_set(&n->shortcuts, v, count);bk_relayout(n);@@ -1323,11 +1337,19 @@ int BK_set_strs(BKNode *n, const char *key, const char *const *v, int count)int BK_strs_count(BKNode *n, const char *key){+ const BKStrs *own = n->cls->get_strs ? n->cls->get_strs(n, key) : NULL;+ if (own) {+ return own->n;+ }return strcmp(key, "items") == 0 ? n->items.n : 0;}const char *BK_strs_get(BKNode *n, const char *key, int i){+ const BKStrs *own = n->cls->get_strs ? n->cls->get_strs(n, key) : NULL;+ if (own) {+ return (i >= 0 && i < own->n) ? own->v[i] : "";+ }if (strcmp(key, "items") == 0 && i >= 0 && i < n->items.n) {return n->items.v[i];}@@ -1893,17 +1915,18 @@ static void draw_tooltip(BKContext *ctx)* lerps from V2D_SCROLL_MIN_WIDTH (5 px * scale + 2 * pixelsize) to V2D_SCROLL_WIDTH* (0.45 * widget_unit + 2 * pixelsize) by alpha_vert, padded 0.1 units from the region edge; the* thumb is at least V2D_SCROLL_THUMB_SIZE_MIN (30 px * scale). */-static void region_scroll_rects(BKContext *ctx, BKRect *r_track, BKRect *r_thumb)+void bk_scroller_rects(const BKRect *area, int scroll, int content_h, int alpha, BKRect *r_track,+ BKRect *r_thumb){- const int top = ctx->header_h, view_h = ctx->win_h - top;+ const int top = area->ymin, view_h = bk_rh(area);const float min_w = 5.0f * bk_scale_fac + 2.0f * bk_px();const float max_w = 0.45f * bk_unit() + 2.0f * bk_px();- const int sw = (int)((max_w - min_w) * (ctx->scroll_alpha / 255.0f) + min_w);- const int xmax = ctx->win_w - (int)(0.1f * bk_unit());+ const int sw = (int)((max_w - min_w) * (alpha / 255.0f) + min_w);+ const int xmax = area->xmax - (int)(0.1f * bk_unit());*r_track = bk_rect(xmax - sw, top, sw, view_h);const float thumb_min = 30.0f * bk_scale_fac;- float t0 = top + (float)view_h * ctx->scroll / ctx->content_h;- float t1 = top + (float)view_h * (ctx->scroll + view_h) / ctx->content_h;+ float t0 = top + (float)view_h * scroll / content_h;+ float t1 = top + (float)view_h * (scroll + view_h) / content_h;if (t1 - t0 < thumb_min) {t1 = BK_CLAMP(t0 + thumb_min, top + thumb_min, (float)(top + view_h));t0 = BK_CLAMP(t0, (float)top, top + view_h - thumb_min);@@ -1911,6 +1934,23 @@ static void region_scroll_rects(BKContext *ctx, BKRect *r_track, BKRect *r_thumb*r_thumb = bk_rect(r_track->xmin, (int)t0, sw, (int)(t1 - t0));}+/* view2d_scrollers_draw_ex: alpha_fac maps alpha_vert 0..255 to V2D_SCROLL_MIN_ALPHA..1 */+void bk_scroller_draw(const BKRect *track, const BKRect *thumb, int alpha, bool pressed)+{+ const float alpha_fac = (alpha / 255.0f) * (1.0f - 0.4f) + 0.4f;+ BKWCol wc = bk_theme.scroll;+ wc.inner[3] = wc.inner[3] == 0 ? (uchar)(0.25f * alpha) : (uchar)(wc.inner[3] * alpha_fac);+ wc.item[3] = (uchar)(wc.item[3] * alpha_fac);+ wc.outline[3] = 0; /* also disables the emboss, as widget_emboss[3] = 0 does */+ bk_widget_scroll(&wc, track, thumb, pressed);+}++static void region_scroll_rects(BKContext *ctx, BKRect *r_track, BKRect *r_thumb)+{+ const BKRect area = bk_rect(0, ctx->header_h, ctx->win_w, ctx->win_h - ctx->header_h);+ bk_scroller_rects(&area, ctx->scroll, ctx->content_h, ctx->scroll_alpha, r_track, r_thumb);+}+/* screen_ops.cc area_azone (AZ_SCROLL_VERT): alpha_vert = 1 - distance in x from the scroller /* V2D_SCROLL_HIDE_HEIGHT (HEADERY * scale); 255 while over it. Dirties it when it changes. */static int region_scroll_update_alpha(BKContext *ctx, int x, int y)@@ -1956,14 +1996,7 @@ static void draw_region(BKContext *ctx, const BKRect *rect)if (ctx->content_h > view_h) { /* region scrollbar */BKRect track, thumb;region_scroll_rects(ctx, &track, &thumb);- /* view2d_scrollers_draw_ex: alpha_fac maps alpha_vert 0..255 to V2D_SCROLL_MIN_ALPHA..1 */- const float a = ctx->scroll_alpha / 255.0f, alpha_fac = a * (1.0f - 0.4f) + 0.4f;- BKWCol wc = bk_theme.scroll;- wc.inner[3] = wc.inner[3] == 0 ? (uchar)(0.25f * ctx->scroll_alpha) :- (uchar)(wc.inner[3] * alpha_fac);- wc.item[3] = (uchar)(wc.item[3] * alpha_fac);- wc.outline[3] = 0; /* also disables the emboss, as widget_emboss[3] = 0 does */- bk_widget_scroll(&wc, &track, &thumb, false);+ bk_scroller_draw(&track, &thumb, ctx->scroll_alpha, false);}for (int i = 0; i < ctx->npopups; i++) {bk_draw_tree(ctx->popups[i]);diff --git a/kit/intern/kit_draw.c b/kit/intern/kit_draw.cindex f05699d..c393283 100644--- a/kit/intern/kit_draw.c+++ b/kit/intern/kit_draw.c@@ -61,6 +61,10 @@ BKTheme bk_theme = {0.2f, /* menu_shadow_fac */6, /* menu_shadow_width */0.4f, /* panel_roundness */+ RGBA(0x282828ffu), /* space_file.back */+ RGBA(0xe6e6e6ffu), /* space_file.text */+ RGBA(0x303030b3u), /* space_file.header */+ RGBA(0xffffff04u), /* space_file.row_alternate */};float bk_scale_fac = 1.0f;@@ -1536,13 +1540,17 @@ void bk_icon(int icon, float cx, float cy, const uchar *color, float alpha, floavoid bk_tria(float cx, float cy, char dir, const float c[4], float size){- /* draw_icon_tri(): 'h' right, 'v' down */+ /* draw_icon_tri(): 'h' right, 'v' down, 't' up */const float s = size > 0 ? size : 0.18f * bk_unit();float p[3][2];if (dir == 'h') {const float q[3][2] = {{cx - s * 0.5f, cy - s}, {cx - s * 0.5f, cy + s}, {cx + s * 0.7f, cy}};memcpy(p, q, sizeof(p));}+ else if (dir == 't') {+ const float q[3][2] = {{cx - s, cy + s * 0.5f}, {cx + s, cy + s * 0.5f}, {cx, cy - s * 0.7f}};+ memcpy(p, q, sizeof(p));+ }else {const float q[3][2] = {{cx - s, cy - s * 0.5f}, {cx + s, cy - s * 0.5f}, {cx, cy + s * 0.7f}};memcpy(p, q, sizeof(p));@@ -1550,6 +1558,22 @@ void bk_tria(float cx, float cy, char dir, const float c[4], float size)BUI_raster_polygon(bk_draw.r, (const float(*)[2])p, 3, c);}+void bk_color_over(const uchar c[4], const uchar back[4], uchar r_out[4])+{+ for (int k = 0; k < 3; k++) {+ r_out[k] = (uchar)(back[k] + ((int)c[k] - back[k]) * c[3] / 255.0f + 0.5f);+ }+ r_out[3] = 255;+}++void bk_color_shade(const uchar c[4], int shade, uchar r_out[4])+{+ for (int k = 0; k < 3; k++) {+ r_out[k] = (uchar)BK_CLAMP((int)c[k] + shade, 0, 255);+ }+ r_out[3] = c[3];+}+void bk_chevron_down(float cx, float cy, const uchar col[4]){float c[4];diff --git a/kit/intern/kit_filebrowser.c b/kit/intern/kit_filebrowser.cnew file mode 100644index 0000000..9e6d490--- /dev/null+++ b/kit/intern/kit_filebrowser.c@@ -0,0 +1,752 @@+/* File browser: Blender's File Browser (editors/space_file) as a kit composite.+ *+ * A "filebrowser" node lays its parts out like Blender's file browser area:+ * - the tools region on the left: Volumes / System / Bookmarks / Recent (kit_fsmenu.c),+ * - the directory-path region at the top: back, forward, parent, refresh, new folder, the path+ * field, search and the hidden-files toggle (bl_ui FILEBROWSER_PT_directory_path),+ * - the main region: the file list (kit_filelist_view.c),+ * - the execute region at the bottom: file name, file-type filter, Cancel and the execute+ * button (file_panels.cc file_panel_execution_buttons_draw).+ * This file builds the node, lays it out, maps keys and properties, and runs the blocking+ * dialog; kit_filebrowser_intern.h lists the other parts.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "kit_filebrowser_intern.h"++static int u(void)+{+ return bk_unit();+}++/* -------------------------------------------------------------------- */+/** \name Keymap (the file browser keymap; also reached from the list)+ * \{ */++typedef void (*FBAction)(FBData *f, int mods);++static void act_cancel(FBData *f, int mods)+{+ (void)mods;+ fb_finish(f, FB_STATE_CANCELLED);+}++static void act_parent(FBData *f, int mods)+{+ (void)mods;+ fb_go_parent(f);+}++static void act_back(FBData *f, int mods)+{+ (void)mods;+ fb_go_back(f);+}++static void act_forward(FBData *f, int mods)+{+ (void)mods;+ fb_go_forward(f);+}++static void act_hidden(FBData *f, int mods)+{+ (void)mods;+ f->b_hidden->value = !fb_show_hidden(f);+ bk_invalidate(f->b_hidden);+ fb_filter_sort(f);+}++static void act_bookmark(FBData *f, int mods)+{+ (void)mods;+ fb_bookmark_dir(f);+}++static void act_refresh(FBData *f, int mods)+{+ (void)mods;+ fb_refresh(f);+}++static void act_new_folder(FBData *f, int mods)+{+ (void)mods;+ fb_new_folder(f);+}++static void act_rename(FBData *f, int mods)+{+ (void)mods;+ fb_rename_begin(f, f->active);+}++static void act_activate(FBData *f, int mods)+{+ (void)mods;+ fb_activate(f);+}++static int active_or_first(const FBData *f)+{+ return f->active < 0 ? 0 : f->active;+}++static void act_up(FBData *f, int mods)+{+ fb_walk(f, f->active < 0 ? 0 : f->active - 1, mods);+}++static void act_down(FBData *f, int mods)+{+ fb_walk(f, f->active < 0 ? 0 : f->active + 1, mods);+}++static void act_home(FBData *f, int mods)+{+ fb_walk(f, 0, mods);+}++static void act_end(FBData *f, int mods)+{+ fb_walk(f, f->nvis - 1, mods);+}++static int page_rows(const FBData *f)+{+ return BK_MAX(1, fb_list_page_rows(f->list) - 1);+}++static void act_page_up(FBData *f, int mods)+{+ fb_walk(f, active_or_first(f) - page_rows(f), mods);+}++static void act_page_down(FBData *f, int mods)+{+ fb_walk(f, active_or_first(f) + page_rows(f), mods);+}++/* file.select_all: every file (folders too when choosing one), or none. */+static void select_all(FBData *f, bool on)+{+ for (int i = 0; f->multiple && i < f->nvis; i++) {+ FBEntry *v = fb_vis_entry(f, i);+ v->sel = on && v->kind != FB_KIND_PARENT &&+ (f->mode == FB_MODE_DIRECTORY || v->kind == FB_KIND_FILE);+ }+ fb_update_exec(f);+ bk_invalidate(f->list);+}++static void act_select_all(FBData *f, int mods)+{+ (void)mods;+ select_all(f, true);+}++static void act_deselect_all(FBData *f, int mods)+{+ (void)mods;+ select_all(f, false);+}++/* Matched on Ctrl and Alt exactly; Shift passes through (it extends walks). */+static const struct {+ const char *keysym;+ int mods;+ FBAction fn;+} g_keymap[] = {+ {"Escape", 0, act_cancel}, {"BackSpace", 0, act_parent},+ {"Up", BK_ALT, act_parent}, {"Left", BK_ALT, act_back},+ {"Right", BK_ALT, act_forward}, {"h", BK_CTRL, act_hidden},+ {"b", BK_CTRL, act_bookmark}, {"r", 0, act_refresh},+ {"i", 0, act_new_folder}, {"F2", 0, act_rename},+ {"Return", BK_CTRL, act_rename}, {"Return", 0, act_activate},+ {"KP_Enter", 0, act_activate}, {"Up", 0, act_up},+ {"Down", 0, act_down}, {"Home", 0, act_home},+ {"End", 0, act_end}, {"Prior", 0, act_page_up},+ {"Next", 0, act_page_down}, {"a", 0, act_select_all},+ {"a", BK_ALT, act_deselect_all},+};++int fb_keymap(FBData *f, const BKEvent *e)+{+ const int mods = e->mods & (BK_CTRL | BK_ALT);+ for (size_t i = 0; i < sizeof(g_keymap) / sizeof(g_keymap[0]); i++) {+ if (mods == g_keymap[i].mods && bk_keysym_is(e->keysym, g_keymap[i].keysym)) {+ g_keymap[i].fn(f, e->mods);+ return 1;+ }+ }+ return 0;+}++static int fb_key(BKNode *n, BKEvent *e)+{+ return fb_keymap(FB(n), e);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Parts and their callbacks+ * \{ */++static void on_prev(BKNode *b, void *data)+{+ (void)b;+ fb_go_back((FBData *)data);+}++static void on_next(BKNode *b, void *data)+{+ (void)b;+ fb_go_forward((FBData *)data);+}++static void on_parent(BKNode *b, void *data)+{+ (void)b;+ fb_go_parent((FBData *)data);+}++static void on_refresh(BKNode *b, void *data)+{+ (void)b;+ fb_refresh((FBData *)data);+}++static void on_newdir(BKNode *b, void *data)+{+ (void)b;+ fb_new_folder((FBData *)data);+}++static void on_path(BKNode *n, void *data)+{+ fb_navigate((FBData *)data, n->text, true); /* file_directory_enter_handle */+}++static void on_search(BKNode *n, void *data)+{+ FBData *f = (FBData *)data;+ snprintf(f->search, sizeof(f->search), "%s", n->text ? n->text : "");+ fb_filter_sort(f);+}++/* The hidden toggle and the filter dropdown hold their settings: re-filter on change. */+static void on_refilter(BKNode *n, void *data)+{+ (void)n;+ fb_filter_sort((FBData *)data);+}++/* file_filename_enter_handle: a folder name (or path) goes there. */+static void on_fname(BKNode *n, void *data)+{+ FBData *f = (FBData *)data;+ char p[FB_PATH];+ if (n->text && n->text[0]) {+ fb_path_resolve(f->dir, n->text, p, sizeof(p));+ if (fb_path_is_dir(p)) {+ bk_set_text(&n->text, "");+ fb_navigate(f, p, true);+ return;+ }+ }+ fb_update_exec(f);+}++static void on_cancel(BKNode *b, void *data)+{+ (void)b;+ fb_finish((FBData *)data, FB_STATE_CANCELLED); /* file.cancel */+}++static void on_exec(BKNode *b, void *data)+{+ (void)b;+ fb_execute((FBData *)data);+}++static BKNode *part(BKNode *parent, const BKClass *cls)+{+ BKNode *c = bk_node_new_cls(cls);+ bk_node_add(parent, c);+ return c;+}++static BKNode *button(FBData *f, const char *icon, const char *text, const char *tip,+ void (*cb)(BKNode *, void *))+{+ BKNode *b = part(f->self, &bk_cls_button);+ b->icon = icon ? bk_icons_lookup(icon) : 0;+ bk_set_text(&b->text, text);+ bk_set_text(&b->desc, tip);+ b->on_click = cb;+ b->on_click_data = f;+ return b;+}++static BKNode *field(FBData *f, const BKClass *cls, const char *tip,+ void (*cb)(BKNode *, void *))+{+ BKNode *t = part(f->self, cls);+ bk_set_text(&t->desc, tip);+ t->on_change = cb;+ t->on_change_data = f;+ return t;+}++static void build_header(FBData *f)+{+ f->b_prev = button(f, "BACK", NULL, "Move to previous folder", on_prev);+ f->b_next = button(f, "FORWARD", NULL, "Move to next folder", on_next);+ f->b_parent = button(f, "FILE_PARENT", NULL, "Move to parent directory", on_parent);+ f->b_refresh = button(f, "FILE_REFRESH", NULL, "Refresh the file list", on_refresh);+ f->b_newdir = button(f, "NEWFOLDER", NULL, "Create a new folder", on_newdir);+ f->path = field(f, &bk_cls_text, "Directory path", on_path);+ f->search_f = field(f, &bk_cls_search, NULL, on_search);+ bk_set_text(&f->search_f->placeholder, "Filter");+ f->search_f->flags |= NF_LIVE;+ f->b_hidden = field(f, &bk_cls_toggle, "Show hidden dot files (Ctrl+H)", on_refilter);+ f->b_hidden->icon = bk_icons_lookup("HIDE_ON");+ f->b_hidden->icon_on = bk_icons_lookup("HIDE_OFF");+}++static void build_side(FBData *f)+{+ static const char *const titles[FB_CAT_NUM] = {"Volumes", "System", "Bookmarks", "Recent"};+ f->side = part(f->self, &bk_cls_column);+ f->side->padding = (int)(FB_MARGIN * u());+ f->side->spacing = (int)(0.2f * u());+ for (int c = 0; c < FB_CAT_NUM; c++) {+ f->panels[c] = part(f->side, &bk_cls_panel);+ bk_set_text(&f->panels[c]->text, titles[c]);+ f->lists[c] = fb_places_view_new(f, (FBCategory)c, (BKNode *)f->panels[c]->ext); /* body */+ }+}++static void build_exec(FBData *f)+{+ f->fname = field(f, &bk_cls_text, "File name", on_fname);+ f->filter_dd = field(f, &bk_cls_dropdown, NULL, on_refilter);+ f->b_cancel = button(f, NULL, "Cancel", NULL, on_cancel);+ f->b_exec = button(f, NULL, NULL, NULL, on_exec);+ f->b_exec->flags |= NF_ACTIVE_DEFAULT; /* row.active_default_set(true) */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Layout and drawing+ * \{ */++/* Show or hide a part from arrange (no relayout request, unlike the "visible" property). */+static void arrange_shown(BKNode *c, bool on, int x, int y, int w, int h)+{+ c->flags = on ? (c->flags | NF_VISIBLE) : (c->flags & ~NF_VISIBLE);+ bk_arrange(c, x, y, on ? w : 0, on ? h : 0);+}++static int natural_w(BKNode *c, int min)+{+ int w, h;+ bk_natural(c, &w, &h);+ return BK_MAX(w, min);+}++/* An aligned row (UI_block_align_begin): rounded only at the ends. Returns the end x. */+static int arrange_aligned(BKNode *const *row, int nrow, int x, int y, int size)+{+ for (int i = 0; i < nrow; i++) {+ row[i]->corners = nrow == 1 ? CNR_ALL :+ i == 0 ? (CNR_TL | CNR_BL) :+ i == nrow - 1 ? (CNR_TR | CNR_BR) :+ 0;+ bk_arrange(row[i], x + i * size, y, size, size);+ }+ return x + nrow * size;+}++static int bar_h(void)+{+ return bk_iround(FB_BAR_SCALE * u()) + 2 * (int)(FB_MARGIN * u());+}++/* FILEBROWSER_PT_directory_path */+static void arrange_header(FBData *f, int x, int y, int w)+{+ const int sp = (int)(FB_SPACE * u()), margin = (int)(FB_MARGIN * u());+ const int bh = bk_iround(FB_BAR_SCALE * u()), by = y + margin;+ const int search_w = BK_MIN(FB_SEARCH_MAX_W * u(), BK_MAX(FB_SEARCH_MIN_W * u(), w / 5));+ int left = x + margin, right = x + w - margin - bh;+ f->r_header = bk_rect(x, y, w, bar_h());+ left = arrange_aligned((BKNode *[]){f->b_prev, f->b_next, f->b_parent, f->b_refresh}, 4,+ left, by, bh) + sp;+ left = arrange_aligned(&f->b_newdir, 1, left, by, bh) + sp;+ arrange_aligned(&f->b_hidden, 1, right, by, bh);+ right -= sp + search_w;+ bk_arrange(f->search_f, right, by, search_w, bh);+ bk_arrange(f->path, left, by, BK_MAX(2 * u(), right - sp - left), bh);+}++/* file_panel_execution_buttons_draw: Cancel then execute (Windows: swapped). */+static void arrange_exec(FBData *f, int x, int y, int w)+{+ const int sp = (int)(FB_SPACE * u()), margin = (int)(FB_MARGIN * u());+ const int bh = bk_iround(FB_BAR_SCALE * u()), by = y + margin;+ const int exec_w = natural_w(f->b_exec, FB_BUTTON_MIN_W * u());+ const int cancel_w = natural_w(f->b_cancel, FB_BUTTON_MIN_W * u());+ const bool windows = fb_os_sep() == '\\';+ BKNode *first = windows ? f->b_cancel : f->b_exec, *second = windows ? f->b_exec : f->b_cancel;+ int right = x + w - margin - (windows ? cancel_w : exec_w);+ f->r_exec = bk_rect(x, y, w, bar_h());+ bk_arrange(first, right, by, windows ? cancel_w : exec_w, bh);+ right -= sp + (windows ? exec_w : cancel_w);+ bk_arrange(second, right, by, windows ? exec_w : cancel_w, bh);+ const int dw = BK_MIN(natural_w(f->filter_dd, FB_FILTER_MIN_W * u()),+ BK_MAX(FB_FILTER_MIN_W * u(), w / 3));+ right -= f->nfilters > 0 ? sp + dw : 0;+ arrange_shown(f->filter_dd, f->nfilters > 0, right, by, dw, bh);+ arrange_shown(f->fname, f->mode != FB_MODE_DIRECTORY, x + margin, by,+ BK_MAX(2 * u(), right - sp - x - margin), bh);+}++static void fb_arrange(BKNode *n)+{+ FBData *f = FB(n);+ const int side_w = n->w >= FB_SIDE_AREA_WIDE * u() ? FB_SIDE_W * u() :+ n->w >= FB_SIDE_AREA_NARROW * u() ? FB_SIDE_W_NARROW * u() :+ 0;+ f->r_side = bk_rect(n->x, n->y, side_w, n->h);+ arrange_shown(f->side, side_w > 0, n->x, n->y, side_w, n->h);+ const int mx = n->x + side_w, mw = n->w - side_w;+ arrange_header(f, mx, n->y, mw);+ arrange_exec(f, mx, n->y + n->h - bar_h(), mw);+ bk_arrange(f->list, mx, n->y + bar_h(), mw, BK_MAX(0, n->h - 2 * bar_h()));+}++/* Region backgrounds: tools (regions.sidebars.back), header and execute (space_file.header over+ * the back color); the main region draws itself. */+static void fb_draw(BKNode *n)+{+ const FBData *f = FB(n);+ uchar header[4];+ bk_color_over(bk_theme.file_header, bk_theme.file_back, header);+ bk_fill(f->r_side.xmin, f->r_side.ymin, bk_rw(&f->r_side), bk_rh(&f->r_side),+ bk_theme.region_bg);+ bk_fill(f->r_header.xmin, f->r_header.ymin, bk_rw(&f->r_header), bk_rh(&f->r_header), header);+ bk_fill(f->r_exec.xmin, f->r_exec.ymin, bk_rw(&f->r_exec), bk_rh(&f->r_exec), header);+}++static void fb_measure(BKNode *n, int *rw, int *rh)+{+ (void)n;+ *rw = FB_NATURAL_W * u();+ *rh = FB_NATURAL_H * u();+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Properties (see BUI_kit.h)+ * \{ */++/* "file": a name, or a path whose folder becomes the directory (Tk's initialfile). */+static void set_file(FBData *f, const char *v)+{+ char t[FB_PATH];+ snprintf(t, sizeof(t), "%s", v ? v : "");+ char *name = t + strlen(t);+ while (name > t && !fb_os_is_sep(name[-1])) {+ name--;+ }+ if (name > t) {+ name[-1] = '\0';+ fb_navigate(f, t[0] ? t : (char[2]){fb_os_sep(), '\0'}, false);+ }+ bk_set_text(&f->fname->text, name);+ bk_invalidate(f->fname);+ fb_update_exec(f);+}++static int fb_set_str(BKNode *n, const char *key, const char *v)+{+ FBData *f = FB(n);+ if (strcmp(key, "dir") == 0 || strcmp(key, "directory") == 0) {+ fb_navigate(f, v, false);+ }+ else if (strcmp(key, "file") == 0 || strcmp(key, "filename") == 0) {+ set_file(f, v);+ }+ else if (strcmp(key, "button") == 0) {+ free(f->exec_label);+ f->exec_label = (v && v[0]) ? bk_strdup(v) : NULL;+ fb_update_exec(f);+ }+ else if (strcmp(key, "search") == 0) {+ bk_set_text(&f->search_f->text, v);+ on_search(f->search_f, f);+ bk_invalidate(f->search_f);+ }+ else if (strcmp(key, "bookmarks_file") == 0) {+ snprintf(f->bookmarks_path, sizeof(f->bookmarks_path), "%s", v ? v : "");+ fb_read_bookmarks(f);+ }+ else {+ return 0;+ }+ bk_relayout(n);+ return 1;+}++static const char *fb_get_str(BKNode *n, const char *key)+{+ FBData *f = FB(n);+ const bool dir = strcmp(key, "dir") == 0 || strcmp(key, "directory") == 0;+ const bool file = strcmp(key, "file") == 0 || strcmp(key, "filename") == 0;+ return dir ? f->dir :+ file ? (f->fname->text ? f->fname->text : "") :+ strcmp(key, "path") == 0 ? (f->result.n ? f->result.v[0] : "") :+ strcmp(key, "search") == 0 ? f->search :+ strcmp(key, "bookmarks_file") == 0 ? f->bookmarks_path :+ NULL;+}++static int fb_set_strs(BKNode *n, const char *key, const char *const *v, int count)+{+ if (strcmp(key, "filters") != 0) {+ return 0;+ }+ fb_filters_set(FB(n), v, count);+ fb_filter_sort(FB(n));+ bk_relayout(n);+ return 1;+}++static const BKStrs *fb_get_strs(BKNode *n, const char *key)+{+ return strcmp(key, "result") == 0 ? &FB(n)->result : NULL;+}++/* Settings that re-filter the list after they change. */+static bool set_listing_num(FBData *f, const char *key, double v)+{+ if (strcmp(key, "hidden") == 0 || strcmp(key, "show_hidden") == 0) {+ f->b_hidden->value = v != 0;+ bk_invalidate(f->b_hidden);+ }+ else if (strcmp(key, "filter") == 0) {+ f->filter_dd->value = BK_CLAMP((int)v, 0, BK_MAX(0, f->nfilters - 1));+ bk_invalidate(f->filter_dd);+ }+ else if (strcmp(key, "sort") == 0) {+ f->sort = (FBSort)BK_CLAMP((int)v, FB_SORT_ALPHA, FB_SORT_SIZE);+ }+ else if (strcmp(key, "invert") == 0) {+ f->invert = v != 0;+ }+ else if (strcmp(key, "mode") == 0) {+ f->mode = (FBMode)BK_CLAMP((int)v, FB_MODE_OPEN, FB_MODE_DIRECTORY);+ fb_update_exec(f);+ bk_relayout(f->self);+ }+ else {+ return false;+ }+ fb_filter_sort(f);+ return true;+}++static int fb_set_num(BKNode *n, const char *key, double v)+{+ FBData *f = FB(n);+ if (set_listing_num(f, key, v)) {+ return 1;+ }+ if (strcmp(key, "multiple") == 0) {+ f->multiple = v != 0;+ }+ else if (strcmp(key, "state") == 0) {+ f->state = v > 0 ? FB_STATE_CHOSEN : (v < 0 ? FB_STATE_CANCELLED : FB_STATE_BROWSING);+ }+ else if (strcmp(key, "refresh") == 0) {+ fb_refresh(f);+ }+ else if (strcmp(key, "execute") == 0) {+ fb_execute(f);+ }+ else if (strcmp(key, "cancel") == 0) {+ fb_finish(f, FB_STATE_CANCELLED);+ }+ else {+ return 0;+ }+ return 1;+}++static int fb_get_num(BKNode *n, const char *key, double *r_v)+{+ const FBData *f = FB(n);+ static const char *const keys[] = {"mode", "multiple", "hidden", "show_hidden", "filter",+ "sort", "invert", "state", "count", "selected",+ "dialog_width", "dialog_height"};+ const double values[] = {f->mode,+ f->multiple,+ fb_show_hidden(f),+ fb_show_hidden(f),+ fb_filter_index(f),+ f->sort,+ f->invert,+ f->state,+ f->nvis, /* listed entries, ".." included */+ fb_count_selected(f, false, NULL),+ FB_DIALOG_W * u(),+ FB_DIALOG_H * u()};+ for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {+ if (strcmp(key, keys[i]) == 0) {+ *r_v = values[i];+ return 1;+ }+ }+ return 0;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name The node+ * \{ */++static void fb_init(BKNode *n)+{+ FBData *f = (FBData *)calloc(1, sizeof(FBData));+ n->ext = f;+ f->self = n;+ f->active = f->anchor = -1;+ build_header(f);+ build_side(f);+ f->list = part(n, &bk_cls_fb_list);+ f->list->ext = f;+ f->list->hot = f->list->rename_row = -1;+ build_exec(f);+ fb_places_read(f);+ fb_navigate(f, ".", false);+}++static void fb_free(BKNode *n)+{+ FBData *f = FB(n);+ fb_entries_free(f);+ free(f->all);+ fb_places_free(f);+ fb_filters_free(f);+ fb_history_free(f);+ bk_strs_free(&f->result);+ free(f->exec_label);+ free(f);+ n->ext = NULL;+}++const BKClass bk_cls_filebrowser = {.name = "filebrowser",+ .flags = CLS_INTERACTIVE,+ .init = fb_init,+ .free_ext = fb_free,+ .measure = fb_measure,+ .arrange = fb_arrange,+ .draw = fb_draw,+ .key = fb_key,+ .set_num = fb_set_num,+ .get_num = fb_get_num,+ .set_str = fb_set_str,+ .get_str = fb_get_str,+ .set_strs = fb_set_strs,+ .get_strs = fb_get_strs};++/** \} */++/* -------------------------------------------------------------------- */+/** \name Blocking dialog in a native window (WM_event_add_fileselect, as a temp window)+ * \{ */++static BKNode *dialog_node(int mode, const char *dir, const char *file,+ const char *const *filters, int nfilters, int multiple)+{+ BKNode *fb = BK_node_new("filebrowser");+ BK_set_num(fb, "mode", mode);+ BK_set_num(fb, "multiple", multiple);+ if (nfilters > 0) {+ BK_set_strs(fb, "filters", filters, nfilters);+ }+ if (dir && dir[0]) {+ BK_set_str(fb, "dir", dir);+ }+ if (file && file[0]) {+ BK_set_str(fb, "file", file);+ }+ return fb;+}++static int dialog_result(BKNode *fb, char ***r_paths)+{+ const int count = BK_get_num(fb, "state") > 0 ? BK_strs_count(fb, "result") : 0;+ *r_paths = count > 0 ? (char **)calloc((size_t)count + 1, sizeof(char *)) : NULL;+ for (int i = 0; i < count; i++) {+ (*r_paths)[i] = bk_strdup(BK_strs_get(fb, "result", i));+ }+ return count;+}++int BK_file_dialog(const char *title,+ int mode,+ const char *dir,+ const char *file,+ const char *const *filters,+ int nfilters,+ int multiple,+ char ***r_paths)+{+ static const char *const titles[] = {"Open", "Save As", "Select Folder"};+ *r_paths = NULL;+ if (!BK_window_supported()) {+ return -1;+ }+ BKNode *fb = dialog_node(mode, dir, file, filters, nfilters, multiple);+ BKContext *ctx = BK_context_new(fb);+ BKWindow *win = BK_window_new(ctx, title && title[0] ? title : titles[FB(fb)->mode],+ (int)BK_get_num(fb, "dialog_width"),+ (int)BK_get_num(fb, "dialog_height"));+ int count = -1;+ if (win) {+ BK_window_show(win);+ while (BK_window_is_open(win) && FB(fb)->state == FB_STATE_BROWSING && BK_window_pump()) {+ if (!BK_needs_render(ctx)) {+ fb_os_sleep_ms(4);+ }+ }+ count = dialog_result(fb, r_paths);+ if (BK_window_is_open(win)) {+ BK_window_close(win);+ }+ BK_window_free(win);+ }+ BK_context_free(ctx);+ BK_node_free(fb);+ return count;+}++void BK_file_dialog_free(char **paths)+{+ for (char **p = paths; p && *p; p++) {+ free(*p);+ }+ free(paths);+}++/** \} */diff --git a/kit/intern/kit_filebrowser_intern.h b/kit/intern/kit_filebrowser_intern.hnew file mode 100644index 0000000..bd02730--- /dev/null+++ b/kit/intern/kit_filebrowser_intern.h@@ -0,0 +1,226 @@+/* File browser internals: shared types, limits and layout factors.+ *+ * The browser is ported from Blender's editors/space_file; each file names the upstream+ * source it follows:+ * kit_filebrowser.c the composite node, keymap, properties, blocking dialog+ * kit_fileops.c navigation, history, execute, new folder, rename (file_ops.cc)+ * kit_filelist.c entries, icons, sort, filter (filelist/)+ * kit_filelist_view.c the list view (file_draw.cc, filesel.cc)+ * kit_fsmenu.c Volumes / System / Bookmarks / Recent (fsmenu.cc)+ * kit_filebrowser_paths.c path helpers (BLI_path_utils subset)+ * kit_filebrowser_posix.c, kit_filebrowser_win32.c platform parts+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */+#pragma once++#include <stdbool.h>+#include <stddef.h>+#include <time.h>++#include "kit_intern.h"++/* -------------------------------------------------------------------- */+/* Limits and layout (UI units unless noted) */++#define FB_PATH 4096+#define FB_HISTORY 64 /* folder_history.cc depth */+#define FB_RECENT_MAX 10 /* U.recent_dirs */+#define FB_DIALOG_W 50 /* blocking dialog window, units */+#define FB_DIALOG_H 30+#define FB_NATURAL_W 30 /* the node's natural size */+#define FB_NATURAL_H 18+#define FB_SIDE_W 10 /* tools region width from FB_SIDE_AREA_WIDE units of area, */+#define FB_SIDE_W_NARROW 7 /* narrow from FB_SIDE_AREA_NARROW, hidden below */+#define FB_SIDE_AREA_WIDE 24+#define FB_SIDE_AREA_NARROW 14+#define FB_BAR_SCALE 1.3f /* scale_y of the directory-path and execute rows */+#define FB_MARGIN 0.4f /* region margin */+#define FB_SPACE 0.25f /* style->buttonspacex */+#define FB_BUTTON_MIN_W 4 /* Cancel / execute */+#define FB_FILTER_MIN_W 5+#define FB_SEARCH_MIN_W 4+#define FB_SEARCH_MAX_W 8+#define FB_PLACES_PAD 0.2f /* template_list box padding */+#define FB_WHEEL_ROWS 2 /* rows scrolled per wheel step */++/* -------------------------------------------------------------------- */+/* Types */++typedef enum FBMode { FB_MODE_OPEN = 0, FB_MODE_SAVE, FB_MODE_DIRECTORY } FBMode;+typedef enum FBState { FB_STATE_CANCELLED = -1, FB_STATE_BROWSING = 0, FB_STATE_CHOSEN = 1 } FBState;+typedef enum FBKind { FB_KIND_FILE = 0, FB_KIND_DIR, FB_KIND_PARENT } FBKind;+typedef enum FBSort { FB_SORT_ALPHA = 0, FB_SORT_TIME, FB_SORT_SIZE } FBSort;+typedef enum FBColumn { FB_COL_NAME = 0, FB_COL_DATE, FB_COL_SIZE, FB_COL_NUM } FBColumn;+/* FSMenuCategory, in the tools region's panel order */+typedef enum FBCategory {+ FB_CAT_VOLUMES = 0,+ FB_CAT_SYSTEM,+ FB_CAT_BOOKMARKS,+ FB_CAT_RECENT,+ FB_CAT_NUM+} FBCategory;++/* FileDirEntry, reduced to a plain directory listing. */+typedef struct FBEntry {+ char *name;+ FBKind kind;+ bool hidden, link, sel;+ long long size;+ time_t mtime;+ int icon;+ char date[40];+ char size_str[16];+} FBEntry;++/* FSMenuEntry */+typedef struct FBPlace {+ char *path;+ char *label;+ int icon;+} FBPlace;++typedef struct FBFilter {+ char *label;+ char **pats;+ int npats;+} FBFilter;++typedef struct FBData {+ BKNode *self;+ FBMode mode;+ bool multiple;+ FBState state;+ char dir[FB_PATH];+ char *exec_label;+ char error[256];++ /* listing (FileList) */+ FBEntry *all;+ int nall, capall;+ int *vis; /* visible entries: filtered and sorted */+ int nvis;+ int active; /* params->active_file (visible index), -1 none */+ int anchor;+ FBSort sort;+ bool invert;+ char search[256];+ FBFilter *filters; /* the selected one is filter_dd's value */+ int nfilters;+ bool scroller_hot; /* pointer over the list's scroller */++ /* folder_history.cc */+ char *back[FB_HISTORY], *fwd[FB_HISTORY];+ int nback, nfwd;++ /* fsmenu */+ FBPlace *places[FB_CAT_NUM];+ int nplaces[FB_CAT_NUM];+ char bookmarks_path[FB_PATH];++ BKStrs result;++ /* parts; b_hidden's value is the show-hidden setting */+ BKNode *b_prev, *b_next, *b_parent, *b_refresh, *b_newdir, *path, *search_f, *b_hidden;+ BKNode *side, *panels[FB_CAT_NUM], *lists[FB_CAT_NUM];+ BKNode *list;+ BKNode *fname, *filter_dd, *b_cancel, *b_exec;++ /* region rects, screen space */+ BKRect r_side, r_header, r_exec;+} FBData;++/* The browser and its list both keep the FBData in ext. */+#define FB(n) ((FBData *)(n)->ext)++/* -------------------------------------------------------------------- */+/* kit_filebrowser_paths.c */++void fb_path_slash_ensure(char *p, size_t size);+bool fb_path_parent(char *p);+void fb_path_join(char *dst, size_t size, const char *dir, const char *file);+bool fb_path_is_dir(const char *p);+bool fb_path_exists(const char *p);+const char *fb_path_basename(const char *p, char *buf, size_t size);+void fb_path_normalize(char *p, size_t size);+/* A typed name or path: absolute (or "~") as is, else inside dir; normalized. */+void fb_path_resolve(const char *dir, const char *typed, char *out, size_t size);+/* "/a/b/" -> "/a/b" (roots keep their separator). */+void fb_path_strip_slash(char *p);++/* -------------------------------------------------------------------- */+/* kit_filebrowser_posix.c / kit_filebrowser_win32.c */++char fb_os_sep(void);+bool fb_os_is_sep(char c);+size_t fb_os_root_len(const char *p); /* drive prefix ("C:"), 0 on POSIX */+bool fb_os_path_is_absolute(const char *p);+bool fb_os_path_is_root(const char *p);+bool fb_os_getcwd(char *buf, size_t size);+bool fb_os_mkdir(const char *p);+const char *fb_os_home(void);+void fb_os_localtime(time_t t, struct tm *r);+void fb_os_sleep_ms(int ms);+void fb_os_bookmarks_path(char *buf, size_t size);+bool fb_os_read_dir(FBData *f); /* adds entries; false when the folder can't be read */+void fb_os_read_system(FBData *f); /* System and Volumes places */++/* -------------------------------------------------------------------- */+/* kit_filelist.c */++FBEntry *fb_entry_add(FBData *f, const char *name);+void fb_entry_finish(FBEntry *e);+void fb_entries_free(FBData *f);+void fb_read_dir(FBData *f);+void fb_filter_sort(FBData *f);+FBEntry *fb_vis_entry(const FBData *f, int i);+bool fb_show_hidden(const FBData *f);+int fb_filter_index(const FBData *f);+int fb_count_selected(const FBData *f, bool files_only, int *r_last);+void fb_select_none(FBData *f);+void fb_filters_set(FBData *f, const char *const *v, int count);+void fb_filters_free(FBData *f);++/* -------------------------------------------------------------------- */+/* kit_filelist_view.c */++extern const BKClass bk_cls_fb_list;+void fb_list_see(BKNode *list, int i);+int fb_list_page_rows(const BKNode *list);+void fb_click_select(FBData *f, int i, int mods);+void fb_walk(FBData *f, int to, int mods);+void fb_rename_begin(FBData *f, int i);++/* -------------------------------------------------------------------- */+/* kit_fsmenu.c */++BKNode *fb_places_view_new(FBData *f, FBCategory cat, BKNode *parent);+void fb_places_read(FBData *f); /* system places, then bookmarks.txt */+void fb_place_add(FBData *f, FBCategory cat, const char *path, const char *label,+ const char *icon, bool sorted);+void fb_places_free(FBData *f);+void fb_read_bookmarks(FBData *f);+void fb_write_bookmarks(FBData *f);+void fb_add_recent(FBData *f, const char *dir);+void fb_bookmark_dir(FBData *f);++/* -------------------------------------------------------------------- */+/* kit_filebrowser.c */++int fb_keymap(FBData *f, const BKEvent *e); /* the browser's keymap; 1 when handled */++/* -------------------------------------------------------------------- */+/* kit_fileops.c */++void fb_navigate(FBData *f, const char *dir, bool history);+void fb_go_back(FBData *f);+void fb_go_forward(FBData *f);+void fb_go_parent(FBData *f);+void fb_refresh(FBData *f);+void fb_new_folder(FBData *f);+bool fb_rename(FBData *f, int i, const char *name);+void fb_open_entry(FBData *f, int i);+void fb_activate(FBData *f);+void fb_execute(FBData *f);+void fb_finish(FBData *f, FBState state);+void fb_update_exec(FBData *f);+void fb_history_free(FBData *f);diff --git a/kit/intern/kit_filebrowser_paths.c b/kit/intern/kit_filebrowser_paths.cnew file mode 100644index 0000000..ade1ccb--- /dev/null+++ b/kit/intern/kit_filebrowser_paths.c@@ -0,0 +1,152 @@+/* File browser paths: the BLI_path_utils subset the browser needs. Platform rules (separators,+ * drive prefixes, the working folder) come from kit_filebrowser_posix.c / _win32.c.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>+#include <string.h>+#include <sys/stat.h>++#include "kit_filebrowser_intern.h"++/* BLI_path_slash_ensure */+void fb_path_slash_ensure(char *p, size_t size)+{+ const size_t len = strlen(p);+ if ((len == 0 || !fb_os_is_sep(p[len - 1])) && len + 1 < size) {+ p[len] = fb_os_sep();+ p[len + 1] = '\0';+ }+}++void fb_path_strip_slash(char *p)+{+ size_t len = strlen(p);+ while (len > 1 && fb_os_is_sep(p[len - 1]) && !fb_os_path_is_root(p)) {+ p[--len] = '\0';+ }+}++/* BLI_path_parent_dir: "/a/b/" -> "/a/" */+bool fb_path_parent(char *p)+{+ if (fb_os_path_is_root(p)) {+ return false;+ }+ size_t len = strlen(p);+ while (len > 0 && fb_os_is_sep(p[len - 1])) {+ len--;+ }+ while (len > 0 && !fb_os_is_sep(p[len - 1])) {+ len--;+ }+ if (len == 0) {+ return false;+ }+ p[len] = '\0';+ return true;+}++void fb_path_join(char *dst, size_t size, const char *dir, const char *file)+{+ const size_t len = strlen(dir);+ const bool sep = len > 0 && !fb_os_is_sep(dir[len - 1]);+ snprintf(dst, size, "%s%s%s", dir, sep ? (char[2]){fb_os_sep(), '\0'} : "", file);+}++bool fb_path_is_dir(const char *p)+{+ struct stat st;+ return stat(p, &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR;+}++bool fb_path_exists(const char *p)+{+ struct stat st;+ return stat(p, &st) == 0;+}++/* The last component, ignoring a trailing separator. */+const char *fb_path_basename(const char *p, char *buf, size_t size)+{+ size_t len = strlen(p);+ while (len > 1 && fb_os_is_sep(p[len - 1])) {+ len--;+ }+ size_t s = len;+ while (s > 0 && !fb_os_is_sep(p[s - 1])) {+ s--;+ }+ snprintf(buf, size, "%.*s", (int)(len - s), p + s);+ return buf;+}++/* "~" and relative paths become absolute. */+static void path_absolute(char *p, size_t size)+{+ char tmp[FB_PATH];+ const char *home = fb_os_home();+ if (p[0] == '~' && (p[1] == '\0' || fb_os_is_sep(p[1])) && home) {+ snprintf(tmp, sizeof(tmp), "%s%s", home, p + 1);+ snprintf(p, size, "%s", tmp);+ }+ char cwd[FB_PATH];+ if (!fb_os_path_is_absolute(p) && fb_os_getcwd(cwd, sizeof(cwd))) {+ fb_path_join(tmp, sizeof(tmp), cwd, p);+ snprintf(p, size, "%s", tmp);+ }+}++/* Collapse separators, "." and "..", keeping the drive prefix; the root keeps its separator. */+static void path_collapse(char *p, size_t size)+{+ char out[FB_PATH];+ const size_t root = fb_os_root_len(p);+ size_t o = root, i = root;+ memcpy(out, p, root);+ while (p[i] && o + 2 < sizeof(out)) {+ while (fb_os_is_sep(p[i])) {+ i++;+ }+ size_t j = i;+ while (p[j] && !fb_os_is_sep(p[j])) {+ j++;+ }+ const size_t n = j - i;+ if (n == 2 && p[i] == '.' && p[i + 1] == '.') {+ while (o > root && out[o - 1] != fb_os_sep()) {+ o--;+ }+ o = o > root + 1 ? o - 1 : root; /* drop the separator before the removed name */+ }+ else if (n > 0 && !(n == 1 && p[i] == '.') && o + n + 2 < sizeof(out)) {+ out[o++] = fb_os_sep();+ memcpy(out + o, p + i, n);+ o += n;+ }+ i = j;+ }+ if (o == root) {+ out[o++] = fb_os_sep();+ }+ out[o] = '\0';+ snprintf(p, size, "%s", out);+}++/* BLI_path_normalize, made absolute. */+void fb_path_normalize(char *p, size_t size)+{+ path_absolute(p, size);+ path_collapse(p, size);+}++void fb_path_resolve(const char *dir, const char *typed, char *out, size_t size)+{+ if (fb_os_path_is_absolute(typed) || typed[0] == '~') {+ snprintf(out, size, "%s", typed);+ }+ else {+ fb_path_join(out, size, dir, typed);+ }+ fb_path_normalize(out, size);+}diff --git a/kit/intern/kit_filebrowser_posix.c b/kit/intern/kit_filebrowser_posix.cnew file mode 100644index 0000000..1b6715f--- /dev/null+++ b/kit/intern/kit_filebrowser_posix.c@@ -0,0 +1,239 @@+/* File browser platform parts for Linux, BSD and macOS: directory reading, system folders+ * (fsmenu_system_unix.cc / fsmenu_system_macos.mm), home, time and sleep.+ * Compiles to nothing on Windows (kit_filebrowser_win32.c).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#ifndef _WIN32++# include <dirent.h>+# include <stdio.h>+# include <stdlib.h>+# include <string.h>+# include <sys/stat.h>+# include <unistd.h>+# ifdef __linux__+# include <mntent.h>+# endif++# include "kit_filebrowser_intern.h"++char fb_os_sep(void)+{+ return '/';+}++bool fb_os_is_sep(char c)+{+ return c == '/';+}++size_t fb_os_root_len(const char *p)+{+ (void)p;+ return 0;+}++bool fb_os_path_is_absolute(const char *p)+{+ return p[0] == '/';+}++bool fb_os_path_is_root(const char *p)+{+ return p[0] == '/' && p[1] == '\0';+}++bool fb_os_getcwd(char *buf, size_t size)+{+ return getcwd(buf, size) != NULL;+}++bool fb_os_mkdir(const char *p)+{+ return mkdir(p, 0777) == 0;+}++const char *fb_os_home(void)+{+ const char *h = getenv("HOME");+ return (h && h[0]) ? h : NULL;+}++void fb_os_localtime(time_t t, struct tm *r)+{+ localtime_r(&t, r);+}++void fb_os_sleep_ms(int ms)+{+ usleep((useconds_t)ms * 1000);+}++void fb_os_bookmarks_path(char *buf, size_t size)+{+ const char *xch = getenv("XDG_CONFIG_HOME");+ if (xch && xch[0]) {+ snprintf(buf, size, "%s/bui/bookmarks.txt", xch);+ }+ else if (fb_os_home()) {+ snprintf(buf, size, "%s/.config/bui/bookmarks.txt", fb_os_home());+ }+}++/* filelist_readjob_common.cc: stat follows links, lstat tells them apart. */+bool fb_os_read_dir(FBData *f)+{+ DIR *d = opendir(f->dir);+ if (!d) {+ return false;+ }+ struct dirent *de;+ while ((de = readdir(d)) != NULL) {+ if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) {+ continue;+ }+ char full[FB_PATH];+ fb_path_join(full, sizeof(full), f->dir, de->d_name);+ struct stat st, lst;+ const bool ok = stat(full, &st) == 0, lok = lstat(full, &lst) == 0;+ const struct stat *use = ok ? &st : &lst; /* a broken link reports itself */+ FBEntry *e = fb_entry_add(f, de->d_name);+ e->hidden = de->d_name[0] == '.';+ e->link = lok && S_ISLNK(lst.st_mode);+ e->kind = (ok && S_ISDIR(st.st_mode)) ? FB_KIND_DIR : FB_KIND_FILE;+ e->size = (ok || lok) ? (long long)use->st_size : 0;+ e->mtime = (ok || lok) ? use->st_mtime : 0;+ fb_entry_finish(e);+ }+ closedir(d);+ return true;+}++/* The six user folders, by their names in $HOME (and XDG keys on Linux). */+static const struct {+ const char *xdg_key, *name, *icon;+} g_user_dirs[] = {+ {"XDG_DESKTOP_DIR", "Desktop", "DESKTOP"},+ {"XDG_DOCUMENTS_DIR", "Documents", "DOCUMENTS"},+ {"XDG_DOWNLOAD_DIR", "Downloads", "IMPORT"},+# ifdef __APPLE__+ {NULL, "Movies", "FILE_MOVIE"},+# else+ {"XDG_VIDEOS_DIR", "Videos", "FILE_MOVIE"},+# endif+ {"XDG_PICTURES_DIR", "Pictures", "FILE_IMAGE"},+ {"XDG_MUSIC_DIR", "Music", "FILE_SOUND"},+};++/* fsmenu_xdg_user_dirs_parse: the KEY="value" line of user-dirs.dirs, "$HOME/" expanded. */+static bool xdg_lookup(const char *home, const char *key, char *out, size_t size)+{+ char cfg[FB_PATH], line[FB_PATH + 128];+ const char *xch = getenv("XDG_CONFIG_HOME");+ if (xch && xch[0]) {+ fb_path_join(cfg, sizeof(cfg), xch, "user-dirs.dirs");+ }+ else {+ snprintf(cfg, sizeof(cfg), "%s/.config/user-dirs.dirs", home);+ }+ FILE *fp = key ? fopen(cfg, "r") : NULL;+ bool found = false;+ const size_t klen = key ? strlen(key) : 0;+ while (fp && !found && fgets(line, sizeof(line), fp)) {+ if (strncmp(line, key, klen) != 0 || line[klen] != '=') {+ continue;+ }+ char *v = line + klen + 1;+ v[strcspn(v, "\r\n")] = '\0';+ const size_t vl = strlen(v);+ if (vl < 2 || v[0] != '"' || v[vl - 1] != '"') {+ continue;+ }+ v[vl - 1] = '\0';+ v++;+ if (strncmp(v, "$HOME/", 6) == 0) {+ snprintf(out, size, "%s/%s", home, v + 6);+ }+ else {+ snprintf(out, size, "%s", v);+ }+ found = true;+ }+ if (fp) {+ fclose(fp);+ }+ return found;+}++static void read_user_dirs(FBData *f, const char *home)+{+ fb_place_add(f, FB_CAT_SYSTEM, home, "Home", "HOME", false);+ for (size_t i = 0; i < sizeof(g_user_dirs) / sizeof(g_user_dirs[0]); i++) {+ char p[FB_PATH];+ if (!xdg_lookup(home, g_user_dirs[i].xdg_key, p, sizeof(p))) {+ fb_path_join(p, sizeof(p), home, g_user_dirs[i].name);+ }+ if (fb_path_is_dir(p)) {+ fb_place_add(f, FB_CAT_SYSTEM, p, g_user_dirs[i].name, g_user_dirs[i].icon, false);+ }+ }+}++/* Same as STRPREFIX, but only at a separator or the end. */+static bool dir_prefix(const char *a, const char *b)+{+ const size_t n = strlen(b);+ return strncmp(a, b, n) == 0 && (a[n] == '\0' || a[n] == '/');+}++static bool read_volumes(FBData *f)+{+ bool found = false;+# ifdef __linux__+ /* Mount points of /dev devices, without /boot, /efi and snap loop devices. */+ FILE *fp = setmntent("/proc/mounts", "r");+ struct mntent *mnt;+ while (fp && (mnt = getmntent(fp)) != NULL) {+ if (dir_prefix(mnt->mnt_dir, "/boot") || dir_prefix(mnt->mnt_dir, "/efi") ||+ !dir_prefix(mnt->mnt_fsname, "/dev") || strncmp(mnt->mnt_fsname, "/dev/loop", 9) == 0)+ {+ continue;+ }+ fb_place_add(f, FB_CAT_VOLUMES, mnt->mnt_dir, NULL, "DISK_DRIVE", true);+ found = true;+ }+ if (fp) {+ endmntent(fp);+ }+# elif defined(__APPLE__)+ DIR *d = opendir("/Volumes");+ struct dirent *de;+ while (d && (de = readdir(d)) != NULL) {+ char p[FB_PATH];+ fb_path_join(p, sizeof(p), "/Volumes", de->d_name);+ if (de->d_name[0] != '.') {+ fb_place_add(f, FB_CAT_VOLUMES, p, de->d_name, "DISK_DRIVE", true);+ }+ }+ if (d) {+ closedir(d);+ }+# else+ (void)dir_prefix;+# endif+ return found;+}++/* fsmenu_read_system */+void fb_os_read_system(FBData *f)+{+ if (fb_os_home()) {+ read_user_dirs(f, fb_os_home());+ }+ if (!read_volumes(f)) {+ fb_place_add(f, FB_CAT_VOLUMES, "/", NULL, "DISK_DRIVE", true);+ }+}++#endif /* !_WIN32 */diff --git a/kit/intern/kit_filebrowser_win32.c b/kit/intern/kit_filebrowser_win32.cnew file mode 100644index 0000000..79cd8ef--- /dev/null+++ b/kit/intern/kit_filebrowser_win32.c@@ -0,0 +1,157 @@+/* File browser platform parts for Windows: directory reading, system folders and drives+ * (fsmenu_system_win32.cc), home, time and sleep. Compiles to nothing elsewhere+ * (kit_filebrowser_posix.c).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#ifdef _WIN32++# ifndef WIN32_LEAN_AND_MEAN+# define WIN32_LEAN_AND_MEAN+# endif+# include <direct.h>+# include <stdio.h>+# include <stdlib.h>+# include <string.h>+# include <windows.h>++# include "kit_filebrowser_intern.h"++char fb_os_sep(void)+{+ return '\\';+}++bool fb_os_is_sep(char c)+{+ return c == '/' || c == '\\';+}++size_t fb_os_root_len(const char *p)+{+ return (p[0] && p[1] == ':') ? 2 : 0;+}++bool fb_os_path_is_absolute(const char *p)+{+ return fb_os_root_len(p) == 2 || (fb_os_is_sep(p[0]) && fb_os_is_sep(p[1]));+}++bool fb_os_path_is_root(const char *p)+{+ return strlen(p) <= 3 && fb_os_root_len(p) == 2;+}++bool fb_os_getcwd(char *buf, size_t size)+{+ return _getcwd(buf, (int)size) != NULL;+}++bool fb_os_mkdir(const char *p)+{+ return _mkdir(p) == 0;+}++const char *fb_os_home(void)+{+ const char *h = getenv("HOME");+ if (!h || !h[0]) {+ h = getenv("USERPROFILE");+ }+ return (h && h[0]) ? h : NULL;+}++void fb_os_localtime(time_t t, struct tm *r)+{+ localtime_s(r, &t);+}++void fb_os_sleep_ms(int ms)+{+ Sleep((DWORD)ms);+}++void fb_os_bookmarks_path(char *buf, size_t size)+{+ const char *base = getenv("APPDATA");+ if (base) {+ snprintf(buf, size, "%s\\bui\\bookmarks.txt", base);+ }+}++static time_t filetime_to_time(FILETIME ft)+{+ const unsigned long long t = ((unsigned long long)ft.dwHighDateTime << 32) | ft.dwLowDateTime;+ return (time_t)((t - 116444736000000000ULL) / 10000000ULL); /* 100 ns since 1601 */+}++bool fb_os_read_dir(FBData *f)+{+ char pattern[FB_PATH];+ wchar_t wpat[FB_PATH];+ fb_path_join(pattern, sizeof(pattern), f->dir, "*");+ MultiByteToWideChar(CP_UTF8, 0, pattern, -1, wpat, FB_PATH);+ WIN32_FIND_DATAW fd;+ HANDLE h = FindFirstFileW(wpat, &fd);+ if (h == INVALID_HANDLE_VALUE) {+ return false;+ }+ do {+ char name[1024];+ WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, name, sizeof(name), NULL, NULL);+ if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {+ continue;+ }+ FBEntry *e = fb_entry_add(f, name);+ e->kind = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? FB_KIND_DIR : FB_KIND_FILE;+ e->hidden = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0 || name[0] == '.';+ e->link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;+ e->size = ((long long)fd.nFileSizeHigh << 32) | fd.nFileSizeLow;+ e->mtime = filetime_to_time(fd.ftLastWriteTime);+ fb_entry_finish(e);+ } while (FindNextFileW(h, &fd));+ FindClose(h);+ return true;+}++static const struct {+ const char *name, *icon;+} g_user_dirs[] = {+ {"Desktop", "DESKTOP"}, {"Documents", "DOCUMENTS"}, {"Downloads", "IMPORT"},+ {"Music", "FILE_SOUND"}, {"Pictures", "FILE_IMAGE"}, {"Videos", "FILE_MOVIE"},+};++static const char *drive_icon(UINT type)+{+ switch (type) {+ case DRIVE_REMOTE:+ return "NETWORK_DRIVE";+ case DRIVE_REMOVABLE:+ return "EXTERNAL_DRIVE";+ default:+ return "DISK_DRIVE";+ }+}++/* fsmenu_read_system */+void fb_os_read_system(FBData *f)+{+ const char *home = fb_os_home();+ if (home) {+ fb_place_add(f, FB_CAT_SYSTEM, home, "Home", "HOME", false);+ for (size_t i = 0; i < sizeof(g_user_dirs) / sizeof(g_user_dirs[0]); i++) {+ char p[FB_PATH];+ fb_path_join(p, sizeof(p), home, g_user_dirs[i].name);+ if (fb_path_is_dir(p)) {+ fb_place_add(f, FB_CAT_SYSTEM, p, g_user_dirs[i].name, g_user_dirs[i].icon, false);+ }+ }+ }+ char drives[512];+ const DWORD n = GetLogicalDriveStringsA(sizeof(drives), drives);+ for (const char *d = drives; n && *d; d += strlen(d) + 1) {+ fb_place_add(f, FB_CAT_VOLUMES, d, d, drive_icon(GetDriveTypeA(d)), false);+ }+}++#endif /* _WIN32 */diff --git a/kit/intern/kit_filelist.c b/kit/intern/kit_filelist.cnew file mode 100644index 0000000..9d86341--- /dev/null+++ b/kit/intern/kit_filelist.c@@ -0,0 +1,384 @@+/* File list data: entries, their icons and detail strings, sorting and filtering+ * (filelist/filelist.cc, filelist_sort.cc, filelist_filter.cc, filelist_readjob_common.cc).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "kit_filebrowser_intern.h"++/* blenlib (bui_core) */+int BLI_strcasecmp_natural(const char *s1, const char *s2);+void BLI_str_format_byte_unit(char dst[15], long long int bytes, bool base_10);++/* -------------------------------------------------------------------- */+/** \name File types (ED_path_extension_type, ED_file_extension_icon)+ * \{ */++static const char *const g_ext_script[] = {".py", NULL};+static const char *const g_ext_text[] = {+ ".txt", ".glsl", ".osl", ".data", ".pov", ".ini", ".mcr", ".inc", ".fountain", ".toml",+ ".md", ".json", ".c", ".h", ".cc", ".hh", ".cpp", ".rs", ".js", ".ts",+ ".css", ".html", ".xml", ".yaml", ".yml", ".csv", ".log", ".cfg", NULL};+static const char *const g_ext_font[] = {".ttf", ".pfb", ".otf", ".woff", ".woff2", NULL};+static const char *const g_ext_btx[] = {".btx", NULL};+static const char *const g_ext_volume[] = {".vdb", NULL};+static const char *const g_ext_archive[] = {".zip", ".tar", ".gz", ".xz", ".bz2", ".7z", ".zst",+ NULL};+static const char *const g_ext_3d[] = {".abc", ".usd", ".usda", ".usdc", ".usdz", ".obj", ".mtl",+ ".3ds", ".fbx", ".glb", ".gltf", ".svg", ".pdf", ".ply",+ ".stl", NULL};+/* imb_ext_image, imb_ext_movie, imb_ext_audio */+static const char *const g_ext_image[] = {+ ".png", ".tga", ".bmp", ".jpg", ".jpeg", ".sgi", ".rgb", ".rgba", ".tif", ".tiff", ".tx",+ ".jp2", ".j2c", ".hdr", ".dds", ".dpx", ".cin", ".exr", ".psd", ".pdd", ".psb", ".webp",+ ".avif", ".gif", NULL};+static const char *const g_ext_movie[] = {+ ".avi", ".flc", ".mov", ".movie", ".mp4", ".m4v", ".m2v", ".m2t", ".m2ts", ".mts",+ ".ts", ".mv", ".avs", ".wmv", ".ogv", ".ogg", ".r3d", ".dv", ".mpeg", ".mpg",+ ".mpg2", ".vob", ".mkv", ".flv", ".divx", ".xvid", ".mxf", ".webm", NULL};+static const char *const g_ext_audio[] = {".wav", ".mp2", ".mp3", ".ac3", ".aac", ".flac", ".wma",+ ".eac3", ".aif", ".aiff", ".m4a", ".mka", ".opus", NULL};++/* In ED_path_extension_type's order: the first list that matches wins. */+static const struct {+ const char *const *exts;+ const char *icon;+} g_file_types[] = {+ {g_ext_script, "FILE_SCRIPT"}, {g_ext_text, "FILE_TEXT"}, {g_ext_font, "FILE_FONT"},+ {g_ext_btx, "FILE_BLANK"}, {g_ext_volume, "FILE_VOLUME"}, {g_ext_archive, "FILE_ARCHIVE"},+ {g_ext_3d, "FILE_3D"}, {g_ext_image, "FILE_IMAGE"}, {g_ext_movie, "FILE_MOVIE"},+ {g_ext_audio, "FILE_SOUND"},+};++static bool ascii_ieq(const char *a, const char *b)+{+ for (; *a && *b; a++, b++) {+ const int ca = (*a >= 'A' && *a <= 'Z') ? *a + 32 : *a;+ const int cb = (*b >= 'A' && *b <= 'Z') ? *b + 32 : *b;+ if (ca != cb) {+ return false;+ }+ }+ return *a == *b;+}++static bool ext_in(const char *dot, const char *const *exts)+{+ for (; *exts; exts++) {+ if (ascii_ieq(dot, *exts)) {+ return true;+ }+ }+ return false;+}++static const char *file_icon_name(const char *name)+{+ const char *dot = strrchr(name, '.');+ if (!dot) {+ return "FILE_BLANK";+ }+ if (ascii_ieq(dot, ".blend")) {+ return "FILE_BLEND";+ }+ if (strncmp(dot, ".blend", 6) == 0 && dot[6] >= '0' && dot[6] <= '9') {+ return "FILE_BACKUP"; /* file_is_blend_backup: ".blend1" ... */+ }+ for (size_t i = 0; i < sizeof(g_file_types) / sizeof(g_file_types[0]); i++) {+ if (ext_in(dot, g_file_types[i].exts)) {+ return g_file_types[i].icon;+ }+ }+ return "FILE_BLANK";+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Entries+ * \{ */++/* date_string::datetime with "Today" / "Yesterday" */+static void format_datetime(time_t t, char *buf, size_t size)+{+ struct tm tm, today, yesterday;+ fb_os_localtime(t, &tm);+ fb_os_localtime(time(NULL), &today);+ fb_os_localtime(time(NULL) - 86400, &yesterday);+ char hm[16];+ strftime(hm, sizeof(hm), "%H:%M", &tm);+ const bool is_today = tm.tm_year == today.tm_year && tm.tm_yday == today.tm_yday;+ const bool is_yesterday = tm.tm_year == yesterday.tm_year && tm.tm_yday == yesterday.tm_yday;+ if (is_today || is_yesterday) {+ snprintf(buf, size, "%s %s", is_today ? "Today" : "Yesterday", hm);+ }+ else {+ strftime(buf, size, "%d %b %Y %H:%M", &tm);+ }+}++FBEntry *fb_entry_add(FBData *f, const char *name)+{+ if (f->nall == f->capall) {+ f->capall = f->capall ? f->capall * 2 : 64;+ f->all = (FBEntry *)realloc(f->all, sizeof(FBEntry) * (size_t)f->capall);+ }+ FBEntry *e = &f->all[f->nall++];+ memset(e, 0, sizeof(*e));+ e->name = bk_strdup(name);+ return e;+}++/* filelist_geticon_file_type_ex + filelist_get_details_column_string */+void fb_entry_finish(FBEntry *e)+{+ static const char *const kind_icons[] = {NULL, "FILE_FOLDER", "FILE_PARENT"};+ const char *icon = e->kind == FB_KIND_FILE ? file_icon_name(e->name) :+ (e->kind == FB_KIND_DIR && e->link) ? "FOLDER_REDIRECT" :+ kind_icons[e->kind];+ e->icon = bk_icons_lookup(icon);+ if (e->kind != FB_KIND_PARENT) {+ format_datetime(e->mtime, e->date, sizeof(e->date));+ }+ if (e->kind == FB_KIND_FILE) {+ BLI_str_format_byte_unit(e->size_str, e->size, true);+ }+}++void fb_entries_free(FBData *f)+{+ for (int i = 0; i < f->nall; i++) {+ free(f->all[i].name);+ }+ f->nall = 0;+ free(f->vis);+ f->vis = NULL;+ f->nvis = 0;+}++void fb_read_dir(FBData *f)+{+ fb_entries_free(f);+ f->error[0] = '\0';+ if (!fb_os_path_is_root(f->dir)) {+ FBEntry *e = fb_entry_add(f, "..");+ e->kind = FB_KIND_PARENT;+ fb_entry_finish(e);+ }+ if (!fb_os_read_dir(f)) {+ snprintf(f->error, sizeof(f->error), "Cannot open directory");+ }+}++FBEntry *fb_vis_entry(const FBData *f, int i)+{+ return (i >= 0 && i < f->nvis) ? &f->all[f->vis[i]] : NULL;+}++bool fb_show_hidden(const FBData *f)+{+ return f->b_hidden && f->b_hidden->value != 0;+}++int fb_filter_index(const FBData *f)+{+ return f->filter_dd ? (int)f->filter_dd->value : 0;+}++/* Selected visible entries (files only, or any but ".."); r_last gets the last one. */+int fb_count_selected(const FBData *f, bool files_only, int *r_last)+{+ int count = 0;+ for (int i = 0; i < f->nvis; i++) {+ const FBEntry *e = fb_vis_entry(f, i);+ if (e->sel && (files_only ? e->kind == FB_KIND_FILE : e->kind != FB_KIND_PARENT)) {+ count++;+ if (r_last) {+ *r_last = i;+ }+ }+ }+ return count;+}++void fb_select_none(FBData *f)+{+ for (int i = 0; i < f->nall; i++) {+ f->all[i].sel = false;+ }+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Sorting (filelist_sort.cc)+ * \{ */++static int cmp_entries(const FBData *f, int ia, int ib)+{+ const FBEntry *a = &f->all[ia], *b = &f->all[ib];+ if (a->kind != b->kind) { /* compare_direntry_generic: "..", then folders, then files */+ return a->kind > b->kind ? -1 : 1;+ }+ int r;+ if (f->sort == FB_SORT_TIME && a->mtime != b->mtime) {+ r = a->mtime < b->mtime ? 1 : -1; /* compare_date: newest first */+ }+ else if (f->sort == FB_SORT_SIZE && a->size != b->size) {+ r = a->size < b->size ? 1 : -1; /* compare_size: largest first */+ }+ else {+ r = BLI_strcasecmp_natural(a->name, b->name); /* compare_tiebreaker */+ }+ return f->invert ? -r : r;+}++/* Stable merge sort of the visible indices, bottom-up (no recursion). */+static void sort_visible(FBData *f)+{+ int *tmp = (int *)malloc(sizeof(int) * (size_t)(f->nvis > 0 ? f->nvis : 1));+ for (int width = 1; width < f->nvis; width *= 2) {+ for (int lo = 0; lo < f->nvis; lo += 2 * width) {+ const int mid = BK_MIN(lo + width, f->nvis), hi = BK_MIN(lo + 2 * width, f->nvis);+ int a = lo, b = mid, o = lo;+ while (a < mid || b < hi) {+ const bool take_a = b >= hi || (a < mid && cmp_entries(f, f->vis[a], f->vis[b]) <= 0);+ tmp[o++] = take_a ? f->vis[a++] : f->vis[b++];+ }+ }+ memcpy(f->vis, tmp, sizeof(int) * (size_t)f->nvis);+ }+ free(tmp);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Filtering (filelist_filter.cc)+ * \{ */++/* fnmatch() with FNM_CASEFOLD for '*' and '?' (portable). */+static bool glob_match(const char *p, const char *s)+{+ const char *star = NULL, *retry = NULL;+ while (*s) {+ const int cp = (*p >= 'A' && *p <= 'Z') ? *p + 32 : *p;+ const int cs = (*s >= 'A' && *s <= 'Z') ? *s + 32 : *s;+ if (*p == '*') {+ star = p++;+ retry = s;+ }+ else if (*p && (*p == '?' || cp == cs)) {+ p++;+ s++;+ }+ else if (star) { /* let the last '*' take one more character */+ p = star + 1;+ s = ++retry;+ }+ else {+ return false;+ }+ }+ while (*p == '*') {+ p++;+ }+ return *p == '\0';+}++static bool matches_filter(const FBData *f, const FBEntry *e)+{+ const int fi = fb_filter_index(f);+ if (e->kind != FB_KIND_FILE || f->nfilters == 0 || fi < 0 || fi >= f->nfilters) {+ return true;+ }+ const FBFilter *flt = &f->filters[fi];+ bool any = flt->npats == 0;+ for (int i = 0; i < flt->npats && !any; i++) {+ any = glob_match(flt->pats[i], e->name);+ }+ return any;+}++static bool entry_visible(const FBData *f, const FBEntry *e)+{+ char pat[300];+ snprintf(pat, sizeof(pat), "*%s*", f->search); /* filter_search is matched as "*search*" */+ return e->kind == FB_KIND_PARENT ||+ ((!e->hidden || fb_show_hidden(f)) && /* is_hidden_dot_filename */+ (f->mode != FB_MODE_DIRECTORY || e->kind == FB_KIND_DIR) &&+ (!f->search[0] || glob_match(pat, e->name)) && matches_filter(f, e));+}++void fb_filter_sort(FBData *f)+{+ free(f->vis);+ f->vis = (int *)malloc(sizeof(int) * (size_t)(f->nall > 0 ? f->nall : 1));+ f->nvis = 0;+ for (int i = 0; i < f->nall; i++) {+ const bool shown = entry_visible(f, &f->all[i]);+ f->all[i].sel &= shown;+ if (shown) {+ f->vis[f->nvis++] = i;+ }+ }+ sort_visible(f);+ f->active = BK_MIN(f->active, f->nvis - 1);+ if (f->list) {+ bk_invalidate(f->list);+ }+}++/* "Label\tpattern pattern ..." (no tab: the text is both); ".py" means "*.py". */+static void parse_filter(FBFilter *flt, const char *s)+{+ const char *tab = strchr(s, '\t');+ const size_t label_len = tab ? (size_t)(tab - s) : strlen(s);+ flt->label = (char *)calloc(label_len + 1, 1);+ memcpy(flt->label, s, label_len);+ for (const char *p = tab ? tab + 1 : s; *p;) {+ p += strspn(p, " ;,");+ const size_t n = strcspn(p, " ;,");+ if (n > 0) {+ flt->pats = (char **)realloc(flt->pats, sizeof(char *) * (size_t)(flt->npats + 1));+ char *pat = (char *)calloc(n + 2, 1);+ snprintf(pat, n + 2, "%s%.*s", p[0] == '.' ? "*" : "", (int)n, p);+ flt->pats[flt->npats++] = pat;+ }+ p += n;+ }+}++void fb_filters_free(FBData *f)+{+ for (int i = 0; i < f->nfilters; i++) {+ free(f->filters[i].label);+ for (int k = 0; k < f->filters[i].npats; k++) {+ free(f->filters[i].pats[k]);+ }+ free(f->filters[i].pats);+ }+ free(f->filters);+ f->filters = NULL;+ f->nfilters = 0;+}++void fb_filters_set(FBData *f, const char *const *v, int count)+{+ fb_filters_free(f);+ f->filters = count > 0 ? (FBFilter *)calloc((size_t)count, sizeof(FBFilter)) : NULL;+ const char **labels = (const char **)calloc((size_t)(count > 0 ? count : 1), sizeof(char *));+ for (int i = 0; i < count; i++) {+ parse_filter(&f->filters[i], v[i] ? v[i] : "");+ labels[i] = f->filters[i].label;+ }+ f->nfilters = BK_MAX(count, 0);+ BK_set_strs(f->filter_dd, "items", labels, f->nfilters);+ f->filter_dd->value = 0;+ free(labels);+}++/** \} */diff --git a/kit/intern/kit_filelist_view.c b/kit/intern/kit_filelist_view.cnew file mode 100644index 0000000..ac893e0--- /dev/null+++ b/kit/intern/kit_filelist_view.c@@ -0,0 +1,574 @@+/* File list view: the main region in vertical (list) display (file_draw.cc file_draw_list,+ * filesel.cc ED_fileselect_init_layout FILE_VERTICALDISPLAY) and its selection (file_ops.cc+ * file_select, file_walk_select).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <math.h>+#include <stdio.h>+#include <string.h>++#include "kit_filebrowser_intern.h"++static int u(void)+{+ return bk_unit();+}++/* -------------------------------------------------------------------- */+/** \name Layout+ * \{ */++/* The attribute columns: one table for the header and the rows. */+static const struct {+ const char *name;+ FBSort sort;+ int align;+} g_columns[FB_COL_NUM] = {+ {"Name", FB_SORT_ALPHA, BK_ALIGN_LEFT},+ {"Date Modified", FB_SORT_TIME, BK_ALIGN_LEFT},+ {"Size", FB_SORT_SIZE, BK_ALIGN_RIGHT},+};++typedef struct FBLayout {+ int border_x, border_y, pad_top, tile_w, tile_h, header_h, item_h, prv_w, col_pad;+ int col_w[FB_COL_NUM];+} FBLayout;++/* ED_fileselect_init_layout (FILE_VERTICALDISPLAY) + file_attribute_columns_widths */+static FBLayout list_layout(const BKNode *n)+{+ FBLayout l;+ l.border_x = (int)(0.4f * u());+ l.border_y = (int)(0.05f * u());+ l.pad_top = 2 * l.border_y;+ l.tile_h = bk_iround(ceilf(bk_font_size() * 1.25f) * 1.4f); /* fontstyle_height_max * 1.4 */+ l.tile_w = n->w - 2 * l.border_x;+ l.header_h = (int)(l.tile_h * 1.2f) + 2 * l.border_y; /* attribute_column_header_h */+ l.item_h = l.tile_h + 2 * l.border_y;+ l.prv_w = (int)(u() * 0.8f); /* ICON_DEFAULT_WIDTH_SCALE */+ l.col_pad = (int)(0.5f * u()); /* ATTRIBUTE_COLUMN_PADDING */+ l.col_w[FB_COL_DATE] = (int)(bk_text_width("30 Sep 2099 03:59", -1, false) + 2 * l.col_pad ++ 0.5f * u());+ l.col_w[FB_COL_SIZE] = (int)(bk_text_width("098.7 MiB", -1, false) + 2 * l.col_pad);+ l.col_w[FB_COL_NAME] = l.tile_w - l.col_w[FB_COL_DATE] - l.col_w[FB_COL_SIZE];+ return l;+}++static int column_x(const BKNode *n, const FBLayout *l, int c)+{+ int x = n->x;+ for (int k = 0; k < c; k++) {+ x += l->col_w[k];+ }+ return x;+}++static int column_at(const BKNode *n, const FBLayout *l, int x)+{+ for (int c = 0; c < FB_COL_NUM; c++) {+ if (x >= column_x(n, l, c) && x < column_x(n, l, c + 1)) {+ return c;+ }+ }+ return -1;+}++static int content_h(const BKNode *n, const FBLayout *l)+{+ return FB(n)->nvis * l->item_h + 2 * l->pad_top;+}++static int view_h(const BKNode *n, const FBLayout *l)+{+ return BK_MAX(0, n->h - l->header_h);+}++static int max_scroll(const BKNode *n, const FBLayout *l)+{+ return BK_MAX(0, content_h(n, l) - view_h(n, l));+}++static BKRect view_rect(const BKNode *n, const FBLayout *l)+{+ return bk_rect(n->x, n->y + l->header_h, n->w, view_h(n, l));+}++/* tile_draw_rect_get (screen space, y down) */+static BKRect tile_rect(const BKNode *n, const FBLayout *l, int i)+{+ const int y = n->y + l->header_h + l->pad_top + l->border_y + i * l->item_h - n->scroll;+ return bk_rect(n->x + l->border_x, y, l->tile_w, l->tile_h);+}++static int row_at(const BKNode *n, const FBLayout *l, int y)+{+ const int rel = y - (n->y + l->header_h + l->pad_top) + n->scroll;+ const int i = (y >= n->y + l->header_h && rel >= 0) ? rel / l->item_h : -1;+ return i < FB(n)->nvis ? i : -1;+}++static bool has_scroller(const BKNode *n, const FBLayout *l)+{+ return content_h(n, l) > view_h(n, l);+}++static void scroller(const BKNode *n, const FBLayout *l, BKRect *r_track, BKRect *r_thumb)+{+ const bool wide = FB(n)->scroller_hot || n->dragmode == 1;+ const BKRect area = view_rect(n, l);+ bk_scroller_rects(&area, n->scroll, content_h(n, l), wide ? 255 : 0, r_track, r_thumb);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Drawing+ * \{ */++/* file_draw_string with text_clip_middle_ex: long names lose their middle. */+static void draw_name(const BKRect *rect, const char *s, const uchar col[4])+{+ static const char ell[] = "\xe2\x80\xa6"; /* BLI_STR_UTF8_HORIZONTAL_ELLIPSIS */+ const int len = (int)strlen(s);+ char buf[FB_PATH];+ snprintf(buf, sizeof(buf), "%s", s);+ for (int keep = len - 1; keep >= 0 && bk_text_width(buf, -1, false) > bk_rw(rect); keep--) {+ int l = keep / 2, rs = len - (keep - keep / 2);+ while (l > 0 && (s[l] & 0xC0) == 0x80) { /* stay on UTF-8 boundaries */+ l--;+ }+ while (rs < len && (s[rs] & 0xC0) == 0x80) {+ rs++;+ }+ snprintf(buf, sizeof(buf), "%.*s%s%s", l, s, ell, s + rs);+ }+ bk_text_in_pad(rect, buf, col, BK_ALIGN_LEFT, false, 0);+}++/* draw_tile_background */+static void draw_tile_background(const BKRect *r, bool selected, bool highlighted)+{+ const BKWCol *w = &bk_theme.list_item;+ float bg[4], outline[4];+ bk_rgba(selected ? w->inner_sel : w->inner, bg);+ bk_rgba(selected ? w->outline_sel : w->outline, outline);+ bg[3] = highlighted ? BK_MIN(bg[3] + 0.1f, 1.0f) : bg[3]; /* hover: at least 10% */+ const float rad = w->roundness * u();+ if (outline[3] > 0.0f) {+ bk_roundbox(r->xmin, r->ymin, bk_rw(r), bk_rh(r), rad, CNR_ALL, outline);+ }+ if (bg[3] > 0.0f) {+ const int in = outline[3] > 0.0f ? 1 : 0;+ bk_roundbox(r->xmin + in, r->ymin + in, bk_rw(r) - 2 * in, bk_rh(r) - 2 * in,+ BK_MAX(0.0f, rad - in), CNR_ALL, bg);+ }+}++/* draw_background: alternating rows, TH_BACK blended with TH_ROW_ALTERNATE. */+static void draw_background(const BKNode *n, const FBLayout *l, int first, int rows)+{+ uchar alt[4];+ bk_color_over(bk_theme.file_row_alternate, bk_theme.file_back, alt);+ bk_fill(n->x, n->y, n->w, n->h, bk_theme.file_back);+ for (int i = first | 1; i < first + rows; i += 2) {+ bk_fill(n->x, tile_rect(n, l, i).ymin - l->border_y, n->w, l->item_h, alt);+ }+}++static void draw_row(const BKNode *n, const FBLayout *l, int i)+{+ const FBEntry *e = fb_vis_entry(FB(n), i);+ const BKRect t = tile_rect(n, l, i);+ const bool editing = n->edit && i == n->rename_row;+ const int padx = (int)(0.1f * u());+ if (!editing) {+ draw_tile_background(&t, e->sel, bk_hovered(n) && i == n->hot);+ }+ bk_icon(e->icon, t.xmin + padx + l->prv_w * 0.5f, t.ymin + bk_rh(&t) * 0.5f, NULL,+ e->hidden ? 0.5f : 1.0f, 0); /* file_add_icon_but: hidden files at half alpha */+ BKRect tr = t; /* text_draw_rect_get */+ tr.xmin += l->prv_w + 2 * padx + 1;+ tr.xmax = t.xmin + l->col_w[FB_COL_NAME] - l->border_x;+ if (editing) {+ bk_te_draw(n->edit, &tr, bk_theme.textfield.text);+ }+ else {+ draw_name(&tr, e->name, e->sel ? bk_theme.list_item.text_sel : bk_theme.list_item.text);+ }+ /* draw_details_columns */+ const char *details[FB_COL_NUM] = {NULL, e->kind == FB_KIND_PARENT ? NULL : e->date,+ e->kind == FB_KIND_FILE ? e->size_str : NULL};+ for (int c = FB_COL_DATE; c < FB_COL_NUM; c++) {+ const BKRect cr = bk_rect(column_x(n, l, c) + l->col_pad, t.ymin,+ l->col_w[c] - 2 * l->col_pad, bk_rh(&t));+ if (details[c]) {+ bk_text_in_pad(&cr, details[c], bk_theme.file_text, g_columns[c].align, false, 0);+ }+ }+}++/* The "No items" / filter / error message at UI_UNIT_X, UI_UNIT_Y into the first free tile. */+static void draw_hint(const BKNode *n, const FBLayout *l)+{+ const FBData *f = FB(n);+ const bool only_parent = f->nvis == 1 && fb_vis_entry(f, 0)->kind == FB_KIND_PARENT;+ if (f->nvis > 0 && !(only_parent && f->error[0])) {+ return;+ }+ const BKRect t = tile_rect(n, l, f->nvis);+ uchar c[4];+ memcpy(c, bk_theme.file_text, 4);+ c[3] = f->search[0] ? c[3] : c[3] / 2;+ const char *msg = f->error[0] ? f->error :+ f->search[0] ? "No results match the search filter" :+ "No items";+ bk_text(t.xmin + u(), t.ymin + u() * 0.7f, msg, -1, c, false);+}++/* draw_fixed_header_background + draw_columnheader_columns, drawn last. */+static void draw_column_header(const BKNode *n, const FBLayout *l)+{+ const FBData *f = FB(n);+ uchar back[4], div[4];+ float divc[4], tc[4];+ bk_color_shade(bk_theme.file_back, 11, back);+ bk_color_shade(bk_theme.file_back, -10, div);+ bk_rgba(div, divc);+ bk_rgba(bk_theme.file_text, tc);+ bk_fill(n->x, n->y, n->w, l->header_h, back);+ const float divider_pad = 0.2f * l->header_h;+ for (int c = 0; c < FB_COL_NUM; c++) {+ const int sx = column_x(n, l, c);+ if (f->sort == g_columns[c].sort) { /* active sort type triangle, 't' when inverted */+ bk_tria(sx + l->col_w[c] - 0.3f * u() - l->col_pad / 2.0f, n->y + l->header_h * 0.5f,+ f->invert ? 't' : 'v', tc, 0);+ }+ const BKRect hr = bk_rect(sx + l->col_pad, n->y + l->border_y, l->col_w[c] - 2 * l->col_pad,+ l->header_h - l->border_y);+ bk_text_in_pad(&hr, g_columns[c].name, bk_theme.file_text, BK_ALIGN_LEFT, false, 0);+ if (c != FB_COL_NAME) {+ bk_line(sx - 1, n->y + divider_pad, sx - 1, n->y + l->header_h - divider_pad, divc, 1.0f);+ }+ }+ bk_line(n->x, n->y + 0.5f, n->x + n->w, n->y + 0.5f, divc, 1.0f);+ bk_line(n->x, n->y + l->header_h - 0.5f, n->x + n->w, n->y + l->header_h - 0.5f, divc, 1.0f);+}++static void list_draw(BKNode *n)+{+ const FBLayout l = list_layout(n);+ n->scroll = BK_CLAMP(n->scroll, 0, max_scroll(n, &l));+ const int first = BK_MAX(0, (n->scroll - l.pad_top) / l.item_h);+ const int rows = view_h(n, &l) / l.item_h + 2;+ const BKRect v = view_rect(n, &l);+ bk_clip_push(v.xmin, v.ymin, bk_rw(&v), bk_rh(&v)); /* the header draws its own back */+ draw_background(n, &l, first, rows);+ for (int i = first; i < FB(n)->nvis && i < first + rows; i++) {+ draw_row(n, &l, i);+ }+ draw_hint(n, &l);+ bk_clip_pop();+ draw_column_header(n, &l);+ if (has_scroller(n, &l)) {+ BKRect track, thumb;+ scroller(n, &l, &track, &thumb);+ bk_scroller_draw(&track, &thumb, FB(n)->scroller_hot || n->dragmode == 1 ? 255 : 0,+ n->dragmode == 1);+ }+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Selection (file_select, file_walk_select)+ * \{ */++void fb_list_see(BKNode *n, int i)+{+ const FBLayout l = list_layout(n);+ const int y = l.pad_top + i * l.item_h, vh = view_h(n, &l);+ n->scroll = y < n->scroll ? y : (y + l.item_h > n->scroll + vh ? y + l.item_h - vh : n->scroll);+ n->scroll = BK_CLAMP(n->scroll, 0, max_scroll(n, &l));+ bk_invalidate(n);+}++/* The name field follows the last selected file (params->file). */+static void sync_filename(FBData *f)+{+ const FBEntry *e = fb_vis_entry(f, f->active);+ if (f->fname && e && e->sel && e->kind == FB_KIND_FILE && f->mode != FB_MODE_DIRECTORY) {+ bk_set_text(&f->fname->text, e->name);+ bk_invalidate(f->fname);+ }+ fb_update_exec(f);+}++/* Click selects, Ctrl toggles (extend), Shift fills from the anchor. */+void fb_click_select(FBData *f, int i, int mods)+{+ FBEntry *e = fb_vis_entry(f, i);+ if (!e) {+ return;+ }+ const bool multi = f->multiple && e->kind != FB_KIND_PARENT;+ if (multi && (mods & BK_SHIFT) && f->anchor >= 0) {+ if (!(mods & BK_CTRL)) {+ fb_select_none(f);+ }+ for (int k = BK_MIN(f->anchor, i); k <= BK_MAX(f->anchor, i); k++) {+ fb_vis_entry(f, k)->sel |= fb_vis_entry(f, k)->kind != FB_KIND_PARENT;+ }+ }+ else {+ const bool toggle = multi && (mods & BK_CTRL);+ const bool on = toggle ? !e->sel : true;+ if (!toggle) {+ fb_select_none(f);+ }+ e->sel = on;+ f->anchor = i;+ }+ f->active = i;+ sync_filename(f);+ bk_invalidate(f->list);+}++/* Arrows move the active file; Shift extends from the anchor. */+void fb_walk(FBData *f, int to, int mods)+{+ if (f->nvis == 0) {+ return;+ }+ to = BK_CLAMP(to, 0, f->nvis - 1);+ const bool extend = f->multiple && (mods & BK_SHIFT);+ if (extend && f->anchor < 0) {+ f->anchor = BK_MAX(f->active, 0);+ }+ fb_click_select(f, to, extend ? BK_SHIFT : 0); /* Shift keeps the anchor */+ fb_list_see(f->list, to);+}++void fb_rename_begin(FBData *f, int i)+{+ const FBEntry *e = fb_vis_entry(f, i);+ if (!e || e->kind == FB_KIND_PARENT) {+ return;+ }+ f->list->rename_row = i;+ bk_begin_edit(f->list, e->name, true);+ fb_list_see(f->list, i);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Input+ * \{ */++static void end_rename(BKNode *n)+{+ BKContext *ctx = bk_ctx(n);+ if (n->edit && ctx && ctx->focus == n) {+ BK_focus_node(ctx, NULL); /* file_params_rename_end */+ }+}++/* A press on the scroller: drag the thumb, or jump to the click first. */+static int press_scroller(BKNode *n, const FBLayout *l, const BKEvent *e)+{+ BKRect track, thumb;+ FB(n)->scroller_hot = true;+ scroller(n, l, &track, &thumb);+ const int vh = BK_MAX(1, view_h(n, l));+ if (e->y < thumb.ymin || e->y >= thumb.ymax) {+ n->scroll = BK_CLAMP(+ (int)((float)(e->y - track.ymin) / vh * content_h(n, l) - vh * 0.5f), 0, max_scroll(n, l));+ }+ n->dragmode = 1;+ n->drag_orig = n->scroll;+ bk_invalidate(n);+ return 1;+}++/* file_column_sort_ui_context: a header click sorts by the column, again inverts. */+static int press_header(BKNode *n, const FBLayout *l, const BKEvent *e)+{+ FBData *f = FB(n);+ const int c = column_at(n, l, e->x);+ if (c >= 0) {+ f->invert = f->sort == g_columns[c].sort && !f->invert;+ f->sort = g_columns[c].sort;+ fb_filter_sort(f);+ }+ return 1;+}++static int list_press(BKNode *n, BKEvent *e)+{+ FBData *f = FB(n);+ const FBLayout l = list_layout(n);+ end_rename(n);+ n->dragmode = 0;+ if (f->scroller_hot && has_scroller(n, &l) && e->y >= n->y + l.header_h) {+ return press_scroller(n, &l, e);+ }+ if (e->y < n->y + l.header_h) {+ return press_header(n, &l, e);+ }+ const int i = row_at(n, &l, e->y);+ if (i >= 0) {+ fb_click_select(f, i, e->mods);+ return 1;+ }+ fb_select_none(f); /* empty space deselects */+ f->active = -1;+ fb_update_exec(f);+ bk_invalidate(n);+ return 1;+}++static int list_dbl(BKNode *n, BKEvent *e)+{+ FBData *f = FB(n);+ const FBLayout l = list_layout(n);+ const int i = row_at(n, &l, e->y);+ if (e->y < n->y + l.header_h || n->dragmode == 1 || i < 0) {+ return e->y < n->y + l.header_h ? list_press(n, e) : 1; /* a header click toggles again */+ }+ if (!fb_vis_entry(f, i)->sel) {+ fb_click_select(f, i, 0);+ }+ fb_open_entry(f, i);+ return 1;+}++static int list_drag(BKNode *n, BKEvent *e)+{+ const FBLayout l = list_layout(n);+ const int vh = BK_MAX(1, view_h(n, &l));+ if (n->dragmode != 1) {+ return 0;+ }+ n->scroll = BK_CLAMP((int)(n->drag_orig + (double)e->dy * content_h(n, &l) / vh), 0,+ max_scroll(n, &l));+ bk_invalidate(n);+ return 1;+}++static int list_release(BKNode *n, BKEvent *e)+{+ (void)e;+ n->dragmode = 0;+ bk_invalidate(n);+ return 1;+}++static int list_move(BKNode *n, BKEvent *e)+{+ FBData *f = FB(n);+ const FBLayout l = list_layout(n);+ const int edge = n->x + n->w - (int)(0.45f * u() + 2 * bk_px()) - (int)(0.3f * u());+ const bool on_scroller = has_scroller(n, &l) && e->y >= n->y + l.header_h && e->x >= edge;+ const int hot = on_scroller ? -1 : row_at(n, &l, e->y);+ if (hot != n->hot || on_scroller != f->scroller_hot) {+ n->hot = hot;+ f->scroller_hot = on_scroller;+ bk_invalidate(n);+ }+ return 0;+}++static int list_leave(BKNode *n)+{+ n->hot = -1;+ FB(n)->scroller_hot = false;+ bk_invalidate(n);+ return 0;+}++static int list_wheel(BKNode *n, BKEvent *e)+{+ const FBLayout l = list_layout(n);+ const int ns = BK_CLAMP(n->scroll - e->delta * l.item_h * FB_WHEEL_ROWS, 0, max_scroll(n, &l));+ if (ns == n->scroll) {+ return 0;+ }+ n->scroll = ns;+ list_move(n, e);+ bk_invalidate(n);+ return 1;+}++/* Keys go to the rename field while editing, else to the browser's keymap. */+static int list_key(BKNode *n, BKEvent *e)+{+ return n->edit ? bk_edit_key(n, e) : fb_keymap(FB(n), e);+}++static void list_finish_edit(BKNode *n, bool confirm)+{+ const int i = n->rename_row;+ n->rename_row = -1;+ if (confirm && n->edit && n->edit->text[0]) {+ fb_rename(FB(n), i, n->edit->text);+ }+ bk_invalidate(n);+}++static int list_cursor_at(BKNode *n, int x, int y)+{+ (void)x;+ (void)y;+ return n->edit ? BK_CURSOR_TEXT : BK_CURSOR_DEFAULT;+}++static void list_measure(BKNode *n, int *rw, int *rh)+{+ (void)n;+ *rw = 16 * u();+ *rh = 8 * u();+}++int fb_list_page_rows(const BKNode *n)+{+ const FBLayout l = list_layout(n);+ return view_h(n, &l) / BK_MAX(1, l.item_h);+}++/* Tk-style yview in rows. */+static void list_view(BKNode *n, int axis, int *r_first, int *r_visible, int *r_total)+{+ const FBLayout l = list_layout(n);+ *r_first = axis == 0 ? n->scroll / BK_MAX(1, l.item_h) : 0;+ *r_visible = axis == 0 ? view_h(n, &l) / BK_MAX(1, l.item_h) : 1;+ *r_total = axis == 0 ? FB(n)->nvis : 1;+}++static void list_set_view(BKNode *n, int axis, int first)+{+ const FBLayout l = list_layout(n);+ if (axis == 0) {+ n->scroll = BK_CLAMP(first * l.item_h, 0, max_scroll(n, &l));+ bk_invalidate(n);+ }+}++const BKClass bk_cls_fb_list = {.name = "filelist",+ .flags = CLS_INTERACTIVE,+ .measure = list_measure,+ .draw = list_draw,+ .press = list_press,+ .dbl = list_dbl,+ .drag = list_drag,+ .release = list_release,+ .move = list_move,+ .leave = list_leave,+ .key = list_key,+ .wheel = list_wheel,+ .cursor_at = list_cursor_at,+ .finish_edit = list_finish_edit,+ .view = list_view,+ .set_view = list_set_view};++/** \} */diff --git a/kit/intern/kit_fileops.c b/kit/intern/kit_fileops.cnew file mode 100644index 0000000..1773402--- /dev/null+++ b/kit/intern/kit_fileops.c@@ -0,0 +1,314 @@+/* File browser operations: navigation and history (file_ops.cc, folder_history.cc), new folder,+ * rename, and executing the browser (FILE_OT_execute, FILE_OT_cancel).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "kit_filebrowser_intern.h"++/* -------------------------------------------------------------------- */+/** \name Navigation (ED_file_change_dir, folder_history.cc)+ * \{ */++static void history_push(char **stack, int *n, const char *dir)+{+ if (*n == FB_HISTORY) {+ free(stack[0]);+ memmove(stack, stack + 1, sizeof(char *) * (FB_HISTORY - 1));+ (*n)--;+ }+ stack[(*n)++] = bk_strdup(dir);+}++static void history_clear(char **stack, int *n)+{+ while (*n > 0) {+ free(stack[--(*n)]);+ }+}++void fb_history_free(FBData *f)+{+ history_clear(f->back, &f->nback);+ history_clear(f->fwd, &f->nfwd);+}++static void update_parts(FBData *f)+{+ bk_set_text(&f->path->text, f->dir);+ bk_invalidate(f->path);+ BK_set_num(f->b_prev, "enabled", f->nback > 0);+ BK_set_num(f->b_next, "enabled", f->nfwd > 0);+ BK_set_num(f->b_parent, "enabled", !fb_os_path_is_root(f->dir));+ bk_invalidate(f->side);+ fb_update_exec(f);+}++void fb_navigate(FBData *f, const char *dir_in, bool history)+{+ char dir[FB_PATH];+ snprintf(dir, sizeof(dir), "%s", dir_in && dir_in[0] ? dir_in : ".");+ fb_path_normalize(dir, sizeof(dir));+ fb_path_slash_ensure(dir, sizeof(dir));+ if (!fb_path_is_dir(dir)) { /* file_directory_enter_handle: keep the current folder */+ bk_set_text(&f->path->text, f->dir);+ bk_invalidate(f->path);+ return;+ }+ if (history && f->dir[0] && strcmp(dir, f->dir) != 0) {+ history_push(f->back, &f->nback, f->dir);+ history_clear(f->fwd, &f->nfwd);+ }+ snprintf(f->dir, sizeof(f->dir), "%s", dir);+ fb_read_dir(f);+ f->active = f->anchor = -1;+ fb_filter_sort(f);+ f->list->scroll = 0;+ f->list->hot = -1;+ update_parts(f);+ bk_emit(f->self, BK_EV_CHANGE, NULL, 0, 0);+}++/* file.previous / file.next: pop one stack, push the current folder on the other. */+static void history_step(FBData *f, char **from, int *nfrom, char **to, int *nto)+{+ if (*nfrom == 0) {+ return;+ }+ history_push(to, nto, f->dir);+ char *d = from[--(*nfrom)];+ fb_navigate(f, d, false);+ free(d);+}++void fb_go_back(FBData *f)+{+ history_step(f, f->back, &f->nback, f->fwd, &f->nfwd);+}++void fb_go_forward(FBData *f)+{+ history_step(f, f->fwd, &f->nfwd, f->back, &f->nback);+}++void fb_go_parent(FBData *f)+{+ char p[FB_PATH];+ snprintf(p, sizeof(p), "%s", f->dir);+ if (fb_path_parent(p)) {+ fb_navigate(f, p, true);+ }+}++void fb_refresh(FBData *f)+{+ fb_read_dir(f);+ fb_filter_sort(f);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name New folder and rename+ * \{ */++static void select_by_name(FBData *f, const char *name)+{+ for (int k = 0; k < f->nvis; k++) {+ if (strcmp(fb_vis_entry(f, k)->name, name) == 0) {+ fb_click_select(f, k, 0);+ fb_list_see(f->list, k);+ return;+ }+ }+}++/* file.directory_new: "untitled", "untitled.001", ... then rename it. */+void fb_new_folder(FBData *f)+{+ char name[64] = "untitled", p[FB_PATH];+ fb_path_join(p, sizeof(p), f->dir, name);+ for (int i = 1; fb_path_exists(p) && i < 1000; i++) {+ snprintf(name, sizeof(name), "untitled.%03d", i);+ fb_path_join(p, sizeof(p), f->dir, name);+ }+ if (!fb_os_mkdir(p)) {+ snprintf(f->error, sizeof(f->error), "Could not create new folder");+ bk_invalidate(f->list);+ return;+ }+ fb_refresh(f);+ select_by_name(f, name);+ fb_rename_begin(f, f->active);+}++/* renamebutton_cb: refuse separators and names that exist, then rename. */+bool fb_rename(FBData *f, int i, const char *name_in)+{+ const FBEntry *e = fb_vis_entry(f, i);+ char from[FB_PATH], to[FB_PATH], name[1024];+ snprintf(name, sizeof(name), "%s", name_in);+ if (!e || strcmp(name, e->name) == 0) {+ return false;+ }+ fb_path_join(from, sizeof(from), f->dir, e->name);+ fb_path_join(to, sizeof(to), f->dir, name);+ const bool has_sep = strchr(name, '/') || strchr(name, fb_os_sep());+ if (has_sep || fb_path_exists(to) || rename(from, to) != 0) {+ snprintf(f->error, sizeof(f->error), "Could not rename \"%s\"", e->name);+ bk_invalidate(f->list);+ return false;+ }+ fb_refresh(f);+ select_by_name(f, name);+ return true;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Execute and cancel+ * \{ */++/* The execute button: "Overwrite" when saving over a file (file_draw_check_exists). */+void fb_update_exec(FBData *f)+{+ static const char *const labels[] = {"Open", "Save", "Accept"};+ const char *typed = f->fname->text ? f->fname->text : "";+ char p[FB_PATH];+ fb_path_join(p, sizeof(p), f->dir, typed);+ const bool overwrite = f->mode == FB_MODE_SAVE && typed[0] && fb_path_exists(p) &&+ !fb_path_is_dir(p);+ const char *label = overwrite ? "Overwrite" : (f->exec_label ? f->exec_label : labels[f->mode]);+ if (!bk_streq(f->b_exec->text, label)) {+ bk_set_text(&f->b_exec->text, label);+ bk_relayout(f->b_exec);+ }+ bk_invalidate(f->b_exec);+}++void fb_finish(FBData *f, FBState state)+{+ f->state = state;+ if (state == FB_STATE_CHOSEN) {+ fb_add_recent(f, f->dir);+ fb_write_bookmarks(f);+ }+ bk_emit(f->self, BK_EV_SUBMIT, NULL, state, 0);+}++static void choose(FBData *f, const char *const *paths, int n)+{+ bk_strs_set(&f->result, paths, n);+ fb_finish(f, FB_STATE_CHOSEN);+}++/* A single selected folder is the answer, else the current one. */+static void execute_directory(FBData *f)+{+ char p[FB_PATH];+ int last = -1;+ if (fb_count_selected(f, false, &last) == 1) {+ fb_path_join(p, sizeof(p), f->dir, fb_vis_entry(f, last)->name);+ }+ else {+ snprintf(p, sizeof(p), "%s", f->dir);+ }+ fb_path_strip_slash(p);+ choose(f, (const char *[]){p}, 1);+}++/* Several selected files ("multiple"); false when there are fewer than two. */+static bool execute_selection(FBData *f)+{+ const int n = fb_count_selected(f, true, NULL);+ if (f->mode != FB_MODE_OPEN || !f->multiple || n < 2) {+ return false;+ }+ char **v = (char **)calloc((size_t)n, sizeof(char *));+ int k = 0;+ for (int i = 0; i < f->nvis; i++) {+ const FBEntry *e = fb_vis_entry(f, i);+ if (e->sel && e->kind == FB_KIND_FILE) {+ char q[FB_PATH];+ fb_path_join(q, sizeof(q), f->dir, e->name);+ v[k++] = bk_strdup(q);+ }+ }+ choose(f, (const char *const *)v, k);+ for (int i = 0; i < k; i++) {+ free(v[i]);+ }+ free(v);+ return true;+}++/* file_exec / FILE_OT_execute */+void fb_execute(FBData *f)+{+ bk_strs_free(&f->result);+ if (f->mode == FB_MODE_DIRECTORY) {+ execute_directory(f);+ return;+ }+ const char *typed = f->fname->text ? f->fname->text : "";+ char p[FB_PATH];+ fb_path_resolve(f->dir, typed, p, sizeof(p));+ if (typed[0] && fb_path_is_dir(p)) { /* a typed folder: go there (file_filename_enter_handle) */+ bk_set_text(&f->fname->text, "");+ fb_navigate(f, p, true);+ return;+ }+ if (execute_selection(f)) {+ return;+ }+ if (!typed[0]) { /* no name: a selected folder opens, else there is nothing to do yet */+ const FBEntry *a = fb_vis_entry(f, f->active);+ if (a && a->sel && a->kind != FB_KIND_FILE) {+ fb_open_entry(f, f->active);+ }+ return;+ }+ if (f->mode == FB_MODE_OPEN && !fb_path_exists(p)) {+ snprintf(f->error, sizeof(f->error), "File not found: %s", typed);+ bk_invalidate(f->list);+ return;+ }+ choose(f, (const char *[]){p}, 1);+}++/* Double click: folders open, files execute. */+void fb_open_entry(FBData *f, int i)+{+ const FBEntry *e = fb_vis_entry(f, i);+ char p[FB_PATH];+ if (!e || e->kind == FB_KIND_FILE) {+ fb_execute(f);+ return;+ }+ snprintf(p, sizeof(p), "%s", f->dir);+ if (e->kind == FB_KIND_PARENT) {+ fb_path_parent(p);+ }+ else {+ fb_path_join(p, sizeof(p), f->dir, e->name);+ }+ fb_navigate(f, p, true);+}++/* Return: a selected folder opens (outside folder selection), else execute. */+void fb_activate(FBData *f)+{+ const FBEntry *a = fb_vis_entry(f, f->active);+ if (a && a->sel && a->kind != FB_KIND_FILE && f->mode != FB_MODE_DIRECTORY) {+ fb_open_entry(f, f->active);+ }+ else {+ fb_execute(f);+ }+}++/** \} */diff --git a/kit/intern/kit_fsmenu.c b/kit/intern/kit_fsmenu.cnew file mode 100644index 0000000..ee437e0--- /dev/null+++ b/kit/intern/kit_fsmenu.c@@ -0,0 +1,315 @@+/* File browser places: Volumes, System, Bookmarks and Recent (fsmenu.cc), read from and written+ * to a bookmarks.txt in fsmenu's format, and the tools-region list that shows them+ * (template_list over FILEBROWSER_UL_dir).+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "kit_filebrowser_intern.h"++int BLI_strcasecmp_natural(const char *s1, const char *s2); /* blenlib (bui_core) */++static int u(void)+{+ return bk_unit();+}++/* -------------------------------------------------------------------- */+/** \name Places (fsmenu_insert_entry, fsmenu_remove_entry)+ * \{ */++static int place_find(const FBData *f, FBCategory cat, const char *path)+{+ for (int i = 0; i < f->nplaces[cat]; i++) {+ if (strcmp(f->places[cat][i].path, path) == 0) {+ return i;+ }+ }+ return -1;+}++static void place_insert(FBData *f, FBCategory cat, int at, const char *path, const char *label,+ const char *icon)+{+ char base[256];+ f->places[cat] = (FBPlace *)realloc(f->places[cat],+ sizeof(FBPlace) * (size_t)(f->nplaces[cat] + 1));+ memmove(&f->places[cat][at + 1], &f->places[cat][at],+ sizeof(FBPlace) * (size_t)(f->nplaces[cat] - at));+ FBPlace *pl = &f->places[cat][at];+ pl->path = bk_strdup(path);+ pl->label = bk_strdup(label ? label :+ fb_os_path_is_root(path) ? path :+ fb_path_basename(path, base, sizeof(base)));+ pl->icon = bk_icons_lookup(icon);+ f->nplaces[cat]++;+}++static void place_remove(FBData *f, FBCategory cat, int i)+{+ free(f->places[cat][i].path);+ free(f->places[cat][i].label);+ memmove(&f->places[cat][i], &f->places[cat][i + 1],+ sizeof(FBPlace) * (size_t)(f->nplaces[cat] - i - 1));+ f->nplaces[cat]--;+}++static void places_clear(FBData *f, FBCategory cat)+{+ while (f->nplaces[cat] > 0) {+ place_remove(f, cat, f->nplaces[cat] - 1);+ }+}++/* FS_INSERT_LAST or FS_INSERT_SORTED; a path that is listed already is not added again. */+void fb_place_add(FBData *f, FBCategory cat, const char *path, const char *label,+ const char *icon, bool sorted)+{+ char p[FB_PATH];+ snprintf(p, sizeof(p), "%s", path);+ fb_path_slash_ensure(p, sizeof(p));+ if (place_find(f, cat, p) >= 0) {+ return;+ }+ int at = f->nplaces[cat];+ while (sorted && at > 0 && BLI_strcasecmp_natural(f->places[cat][at - 1].path, p) > 0) {+ at--;+ }+ place_insert(f, cat, at, p, label, icon);+}++void fb_places_free(FBData *f)+{+ for (int c = 0; c < FB_CAT_NUM; c++) {+ places_clear(f, (FBCategory)c);+ free(f->places[c]);+ f->places[c] = NULL;+ }+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name bookmarks.txt (fsmenu_read_bookmarks, fsmenu_write_file)+ * \{ */++static const char *const g_sections[FB_CAT_NUM] = {NULL, NULL, "[Bookmarks]", "[Recent]"};+static const char *const g_icons[FB_CAT_NUM] = {NULL, NULL, "BOOKMARKS", "FILE_FOLDER"};++void fb_read_bookmarks(FBData *f)+{+ places_clear(f, FB_CAT_BOOKMARKS);+ places_clear(f, FB_CAT_RECENT);+ FILE *fp = f->bookmarks_path[0] ? fopen(f->bookmarks_path, "r") : NULL;+ char line[FB_PATH];+ int cat = -1;+ while (fp && fgets(line, sizeof(line), fp)) {+ line[strcspn(line, "\r\n")] = '\0';+ const bool bookmarks = strcmp(line, g_sections[FB_CAT_BOOKMARKS]) == 0;+ const bool recent = strcmp(line, g_sections[FB_CAT_RECENT]) == 0;+ cat = bookmarks ? FB_CAT_BOOKMARKS : (recent ? FB_CAT_RECENT : cat);+ /* "!#!name" lines are labels; paths that are gone are skipped */+ if (!bookmarks && !recent && cat >= 0 && line[0] && strncmp(line, "!#!", 3) != 0 &&+ fb_path_is_dir(line))+ {+ fb_place_add(f, (FBCategory)cat, line, NULL, g_icons[cat], false);+ }+ }+ if (fp) {+ fclose(fp);+ }+}++void fb_write_bookmarks(FBData *f)+{+ char dir[FB_PATH];+ snprintf(dir, sizeof(dir), "%s", f->bookmarks_path);+ if (!f->bookmarks_path[0] || !fb_path_parent(dir)) {+ return;+ }+ if (!fb_path_is_dir(dir)) {+ fb_os_mkdir(dir); /* the config folder, one level (BKE_appdir_folder_id_create) */+ }+ FILE *fp = fopen(f->bookmarks_path, "w");+ for (int c = FB_CAT_BOOKMARKS; fp && c <= FB_CAT_RECENT; c++) {+ fprintf(fp, "%s\n", g_sections[c]);+ for (int i = 0; i < f->nplaces[c]; i++) {+ fprintf(fp, "%s\n", f->places[c][i].path);+ }+ }+ if (fp) {+ fclose(fp);+ }+}++static void default_bookmarks_path(FBData *f)+{+ const char *env = getenv("BUI_BOOKMARKS");+ if (env && env[0]) {+ snprintf(f->bookmarks_path, sizeof(f->bookmarks_path), "%s", env);+ }+ else {+ fb_os_bookmarks_path(f->bookmarks_path, sizeof(f->bookmarks_path));+ }+}++/* FS_INSERT_SAVE into Recent: first, once, at most U.recent_dirs entries. */+void fb_add_recent(FBData *f, const char *dir)+{+ const int old = place_find(f, FB_CAT_RECENT, dir);+ if (old >= 0) {+ place_remove(f, FB_CAT_RECENT, old);+ }+ place_insert(f, FB_CAT_RECENT, 0, dir, NULL, g_icons[FB_CAT_RECENT]);+ while (f->nplaces[FB_CAT_RECENT] > FB_RECENT_MAX) {+ place_remove(f, FB_CAT_RECENT, f->nplaces[FB_CAT_RECENT] - 1);+ }+}++/* file.bookmark_add */+void fb_bookmark_dir(FBData *f)+{+ fb_place_add(f, FB_CAT_BOOKMARKS, f->dir, NULL, g_icons[FB_CAT_BOOKMARKS], false);+ fb_write_bookmarks(f);+ bk_relayout(f->self);+ bk_invalidate(f->side);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name The tools-region list+ * \{ */++typedef struct FBPlacesView {+ FBData *f;+ FBCategory cat;+} FBPlacesView;++#define PV(n) ((FBPlacesView *)(n)->ext)++static int pad(void)+{+ return (int)(FB_PLACES_PAD * u());+}++static void pv_measure(BKNode *n, int *rw, int *rh)+{+ *rw = 6 * u();+ *rh = BK_MAX(1, PV(n)->f->nplaces[PV(n)->cat]) * u() + 2 * pad();+}++static int pv_row_at(BKNode *n, int y)+{+ const int i = (y - n->y - pad()) / u();+ return (y >= n->y + pad() && i < PV(n)->f->nplaces[PV(n)->cat]) ? i : -1;+}++static void pv_draw(BKNode *n)+{+ const FBData *f = PV(n)->f;+ const FBPlace *places = f->places[PV(n)->cat];+ BKRect r = bk_node_rect(n);+ BKWCol box = bk_theme.box;+ bk_widget_box(&box, &r, CNR_ALL, NULL);+ for (int i = 0; i < f->nplaces[PV(n)->cat]; i++) {+ BKRect row = bk_rect(n->x + pad(), n->y + pad() + i * u(), n->w - 2 * pad(), u());+ const bool active = strcmp(places[i].path, f->dir) == 0; /* the current folder */+ const int st = (active ? ST_SELECT : 0) | (i == n->hot && bk_hovered(n) ? ST_HOVER : 0);+ BKWCol w;+ bk_widget_state(&w, &bk_theme.list_item, st & ST_SELECT);+ bk_widget_list_itembut(&w, &(BKRect){row.xmin, row.ymin, row.xmax, row.ymax}, st);+ bk_text_icon(&row, places[i].label, places[i].icon,+ active ? bk_theme.list_item.text_sel : bk_theme.list_item.text, BK_ALIGN_LEFT,+ true);+ }+}++static int pv_move(BKNode *n, BKEvent *e)+{+ const int i = pv_row_at(n, e->y);+ if (i != n->hot) {+ n->hot = i;+ bk_set_text(&n->desc, i >= 0 ? PV(n)->f->places[PV(n)->cat][i].path : NULL); /* tooltip */+ bk_invalidate(n);+ }+ return 0;+}++static int pv_leave(BKNode *n)+{+ n->hot = -1;+ bk_invalidate(n);+ return 0;+}++static int pv_press(BKNode *n, BKEvent *e)+{+ char path[FB_PATH];+ const int i = pv_row_at(n, e->y);+ if (i >= 0) {+ snprintf(path, sizeof(path), "%s", PV(n)->f->places[PV(n)->cat][i].path);+ fb_navigate(PV(n)->f, path, true);+ }+ return 1;+}++/* file.bookmark_delete / file.reset_recent on the hovered row: Delete or X. */+static int pv_key(BKNode *n, BKEvent *e)+{+ FBPlacesView *pv = PV(n);+ const bool removable = pv->cat == FB_CAT_BOOKMARKS || pv->cat == FB_CAT_RECENT;+ if (!removable || n->hot < 0 ||+ !(bk_keysym_is(e->keysym, "Delete") || bk_keysym_is(e->keysym, "x")))+ {+ return 0; /* bubbles up to the browser's keymap */+ }+ place_remove(pv->f, pv->cat, n->hot);+ n->hot = -1;+ fb_write_bookmarks(pv->f);+ bk_relayout(n);+ bk_invalidate(n);+ return 1;+}++static void pv_free(BKNode *n)+{+ free(n->ext);+ n->ext = NULL;+}++static const BKClass bk_cls_fb_places = {.name = "fsmenu",+ .flags = CLS_INTERACTIVE,+ .free_ext = pv_free,+ .measure = pv_measure,+ .draw = pv_draw,+ .press = pv_press,+ .move = pv_move,+ .leave = pv_leave,+ .key = pv_key};++/* One list per category, in the panels' bodies. */+BKNode *fb_places_view_new(FBData *f, FBCategory cat, BKNode *parent)+{+ BKNode *n = bk_node_new_cls(&bk_cls_fb_places);+ FBPlacesView *pv = (FBPlacesView *)calloc(1, sizeof(FBPlacesView));+ pv->f = f;+ pv->cat = cat;+ n->ext = pv;+ n->hot = -1;+ bk_node_add(parent, n);+ return n;+}++/* fsmenu_read_system + fsmenu_read_bookmarks */+void fb_places_read(FBData *f)+{+ fb_os_read_system(f);+ default_bookmarks_path(f);+ fb_read_bookmarks(f);+}++/** \} */diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.hindex 2a33ae3..537bf3a 100644--- a/kit/intern/kit_intern.h+++ b/kit/intern/kit_intern.h@@ -53,6 +53,8 @@ typedef struct BKTheme {float menu_shadow_fac;int menu_shadow_width;float panel_roundness;+ /* space_file */+ uchar file_back[4], file_text[4], file_header[4], file_row_alternate[4];} BKTheme;extern BKTheme bk_theme;@@ -162,7 +164,15 @@ int bk_icon_size(void);void bk_icon(int icon, float cx, float cy, const uchar *color, float alpha, float size);const float *bk_icon_tint(int icon); /* NULL: use text color */float bk_content_width(const char *s, int icon, bool bold);-void bk_tria(float cx, float cy, char dir, const float c[4], float size);+void bk_tria(float cx, float cy, char dir, const float c[4], float size); /* 'h' 'v' 't' */+/* `c` drawn with its alpha over the opaque `back` (rounded), and shaded by `shade` (RGB). */+void bk_color_over(const uchar c[4], const uchar back[4], uchar r_out[4]);+void bk_color_shade(const uchar c[4], int shade, uchar r_out[4]);+/* View2D vertical scroller along the right edge of `area` (view2d_scroller_size_get,+ * view2d_scrollers_calc, view2d_scrollers_draw_ex); alpha is alpha_vert, 0..255. */+void bk_scroller_rects(const BKRect *area, int scroll, int content_h, int alpha, BKRect *r_track,+ BKRect *r_thumb);+void bk_scroller_draw(const BKRect *track, const BKRect *thumb, int alpha, bool pressed);void bk_chevron_down(float cx, float cy, const uchar c[4]);/* Browser-look primitives (kit_draw.c). Colors are 0xAARRGGBB. */@@ -257,6 +267,12 @@ typedef struct BKClass {* (rows, lines, pixels): Tk's xview/yview and scrollbars build on this */void (*view)(BKNode *n, int axis, int *r_first, int *r_visible, int *r_total);void (*set_view)(BKNode *n, int axis, int first);+ /* class-specific string and string-list properties (consulted before the generic ones;+ * get_str / get_strs return NULL for keys they don't own) */+ int (*set_str)(BKNode *n, const char *key, const char *v);+ const char *(*get_str)(BKNode *n, const char *key);+ int (*set_strs)(BKNode *n, const char *key, const char *const *v, int count);+ const struct BKStrs *(*get_strs)(BKNode *n, const char *key);} BKClass;enum {@@ -297,6 +313,7 @@ enum {NF_CONFIGURED = 1 << 23, /* geometry changed since the host was told (BK_EV_CONFIGURE) */NF_OPAQUE = 1 << 24, /* root: the host paints every pixel, skip the region clear */NF_HTML = 1 << 25, /* "html": Chrome's default form-control look and interaction */+ NF_ACTIVE_DEFAULT = 1 << 26, /* buttons: UI_BUT_ACTIVE_DEFAULT (drawn with the select colors) */};#define BK_HTML(n) (((n)->flags & NF_HTML) != 0)@@ -573,6 +590,7 @@ float bk_hpx(float css);/* Chrome's text field content: text, selection (#3390ff / white text) and caret. */void bk_html_te_draw(BKTextEdit *te, const BKRect *content, const uchar color[4]);extern const BKClass bk_cls_meter;+extern const BKClass bk_cls_filebrowser; /* kit_filebrowser.c */bool bk_textarea_html_measure(BKNode *n, int *r_w, int *r_h); /* kit_textarea.c */void bk_textarea_html_draw(BKNode *n);diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.cindex a5376e9..7dd9fa6 100644--- a/kit/intern/kit_widgets.c+++ b/kit/intern/kit_widgets.c@@ -51,6 +51,9 @@ static int state_of(const BKNode *n)if (n->flags & NF_SELECTED) {st = (st & ~ST_HOVER) | ST_SELECT; /* part of a multi-drag */}+ if (n->flags & NF_ACTIVE_DEFAULT) {+ st |= ST_ACTIVE_DEFAULT;+ }/* aligned column: only the bottom button draws the emboss */if (n->parent && (n->parent->flags & NF_ALIGN) && !(n->corners & (CNR_BL | CNR_BR)) &&(n->parent->cls == &bk_cls_column))diff --git a/ui/CMakeLists.txt b/ui/CMakeLists.txtindex 9a951d9..1335752 100644--- a/ui/CMakeLists.txt+++ b/ui/CMakeLists.txt@@ -54,3 +54,38 @@ else()add_library(bui::ui ALIAS bui_ui)target_include_directories(bui_ui INTERFACE ${UI_INC})endif()++# Blender's File Browser (editors/space_file + ED_fileselect.hh), staged in+# space_file/ from upstream d0ee3e1db6f (2026-11-04) with only the mechanical+# include pass (BLI_*.hh -> BUI's BLI_*.h). Not compiled: upstream has moved+# past the vendored blenlib/DNA (MutableCStr, ListBaseT methods, enum types) and+# the rest needs the asset system, BLO, ImBuf thumbnails and WM operators.+# The running port is kit/intern/kit_filebrowser.c ("filebrowser" node), which+# names the upstream function behind each part; diff against these files when+# syncing it.+set(UI_SPACE_FILE_STAGED+ space_file/ED_fileselect.hh+ space_file/file_intern.hh+ space_file/filelist.hh+ space_file/fsmenu.hh+ space_file/fsmenu.cc+ space_file/fsmenu_system_unix.cc+ space_file/fsmenu_system_win32.cc+ space_file/fsmenu_system_macos.mm+ space_file/folder_history.cc+ space_file/file_draw.cc+ space_file/file_ops.cc+ space_file/file_panels.cc+ space_file/file_utils.cc+ space_file/file_context.cc+ space_file/filesel.cc+ space_file/space_file.cc+ space_file/filelist/filelist.cc+ space_file/filelist/filelist_filter.cc+ space_file/filelist/filelist_intern.hh+ space_file/filelist/filelist_readjob.cc+ space_file/filelist/filelist_readjob.hh+ space_file/filelist/filelist_readjob_common.cc+ space_file/filelist/filelist_readjob_directories.cc+ space_file/filelist/filelist_sort.cc+)diff --git a/ui/space_file/ED_fileselect.hh b/ui/space_file/ED_fileselect.hhnew file mode 100644index 0000000..6ea78ca--- /dev/null+++ b/ui/space_file/ED_fileselect.hh@@ -0,0 +1,279 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup editors+ */++#pragma once++#include <string>++#include "BLI_vector.hh"++#include "DNA_uuid_types.h"++namespace blender {++struct ARegion;+struct FileAssetSelectParams;+struct FileDirEntry;+struct FileSelectParams;+struct FSMenu;+struct FSMenuEntry;+struct ID;+struct ScrArea;+struct SpaceFile;+struct bContext;+struct bScreen;+namespace ui {+struct Block;+}+struct wmOperator;+struct wmWindow;+struct wmWindowManager;+struct View2D;+struct rcti;+namespace asset_system {+class AssetLibrary;+}++enum eFileSortType : short;++#define FILE_LAYOUT_HOR 1+#define FILE_LAYOUT_VER 2++enum FileAttributeColumnType {+ COLUMN_NONE = -1,+ COLUMN_NAME = 0,+ COLUMN_DATETIME,+ COLUMN_SIZE,++ ATTRIBUTE_COLUMN_MAX+};++struct FileAttributeColumn {+ /** UI name for this column */+ const char *name;++ float width;+ /** The sort type to use when sorting by this column. */+ eFileSortType sort_type;++ /** Alignment of column texts, header text is always left aligned */+ int text_align; /* eFontStyle_Align */+};++struct FileLayout {+ /* view settings - XXX: move into its own struct. */+ int offset_top;+ /** Height of the header for the different FileAttributeColumn's. */+ int attribute_column_header_h;+ int prv_w;+ int prv_h;+ /** Extra padding to add above any files. Used for horizontal and column list views. */+ int list_padding_top;+ /** Width to draw the file's "tile" (matches the highlight background) with. `tile_border_x` will+ * be added before and after it as padding around the tile. */+ int tile_w;+ /** Height to draw the file's "tile" (matches the highlight background) with. `tile_border_y`+ * will be added above and below it as padding around the tile. */+ int tile_h;+ int tile_border_x;+ int tile_border_y;+ int prv_border_x;+ int prv_border_y;+ int rows;+ /**+ * Those are the major layout columns the files are distributed across,+ * not to be confused with `attribute_columns` array below.+ */+ int flow_columns;+ int width;+ int height;+ int flag;+ int dirty;+ int text_line_height;+ int text_lines_count;+ /**+ * The columns for each item (name, modification date/time, size).+ * Not to be confused with the `flow_columns` above.+ */+ FileAttributeColumn attribute_columns[ATTRIBUTE_COLUMN_MAX];++ /** When we change display size, we may have to update static strings like size of files. */+ short curr_size;+};++struct FileSelection {+ int first;+ int last;+};++/**+ * If needed, create and return the file select parameters for the active browse mode.+ */+FileSelectParams *ED_fileselect_ensure_active_params(SpaceFile *sfile);+/**+ * Get the file select parameters for the active browse mode.+ */+FileSelectParams *ED_fileselect_get_active_params(const SpaceFile *sfile);+FileSelectParams *ED_fileselect_get_file_params(const SpaceFile *sfile);+FileAssetSelectParams *ED_fileselect_get_asset_params(const SpaceFile *sfile);+bool ED_fileselect_is_local_asset_library(const SpaceFile *sfile);++void ED_fileselect_set_params_from_userdef(SpaceFile *sfile);+/**+ * Update the user-preference data for the file space. In fact, this also contains some+ * non-FileSelectParams data, but we can safely ignore this.+ */+void ED_fileselect_params_to_userdef(SpaceFile *sfile);++void ED_fileselect_init_layout(SpaceFile *sfile, ARegion *region);++FileLayout *ED_fileselect_get_layout(SpaceFile *sfile, ARegion *region);++int ED_fileselect_layout_numfiles(FileLayout *layout, ARegion *region);+int ED_fileselect_layout_offset(FileLayout *layout, int x, int y);+FileSelection ED_fileselect_layout_offset_rect(FileLayout *layout, const rcti *rect);++/**+ * Get the currently visible bounds of the layout in screen space. Matches View2D.mask minus the+ * top column-header row.+ */+void ED_fileselect_layout_maskrect(const FileLayout *layout, const View2D *v2d, rcti *r_rect);+bool ED_fileselect_layout_is_inside_pt(const FileLayout *layout, const View2D *v2d, int x, int y);+bool ED_fileselect_layout_isect_rect(const FileLayout *layout,+ const View2D *v2d,+ const rcti *rect,+ rcti *r_dst);+void ED_fileselect_layout_tilepos(const FileLayout *layout, int tile, int *x, int *y);++void ED_operatormacros_file();++void ED_fileselect_clear(wmWindowManager *wm, SpaceFile *sfile);+void ED_fileselect_clear_main_assets(wmWindowManager *wm, SpaceFile *sfile);++void ED_fileselect_exit(wmWindowManager *wm, SpaceFile *sfile);++bool ED_fileselect_is_file_browser(const SpaceFile *sfile);+bool ED_fileselect_is_asset_browser(const SpaceFile *sfile);+asset_system::AssetLibrary *ED_fileselect_active_asset_library_get(const SpaceFile *sfile);+ID *ED_fileselect_active_asset_get(const SpaceFile *sfile);++void ED_fileselect_activate_asset_catalog(const SpaceFile *sfile, bUUID catalog_id);++/**+ * Resolve this space's #eFileAssetImportMethod to the #eAssetImportMethod (note the different+ * type) to be used for the actual import of a specific asset.+ * - If the asset system dictates a certain import method, this will be returned.+ * - If the Asset Browser is set to follow the Preferences (#FILE_ASSET_IMPORT_FOLLOW_PREFS), the+ * asset system determines the import method (which is the default from the Preferences). -1 is+ * returned if the asset system doesn't specify a method (e.g. because the asset library doesn't+ * come from the Preferences).+ * - Otherwise, the Asset Browser determines (possibly overrides) the import method.+ *+ * \return -1 on error, for example when #FILE_ASSET_IMPORT_FOLLOW_PREFS was requested but the+ * active asset library reference couldn't be found in the preferences.+ */+int /* #eAssetImportMethod */ ED_fileselect_asset_import_method_get(const SpaceFile *sfile,+ const FileDirEntry *file);++/**+ * Activate and select the file that corresponds to the given ID.+ * Pass deferred=true to wait for the next refresh before activating.+ */+void ED_fileselect_activate_by_id(SpaceFile *sfile, ID *asset_id, bool deferred);++void ED_fileselect_deselect_all(SpaceFile *sfile);+void ED_fileselect_activate_by_relpath(SpaceFile *sfile, const char *relative_path);++void ED_fileselect_window_params_get(const wmWindow *win, int r_win_size[2], bool *r_is_maximized);++/**+ * Return the File Browser area in which \a file_operator is active.+ */+ScrArea *ED_fileselect_handler_area_find(const wmWindow *win, const wmOperator *file_operator);+/**+ * Check if there is any area in \a win that acts as a modal File Browser (#SpaceFile.op is set)+ * and return it.+ */+ScrArea *ED_fileselect_handler_area_find_any_with_op(const wmWindow *win);++/**+ * If filepath property is not set on the operator, sets it to+ * the blend file path (or untitled if file is not saved yet) with the given extension.+ */+void ED_fileselect_ensure_default_filepath(bContext *C, wmOperator *op, const char *extension);++Vector<std::string> ED_fileselect_selected_files_full_paths(const SpaceFile *sfile);++/* TODO: Maybe we should move this to BLI?+ * On the other hand, it's using defines from space-file area, so not sure... */+int ED_path_extension_type(const char *path);+int ED_file_extension_icon(const char *path);+int ED_file_icon(const FileDirEntry *file);++void ED_file_read_bookmarks();++/**+ * Support updating the directory even when this isn't the active space+ * needed so RNA properties update function isn't context sensitive, see #70255.+ */+void ED_file_change_dir_ex(bContext *C, ScrArea *area);+void ED_file_change_dir(bContext *C);++void ED_file_path_button(bScreen *screen,+ SpaceFile *sfile,+ FileSelectParams *params,+ ui::Block *block);++/* File menu stuff */++/* FSMenuEntry's without paths indicate separators */+struct FSMenuEntry {+ FSMenuEntry *next;++ char *path;+ char name[/*FILE_MAXFILE*/ 256];+ short save;+ int icon;+};++enum FSMenuCategory {+ FS_CATEGORY_SYSTEM,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FS_CATEGORY_BOOKMARKS,+ FS_CATEGORY_RECENT,+ /** For internal use, a list of known paths that are used to match paths to icons and names. */+ FS_CATEGORY_OTHER,+};++enum FSMenuInsert {+ FS_INSERT_SORTED = (1 << 0),+ FS_INSERT_SAVE = (1 << 1),+ /** moves the item to the front of the list when its not already there */+ FS_INSERT_FIRST = (1 << 2),+ /** just append to preserve delivered order */+ FS_INSERT_LAST = (1 << 3),+};++FSMenu *ED_fsmenu_get();+FSMenuEntry *ED_fsmenu_get_category(FSMenu *fsmenu, FSMenuCategory category);+void ED_fsmenu_set_category(FSMenu *fsmenu, FSMenuCategory category, FSMenuEntry *fsm_head);++int ED_fsmenu_get_nentries(FSMenu *fsmenu, FSMenuCategory category);++FSMenuEntry *ED_fsmenu_get_entry(FSMenu *fsmenu, FSMenuCategory category, int idx);++char *ED_fsmenu_entry_get_path(FSMenuEntry *fsentry);+void ED_fsmenu_entry_set_path(FSMenuEntry *fsentry, const char *path);++char *ED_fsmenu_entry_get_name(FSMenuEntry *fsentry);+void ED_fsmenu_entry_set_name(FSMenuEntry *fsentry, const char *name);++int ED_fsmenu_entry_get_icon(FSMenuEntry *fsentry);+void ED_fsmenu_entry_set_icon(FSMenuEntry *fsentry, int icon);++} // namespace blenderdiff --git a/ui/space_file/file_context.cc b/ui/space_file/file_context.ccnew file mode 100644index 0000000..b0cbf73--- /dev/null+++ b/ui/space_file/file_context.cc@@ -0,0 +1,146 @@+/* SPDX-FileCopyrightText: 2023 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "BKE_context.hh"++#include "ED_fileselect.hh"+#include "ED_screen.hh"++#include "RNA_prototypes.hh"++#include "file_intern.hh"+#include "filelist.hh"++namespace blender {++const char *file_context_dir[] = {+ "active_file",+ "selected_files",+ "asset_library_reference",+ "asset",+ "selected_assets",+ "id",+ "selected_ids",+ nullptr,+};++int /*eContextResult*/ file_context(const bContext *C,+ const char *member,+ bContextDataResult *result)+{+ bScreen *screen = CTX_wm_screen(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ BLI_assert(!ED_area_is_global(CTX_wm_area(C)));++ if (CTX_data_dir(member)) {+ CTX_data_dir_set(result, file_context_dir);+ return CTX_RESULT_OK;+ }++ /* The following member checks return file-list data, check if that needs refreshing first. */+ if (file_main_region_needs_refresh_before_draw(sfile)) {+ return CTX_RESULT_NO_DATA;+ }++ if (CTX_data_equals(member, "active_file")) {+ FileDirEntry *file = filelist_file(sfile->files, params->active_file);+ if (file == nullptr) {+ return CTX_RESULT_NO_DATA;+ }++ CTX_data_pointer_set(result, &screen->id, RNA_FileSelectEntry, file);+ return CTX_RESULT_OK;+ }+ if (CTX_data_equals(member, "selected_files")) {+ const int num_files_filtered = filelist_files_ensure(sfile->files);++ for (int file_index = 0; file_index < num_files_filtered; file_index++) {+ if (filelist_entry_is_selected(sfile->files, file_index)) {+ FileDirEntry *entry = filelist_file(sfile->files, file_index);+ CTX_data_list_add(result, &screen->id, RNA_FileSelectEntry, entry);+ }+ }++ CTX_data_type_set(result, ContextDataType::Collection);+ return CTX_RESULT_OK;+ }++ if (CTX_data_equals(member, "asset_library_reference")) {+ FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);+ if (!asset_params) {+ return CTX_RESULT_NO_DATA;+ }++ CTX_data_pointer_set(+ result, &screen->id, RNA_AssetLibraryReference, &asset_params->asset_library_ref);+ return CTX_RESULT_OK;+ }++ if (CTX_data_equals(member, "asset")) {+ FileDirEntry *file = filelist_file(sfile->files, params->active_file);+ if (file == nullptr || !file->asset) {+ return CTX_RESULT_NO_DATA;+ }++ CTX_data_pointer_set(result, nullptr, RNA_AssetRepresentation, file->asset);+ return CTX_RESULT_OK;+ }+ if (CTX_data_equals(member, "selected_assets")) {+ const int num_files_filtered = filelist_files_ensure(sfile->files);++ for (int file_index = 0; file_index < num_files_filtered; file_index++) {+ if (filelist_entry_is_selected(sfile->files, file_index)) {+ FileDirEntry *entry = filelist_file(sfile->files, file_index);+ if (entry->asset) {+ CTX_data_list_add(result, nullptr, RNA_AssetRepresentation, entry->asset);+ }+ }+ }++ CTX_data_type_set(result, ContextDataType::Collection);+ return CTX_RESULT_OK;+ }+ if (CTX_data_equals(member, "id")) {+ const FileDirEntry *file = filelist_file(sfile->files, params->active_file);+ if (file == nullptr) {+ return CTX_RESULT_NO_DATA;+ }++ ID *id = filelist_file_get_id(file);+ if (id == nullptr) {+ return CTX_RESULT_NO_DATA;+ }++ CTX_data_id_pointer_set(result, id);+ return CTX_RESULT_OK;+ }+ if (CTX_data_equals(member, "selected_ids")) {+ const int num_files_filtered = filelist_files_ensure(sfile->files);++ for (int file_index = 0; file_index < num_files_filtered; file_index++) {+ if (!filelist_entry_is_selected(sfile->files, file_index)) {+ continue;+ }+ ID *id = filelist_entry_get_id(sfile->files, file_index);+ if (!id) {+ continue;+ }++ CTX_data_id_list_add(result, id);+ }++ CTX_data_type_set(result, ContextDataType::Collection);+ return CTX_RESULT_OK;+ }++ return CTX_RESULT_MEMBER_NOT_FOUND;+}++} // namespace blenderdiff --git a/ui/space_file/file_draw.cc b/ui/space_file/file_draw.ccnew file mode 100644index 0000000..2087f47--- /dev/null+++ b/ui/space_file/file_draw.cc@@ -0,0 +1,2253 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include <algorithm>+#include <cerrno>+#include <cstring>+#include <string>++#include <fmt/format.h>++#include "BLI_rect.h"+#include "DNA_space_enums.h"+#include "ED_asset_menu_utils.hh"+#include "MEM_guardedalloc.h"++#include "AS_asset_library.hh"+#include "AS_asset_representation.hh"+#include "AS_remote_library.hh"++#include "BLI_fileops.hh"+#include "BLI_fileops_types.h"+#include "BLI_listbase.h"+#include "BLI_math_color.h"+#include "BLI_math_vector.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_string_utf8.h"+#include "BLI_utildefines.h"++#ifdef WIN32+# include "BLI_winstuff.hh"+#endif++#include "BIF_glutil.hh"++#include "BKE_blendfile.hh"+#include "BKE_context.hh"+#include "BKE_global.hh"+#include "BKE_icons.hh"+#include "BKE_preferences.h"+#include "BKE_report.hh"++#include "BLO_readfile.hh"++#include "BLT_date_string.hh"+#include "BLT_lang.hh"+#include "BLT_translation.hh"++#include "BLF_api.hh"++#include "IMB_imbuf.hh"+#include "IMB_imbuf_types.hh"+#include "IMB_metadata.hh"+#include "IMB_thumbs.hh"++#include "DNA_userdef_types.h"+#include "DNA_windowmanager_types.h"++#include "RNA_access.hh"+#include "RNA_prototypes.hh"++#include "ED_asset.hh"+#include "ED_fileselect.hh"+#include "ED_screen.hh"++#include "UI_interface.hh"+#include "UI_interface_c.hh"+#include "UI_interface_icons.hh"+#include "UI_interface_layout.hh"+#include "UI_resources.hh"+#include "UI_view2d.hh"++#include "WM_api.hh"+#include "WM_types.hh"++#include "GPU_immediate.hh"+#include "GPU_immediate_util.hh"+#include "GPU_state.hh"++#include "file_banner.hh"+#include "filelist.hh"++#include "file_intern.hh" /* own include */++namespace blender {++using RemoteLibraryLoadingStatus = asset_system::RemoteLibraryLoadingStatus;++void ED_file_path_button(bScreen *screen,+ SpaceFile *sfile,+ FileSelectParams *params,+ ui::Block *block)+{+ ui::Button *but;++ BLI_assert_msg(params != nullptr,+ "File select parameters not set. The caller is expected to check this.");+ BLI_assert(params == sfile->params || params == &sfile->asset_params->base_params);++ PointerRNA space_ptr = RNA_pointer_create_discrete(&screen->id, RNA_SpaceFileBrowser, sfile);+ PointerRNA params_rna_ptr = RNA_pointer_create_with_parent(+ space_ptr, RNA_FileSelectParams, params);++ /* callbacks for operator check functions */+ block_func_set(block, file_draw_check_cb, nullptr, nullptr);++ but = uiDefButR(block,+ ui::ButtonType::Text,+ "",+ 0,+ 0,+ UI_UNIT_X * 10,+ UI_UNIT_Y,+ ¶ms_rna_ptr,+ "directory",+ 0,+ 0.0f,+ float(FILE_MAX),+ TIP_("File path"));++ BLI_assert(!button_flag_is_set(but, ui::BUT_UNDO));+ BLI_assert(!but_is_utf8(but));++ button_func_complete_set(but, autocomplete_directory, nullptr);+ button_funcN_set(but, file_directory_enter_handle, nullptr, but, nullptr, nullptr);+ /* Keep editing after Tab completes a directory. */+ button_flag_enable(but, ui::BUT_TEXTEDIT_AUTOCOMPLETE_KEEP_ACTIVE);++ /* TODO: directory editing is non-functional while a library is loaded+ * until this is properly supported just disable it. */+ if (sfile && sfile->files && filelist_lib(sfile->files)) {+ button_flag_enable(but, ui::BUT_DISABLED);+ }++ /* clear func */+ block_func_set(block, nullptr, nullptr, nullptr);+}++struct FileTooltipData {+ const SpaceFile *sfile;+ const FileDirEntry *file;+};++static FileTooltipData *file_tooltip_data_create(const SpaceFile *sfile, const FileDirEntry *file)+{+ FileTooltipData *data = MEM_new_uninitialized<FileTooltipData>(__func__);+ data->sfile = sfile;+ data->file = file;+ return data;+}++static void file_draw_tooltip_custom_func(bContext & /*C*/,+ ui::TooltipData &tip,+ ui::Button * /*but*/,+ void *argN)+{+ FileTooltipData *file_data = static_cast<FileTooltipData *>(argN);+ const SpaceFile *sfile = file_data->sfile;+ const FileList *files = sfile->files;+ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const FileDirEntry *file = file_data->file;++ BLI_assert_msg(!file->asset, "Asset tooltip should never be overridden here.");++ /* Check the FileDirEntry first to see if the preview is already loaded. */+ ImBuf *thumb = filelist_file_get_preview_image(file);++ /* Only free if it is loaded later. */+ bool free_imbuf = (thumb == nullptr);++ tooltip_text_field_add(tip, file->name, {}, ui::TIP_STYLE_HEADER, ui::TIP_LC_MAIN);+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);++ if (!(file->typeflag & FILE_TYPE_BLENDERLIB)) {++ char full_path[FILE_MAX_LIBEXTRA];+ filelist_file_get_full_path(files, file, full_path);++ if (params->recursion_level > 0) {+ char root[FILE_MAX];+ BLI_path_split_dir_part(full_path, root);+ tooltip_text_field_add(tip, root, {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_NORMAL);+ }++ if (file->redirection_path) {+ tooltip_text_field_add(+ tip,+ fmt::format(fmt::runtime(TIP_("Link target: {}")), file->redirection_path),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ }+ if (file->attributes & FILE_ATTR_OFFLINE) {+ tooltip_text_field_add(+ tip, TIP_("This file is offline"), {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_ALERT);+ }+ if (file->attributes & FILE_ATTR_READONLY) {+ tooltip_text_field_add(+ tip, TIP_("This file is read-only"), {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_ALERT);+ }+ if (file->attributes & (FILE_ATTR_SYSTEM | FILE_ATTR_RESTRICTED)) {+ tooltip_text_field_add(tip,+ TIP_("This is a restricted system file"),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_ALERT);+ }++ if (file->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {+ char version_str[128] = {0};+ if (!thumb) {+ /* Load the thumbnail from cache if existing, but don't create if not. */+ thumb = IMB_thumb_read(full_path, THB_LARGE);+ }+ if (thumb) {+ /* Look for version in existing thumbnail if available. */+ IMB_metadata_get_field(thumb->metadata(), "Thumb::Blender::Version", version_str);+ }++ if (!version_str[0] && !(file->attributes & FILE_ATTR_OFFLINE)) {+ /* Load Blender version directly from the file. */+ short version = BLO_version_from_file(full_path);+ if (version != 0) {+ SNPRINTF_UTF8(version_str, "%d.%01d", version / 100, version % 100);+ }+ }++ if (version_str[0]) {+ tooltip_text_field_add(tip,+ fmt::format("Blender {}", version_str),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);+ }+ }+ else if (file->typeflag & FILE_TYPE_IMAGE) {+ if (!thumb) {+ /* Load the thumbnail from cache if existing, create if not. */+ thumb = IMB_thumb_manage(full_path, THB_LARGE, THB_SOURCE_IMAGE);+ }+ if (thumb) {+ char value1[128];+ char value2[128];+ if (IMB_metadata_get_field(thumb->metadata(), "Thumb::Image::Width", value1) &&+ IMB_metadata_get_field(thumb->metadata(), "Thumb::Image::Height", value2))+ {+ tooltip_text_field_add(tip,+ fmt::format("{} \u00D7 {}", value1, value2),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);+ }+ }+ }+ else if (file->typeflag & FILE_TYPE_MOVIE) {+ if (!thumb) {+ /* This could possibly take a while. */+ thumb = IMB_thumb_manage(full_path, THB_LARGE, THB_SOURCE_MOVIE);+ }+ if (thumb) {+ char value1[128];+ char value2[128];+ char value3[128];+ if (IMB_metadata_get_field(thumb->metadata(), "Thumb::Video::Width", value1) &&+ IMB_metadata_get_field(thumb->metadata(), "Thumb::Video::Height", value2))+ {+ tooltip_text_field_add(tip,+ fmt::format("{} \u00D7 {}", value1, value2),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ }+ if (IMB_metadata_get_field(thumb->metadata(), "Thumb::Video::Frames", value1) &&+ IMB_metadata_get_field(thumb->metadata(), "Thumb::Video::FPS", value2) &&+ IMB_metadata_get_field(thumb->metadata(), "Thumb::Video::Duration", value3))+ {+ tooltip_text_field_add(+ tip,+ fmt::format(fmt::runtime(TIP_("{} Frames @ {} FPS")), value1, value2),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ tooltip_text_field_add(tip,+ fmt::format(fmt::runtime(TIP_("{} seconds")), value3),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);+ }+ }+ }+ else if (file->typeflag & FILE_TYPE_FTFONT) {+ float color[4];+ const bTheme *btheme = ui::theme::theme_get();+ rgba_uchar_to_float(color, btheme->tui.wcol_tooltip.text);+ thumb = IMB_font_preview(file->redirection_path ? file->redirection_path : full_path,+ 512 * UI_SCALE_FAC,+ color,+ TIP_("The five boxing wizards jump quickly! 0123456789"));+ free_imbuf = true;+ }++ const time_t file_time = (time_t)file->time;+ const std::tm mod_time = date_string::localtime_safe(file_time);+ const time_t ts_now = time(nullptr);+ const std::tm now = date_string::localtime_safe(ts_now);+ const char *lang = BLT_lang_get();+ std::string modified_s = blender::date_string::datetime(mod_time,+ lang,+ date_string::DateFormat(U.date_format),+ date_string::TimeFormat(U.time_format),+ &now,+ TIP_("Today"),+ TIP_("Yesterday"));+ tooltip_text_field_add(tip,+ fmt::format(fmt::runtime(TIP_("Modified: {}")), modified_s),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);++ if (!(file->typeflag & FILE_TYPE_DIR) && file->size > 0) {+ char size[16];+ BLI_filelist_entry_size_to_string(nullptr, file->size, false, size);+ if (file->size < 10000) {+ char size_full[BLI_STR_FORMAT_UINT64_GROUPED_SIZE];+ BLI_str_format_uint64_grouped(size_full, file->size);+ tooltip_text_field_add(+ tip,+ fmt::format(fmt::runtime(TIP_("Size: {} ({} bytes)")), size, size_full),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ }+ else {+ tooltip_text_field_add(tip,+ fmt::format(fmt::runtime(TIP_("Size: {}")), size),+ {},+ ui::TIP_STYLE_NORMAL,+ ui::TIP_LC_NORMAL);+ }+ }+ }++ if (thumb && file->typeflag & FILE_TYPE_FTFONT) {+ const float scale = (512.0f * UI_SCALE_FAC) / float(std::max(thumb->x, thumb->y));+ ui::TooltipImage image_data;+ image_data.ibuf = thumb;+ image_data.width = short(float(thumb->x) * scale);+ image_data.height = short(float(thumb->y) * scale);+ image_data.background = ui::TooltipImageBackground::None;+ image_data.premultiplied = false;+ image_data.text_color = true;+ image_data.border = false;+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);+ tooltip_image_field_add(tip, image_data);+ }+ else if (thumb && params->display != FILE_IMGDISPLAY) {+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);+ tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);++ ui::TooltipImage image_data;+ float scale = (96.0f * UI_SCALE_FAC) / float(std::max(thumb->x, thumb->y));+ image_data.ibuf = thumb;+ image_data.width = short(float(thumb->x) * scale);+ image_data.height = short(float(thumb->y) * scale);+ image_data.border = true;+ image_data.background = ui::TooltipImageBackground::Checkerboard_Themed;+ image_data.premultiplied = true;+ tooltip_image_field_add(tip, image_data);+ }++ if (thumb && free_imbuf) {+ IMB_freeImBuf(thumb);+ }+}++static void file_draw_asset_tooltip_custom_func(bContext & /*C*/,+ ui::TooltipData &tip,+ ui::Button * /*but*/,+ void *argN)+{+ const auto *asset = static_cast<asset_system::AssetRepresentation *>(argN);+ ed::asset::asset_tooltip(*asset, tip);+}++static void draw_tile_background(const rcti *draw_rect, bool is_selected, bool is_highlighted)+{+ uiWidgetColors wcol = ui::theme::theme_get()->tui.wcol_list_item;+ float color_background_1[4], color_background_2[4], color_outline[4];+ const float roundness = wcol.roundness * U.widget_unit;+ rctf draw_rect_fl;+ BLI_rctf_rcti_copy(&draw_rect_fl, draw_rect);++ if (is_selected) {+ rgba_uchar_to_float(color_background_1, wcol.inner_sel);+ rgba_uchar_to_float(color_outline, wcol.outline_sel);+ std::swap(wcol.shadetop, wcol.shadedown);+ }+ else {+ rgba_uchar_to_float(color_background_1, wcol.inner);+ rgba_uchar_to_float(color_outline, wcol.outline);+ }++ /* Gradient fill, if list_item is set to shaded in the theme. */+ if (wcol.shaded == 0) {+ copy_v4_v4(color_background_2, color_background_1);+ }+ else {+ constexpr float inv_255 = 1.0f / 255.0f;+ float color_base[3];+ copy_v3_v3(color_base, color_background_1);++ for (int i = 0; i < 3; i++) {+ color_background_1[i] = std::clamp(color_base[i] + wcol.shadetop * inv_255, 0.0f, 1.0f);+ color_background_2[i] = std::clamp(color_base[i] + wcol.shadedown * inv_255, 0.0f, 1.0f);+ }+ }++ /* Hover effect. Force opacity of inner color at least 10%. */+ if (is_highlighted) {+ color_background_1[3] = std::min(color_background_1[3] + 0.1f, 1.0f);+ }++ color_background_2[3] = color_background_1[3];++ draw_roundbox_corner_set(ui::CNR_ALL);+ ui::draw_roundbox_4fv_ex(+ &draw_rect_fl, color_background_1, color_background_2, 1.0f, color_outline, 1.0f, roundness);+}++static void file_but_enable_drag(ui::Button *but,+ const SpaceFile *sfile,+ const FileDirEntry *file,+ const char *path,+ const ImBuf *preview_image,+ int icon,+ float scale)+{+ ID *id;++ if ((id = filelist_file_get_id(file))) {+ button_drag_set_id(but, id);+ if (preview_image) {+ button_drag_attach_image(but, preview_image, scale);+ }+ }+ else if (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS &&+ (file->typeflag & FILE_TYPE_ASSET) != 0)+ {+ const int import_method = ED_fileselect_asset_import_method_get(sfile, file);+ BLI_assert(import_method > -1);+ if (import_method > -1) {+ AssetImportSettings import_settings{};+ import_settings.method = eAssetImportMethod(import_method);+ import_settings.use_instance_collections =+ (sfile->asset_params->import_flags &+ (ELEM(import_method, ASSET_IMPORT_LINK, ASSET_IMPORT_PACK) ?+ FILE_ASSET_IMPORT_INSTANCE_COLLECTIONS_ON_LINK :+ FILE_ASSET_IMPORT_INSTANCE_COLLECTIONS_ON_APPEND)) != 0;++ button_drag_set_asset(but, file->asset, import_settings, icon, file->preview_icon_id);+ }+ }+ else if (preview_image) {+ button_drag_set_image(but, path, icon, preview_image, scale);+ }+ else {+ /* path is no more static, cannot give it directly to but... */+ button_drag_set_path(but, path);+ }+}++static void file_but_tooltip_func_set(const SpaceFile *sfile,+ const FileDirEntry *file,+ ui::Button *but)+{+ if (file->asset) {+ button_func_tooltip_custom_set(but, file_draw_asset_tooltip_custom_func, file->asset, nullptr);+ }+ else {+ button_func_tooltip_custom_set(+ but, file_draw_tooltip_custom_func, file_tooltip_data_create(sfile, file));+ }+}++static ui::Button *file_add_icon_but(const SpaceFile *sfile,+ ui::Block *block,+ const char * /*path*/,+ const FileDirEntry *file,+ const rcti *tile_draw_rect,+ int icon,+ int width,+ int height,+ int padx,+ bool dimmed)+{+ ui::Button *but;++ const int x = tile_draw_rect->xmin + padx;+ const int y = tile_draw_rect->ymin ++ round_fl_to_int((BLI_rcti_size_y(tile_draw_rect) - height) / 2.0f);++ if (icon < BIFICONID_LAST_STATIC) {+ /* Small built-in icon. Draw centered in given width. */+ but = uiDefIconBut(block,+ ui::ButtonType::Label,+ icon,+ x,+ y,+ width,+ height,+ nullptr,+ 0.0f,+ 0.0f,+ std::nullopt);+ /* Center the icon. */+ button_drawflag_disable(but, ui::BUT_ICON_LEFT);+ }+ else {+ /* Larger preview icon. Fills available width/height. */+ but = uiDefIconPreviewBut(block,+ ui::ButtonType::Label,+ icon,+ x,+ y,+ width,+ height,+ nullptr,+ 0.0f,+ 0.0f,+ std::nullopt);+ }+ button_label_alpha_factor_set(but, dimmed ? 0.3f : 1.0f);+ file_but_tooltip_func_set(sfile, file, but);++ return but;+}++static ui::Button *file_add_overlay_icon_but(ui::Block *block, int pos_x, int pos_y, int icon)+{+ ui::Button *but = uiDefIconBut(block,+ ui::ButtonType::Label,+ icon,+ pos_x,+ pos_y,+ ICON_DEFAULT_WIDTH_SCALE,+ ICON_DEFAULT_HEIGHT_SCALE,+ nullptr,+ 0.0f,+ 0.0f,+ std::nullopt);+ /* Otherwise a left hand padding will be added. */+ button_drawflag_disable(but, ui::BUT_ICON_LEFT);+ button_label_alpha_factor_set(but, 0.6f);+ const uchar light[4] = {255, 255, 255, 255};+ button_color_set(but, light);++ return but;+}++static void file_draw_string(int sx,+ int sy,+ const char *string,+ float width,+ int height,+ ui::FontStyleAlign align,+ const uchar col[4])+{+ uiFontStyle fs;+ rcti rect;+ char filename[FILE_MAXFILE];++ if (string[0] == '\0' || width < 1) {+ return;+ }++ const uiStyle *style = ui::style_get();+ fs = style->widget;++ STRNCPY(filename, string);+ ui::text_clip_middle_ex(&fs, filename, width, UI_ICON_SIZE, '\0');++ /* no text clipping needed, fontstyle_draw does it but is a bit too strict+ * (for buttons it works) */+ rect.xmin = sx;+ rect.xmax = sx + round_fl_to_int(width);+ rect.ymin = sy - height;+ rect.ymax = sy;++ ui::FontStyleDrawParams font_style_params{};+ font_style_params.align = align;++ fontstyle_draw(&fs, &rect, filename, sizeof(filename), col, &font_style_params);+}++/**+ * Draw the string over at max \a line_count lines, clipping in the middle so it fits.+ */+static void file_draw_string_mulitline_clipped(const rcti *rect,+ const char *string,+ ui::FontStyleAlign align,+ const uchar col[4])+{+ if (string[0] == '\0' || BLI_rcti_size_x(rect) < 1) {+ return;+ }++ const uiStyle *style = ui::style_get();+ uiFontStyle fs = style->widget;++ fontstyle_draw_multiline_clipped(&fs, rect, string, col, align);+}++static rcti file_measure_string_multiline(const StringRef string, const int wrap_width)+{+ if (string[0] == '\0' || wrap_width < 1) {+ return {.xmin = 0, .xmax = 0, .ymin = 0, .ymax = 0};+ }++ const uiStyle *style = ui::style_get();+ const int font_id = style->widget.uifont_id;++ rcti textbox;+ BLF_wordwrap(font_id,+ wrap_width,+ BLFWrapMode::Typographical | BLFWrapMode::Path | BLFWrapMode::HardLimit);+ BLF_enable(font_id, BLF_WORD_WRAP);+ BLF_boundbox(font_id, string.data(), string.size(), &textbox);+ BLF_disable(font_id, BLF_WORD_WRAP);++ return textbox;+}++/**+ * \param r_sx, r_sy: The lower right corner of the last line drawn, plus the height of the last+ * line. This is the cursor position on completion to allow drawing more text+ * behind that.+ */+static void file_draw_string_multiline(int sx,+ int sy,+ const StringRef string,+ int wrap_width,+ int line_height,+ const uchar text_col[4],+ int *r_sx,+ int *r_sy)+{+ rcti rect;++ if (string[0] == '\0' || wrap_width < 1) {+ return;+ }++ const uiStyle *style = ui::style_get();+ const rcti textbox = file_measure_string_multiline(string, wrap_width);++ /* no text clipping needed, fontstyle_draw does it but is a bit too strict+ * (for buttons it works) */+ rect.xmin = sx;+ rect.xmax = sx + wrap_width;+ /* Need to increase the clipping rect by one more line, since the #fontstyle_draw_ex() will+ * actually start drawing at (ymax - line-height). */+ rect.ymin = sy - BLI_rcti_size_y(&textbox) - line_height;+ rect.ymax = sy;++ ui::FontStyleDrawParams font_style_params{};+ font_style_params.align = ui::UI_STYLE_TEXT_LEFT;+ font_style_params.word_wrap = true;++ ResultBLF result;+ fontstyle_draw_ex(&style->widget,+ &rect,+ string.data(),+ string.size(),+ text_col,+ &font_style_params,+ nullptr,+ nullptr,+ &result);+ if (r_sx) {+ *r_sx = result.width;+ }+ if (r_sy) {+ *r_sy = rect.ymin + line_height;+ }+}++static std::tuple<int, int, float> preview_image_scaled_dimensions_get(const int image_width,+ const int image_height,+ const FileLayout &layout)+{+ const float ui_imbx = image_width * UI_SCALE_FAC;+ const float ui_imby = image_height * UI_SCALE_FAC;++ float scale;+ float scaledx, scaledy;+ if (((ui_imbx > layout.prv_w) || (ui_imby > layout.prv_h)) ||+ ((ui_imbx < layout.prv_w) || (ui_imby < layout.prv_h)))+ {+ if (image_width > image_height) {+ scaledx = float(layout.prv_w);+ scaledy = (float(image_height) / float(image_width)) * layout.prv_w;+ scale = scaledx / image_width;+ }+ else {+ scaledy = float(layout.prv_h);+ scaledx = (float(image_width) / float(image_height)) * layout.prv_h;+ scale = scaledy / image_height;+ }+ }+ else {+ scaledx = ui_imbx;+ scaledy = ui_imby;+ scale = UI_SCALE_FAC;+ }++ return std::make_tuple(int(scaledx), int(scaledy), scale);+}++static void file_add_preview_drag_but(const SpaceFile *sfile,+ ui::Block *block,+ const FileDirEntry *file,+ const char *path,+ const rcti *tile_draw_rect,+ const int file_type_icon)+{+ /* Invisible button for dragging. */+ ui::Button *but = uiDefBut(block,+ ui::ButtonType::Label,+ "",+ tile_draw_rect->xmin,+ tile_draw_rect->ymin,+ BLI_rcti_size_x(tile_draw_rect),+ BLI_rcti_size_y(tile_draw_rect),+ nullptr,+ 0.0,+ 0.0,+ std::nullopt);++ const ImBuf *preview_image = filelist_file_get_preview_image(file);+ const ImBuf *drag_image = (preview_image || file->asset) ?+ preview_image :+ /* Larger directory or document icon. */+ filelist_geticon_special_file_image_ex(file);+ const float scale = drag_image ? (PREVIEW_DRAG_DRAW_SIZE * UI_SCALE_FAC) /+ std::max(drag_image->x, drag_image->y) :+ 1.0f;+ file_but_enable_drag(but, sfile, file, path, drag_image, file_type_icon, scale);+ file_but_tooltip_func_set(sfile, file, but);+}++static void file_add_asset_download_but(ui::Block *block,+ const FileLayout *layout,+ const FileDirEntry *file,+ const rcti *tile_draw_rect)+{+ const int preview_center_x = BLI_rcti_cent_x(tile_draw_rect);+ const int preview_center_y = tile_draw_rect->ymax - layout->tile_border_y - layout->prv_h * 0.5f;+ const int icon_width = ICON_DEFAULT_WIDTH_SCALE * 2.0f;+ const int icon_height = ICON_DEFAULT_HEIGHT_SCALE * 2.0f;+ const int icon_x = preview_center_x - icon_width * 0.5f;+ const int icon_y = preview_center_y - icon_height * 0.5f;++ ui::Button *but = uiDefIconButO(block,+ ui::ButtonType::But,+ "ASSET_OT_asset_download",+ wm::OpCallContext::ExecDefault,+ ICON_DOWNLOAD,+ icon_x,+ icon_y,+ icon_width,+ icon_height,+ std::nullopt);+ PointerRNA *opptr = ui::button_operator_ptr_ensure(but);+ ed::asset::operator_asset_reference_props_set(*file->asset, *opptr);+ ui::button_icon_scale_set(but, 1.5f);+ ui::button_pushbutton_draw_as_overlay_set(but, true);+}++static void file_draw_preview(const FileDirEntry *file,+ const rcti *tile_draw_rect,+ const IconBufferRef &preview,+ FileLayout *layout,+ const bool dimmed)+{+ const auto [scaled_width, scaled_height, scale] = preview_image_scaled_dimensions_get(+ preview.width, preview.height, *layout);++ /* Additional offset to keep the scaled image centered. Difference between maximum+ * width/height and the actual width/height, divided by two for centering. */+ const float ofs_x = (float(layout->prv_w) - float(scaled_width)) / 2.0f;+ const float ofs_y = (float(layout->prv_h) - float(scaled_height)) / 2.0f;+ const int xmin = tile_draw_rect->xmin + layout->prv_border_x + int(ofs_x + 0.5f);+ const int ymin = tile_draw_rect->ymax - layout->prv_border_y - layout->prv_h + int(ofs_y + 0.5f);++ GPU_blend(GPU_BLEND_ALPHA);++ float document_img_col[4] = {1.0f, 1.0f, 1.0f, 1.0f};+ if (file->typeflag & FILE_TYPE_FTFONT) {+ ui::theme::get_color_4fv(TH_TEXT, document_img_col);+ }+ if (dimmed) {+ document_img_col[3] *= 0.3f;+ }++ if (ELEM(file->typeflag, FILE_TYPE_IMAGE, FILE_TYPE_OBJECT_IO)) {+ /* Draw checker pattern behind image previews in case they have transparency. */+ imm_draw_box_checker_2d(+ float(xmin), float(ymin), float(xmin + scaled_width), float(ymin + scaled_height));+ }++ if (file->typeflag & FILE_TYPE_BLENDERLIB) {+ /* Datablock preview images use premultiplied alpha. */+ GPU_blend(GPU_BLEND_ALPHA_PREMULT);+ }++ const gpu::TextureFormat format = gpu::TextureFormat::UNORM_8_8_8_8;+ BLI_assert_msg(preview.channels == 4, "preview images are expected to be 4 channels");++ PixelBitmapDrawer drawer(GPU_SHADER_3D_IMAGE_COLOR);+ drawer.draw(float(xmin),+ float(ymin),+ preview.width,+ preview.height,+ format,+ true,+ preview.buffer.data(),+ scale,+ scale,+ document_img_col);++ const bool show_outline = (file->typeflag & (FILE_TYPE_IMAGE | FILE_TYPE_OBJECT_IO |+ FILE_TYPE_MOVIE | FILE_TYPE_BLENDER));+ /* Contrasting outline around some preview types. */+ if (show_outline) {+ GPU_blend(GPU_BLEND_ALPHA);++ GPUVertFormat *format = immVertexFormat();+ uint pos = GPU_vertformat_attr_add(format, "pos", gpu::VertAttrType::SFLOAT_32_32);+ immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);+ float border_color[4] = {1.0f, 1.0f, 1.0f, 0.15f};+ float bgcolor[4];+ ui::theme::get_color_4fv(TH_BACK, bgcolor);+ if (srgb_to_grayscale(bgcolor) > 0.5f) {+ border_color[0] = 0.0f;+ border_color[1] = 0.0f;+ border_color[2] = 0.0f;+ }+ immUniformColor4fv(border_color);+ imm_draw_box_wire_2d(pos,+ float(xmin),+ float(ymin),+ float(xmin + scaled_width + 1),+ float(ymin + scaled_height + 1));+ immUnbindProgram();+ }++ GPU_blend(GPU_BLEND_NONE);+}++static void file_draw_special_image(const FileDirEntry *file,+ const rcti *tile_draw_rect,+ const int file_type_icon,+ const float icon_aspect,+ const FileLayout *layout,+ const bool dimmed,+ eDirEntry_SelectFlag file_selflag)+{+ float document_img_col[4] = {1.0f, 1.0f, 1.0f, 1.0f};+ const bool selected = file_selflag & FILE_SEL_SELECTED;+ if (file->typeflag & FILE_TYPE_DIR) {+ ui::theme::get_color_4fv(TH_ICON_FOLDER, document_img_col);+ }+ else {+ const uiWidgetColors wcol = ui::theme::theme_get()->tui.wcol_list_item;+ rgba_uchar_to_float(document_img_col, !selected ? wcol.text : wcol.text_sel);+ }++ if (dimmed) {+ document_img_col[3] *= 0.3f;+ }++ GPU_blend(GPU_BLEND_ALPHA);++ const int cent_x = tile_draw_rect->xmin + layout->prv_border_x + (layout->prv_w / 2.0f) + 0.5f;+ const int cent_y = tile_draw_rect->ymax - layout->prv_border_y - (layout->prv_h / 2.0f) + 0.5f;+ const float aspect = icon_aspect / UI_SCALE_FAC;++ {+ /* Draw large folder or document icon. */+ const int icon_large = (file->typeflag & FILE_TYPE_DIR) ? ICON_FILE_FOLDER_LARGE :+ ICON_FILE_LARGE;++ uchar icon_col[4];+ rgba_float_to_uchar(icon_col, document_img_col);++ const float scale = 4.0f;+ const float ofs_y = (file->typeflag & FILE_TYPE_DIR ? -0.02f : 0.0f) * layout->prv_h;++ ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH * scale / aspect / 2.0f),+ cent_y - (ICON_DEFAULT_HEIGHT * scale / aspect / 2.0f) + ofs_y,+ icon_large,+ icon_aspect / UI_SCALE_FAC / scale,+ document_img_col[3],+ 0.0f,+ icon_col,+ false,+ UI_NO_ICON_OVERLAY_TEXT);+ }++ if (file_type_icon) {+ /* Small icon in the middle of large image, scaled to fit container and UI scale */+ float icon_opacity = 0.4f;+ uchar icon_color[4] = {0, 0, 0, 255};+ if (srgb_to_grayscale(document_img_col) < 0.5f) {+ icon_color[0] = 255;+ icon_color[1] = 255;+ icon_color[2] = 255;+ }++ const float scale = file->typeflag & FILE_TYPE_DIR ? 1.5f : 2.0f;+ const float ofs_y = (file->typeflag & FILE_TYPE_DIR ? -0.035f : -0.135f) * layout->prv_h;++ ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH * scale / aspect / 2.0f),+ cent_y - (ICON_DEFAULT_HEIGHT * scale / aspect / 2.0f) + ofs_y,+ file_type_icon,+ icon_aspect / UI_SCALE_FAC / scale,+ icon_opacity,+ 0.0f,+ icon_color,+ false,+ UI_NO_ICON_OVERLAY_TEXT);+ }++ GPU_blend(GPU_BLEND_NONE);+}++static void file_draw_loading_icon(const rcti *tile_draw_rect,+ const float preview_icon_aspect,+ const FileLayout *layout)+{+ uchar icon_color[4] = {0, 0, 0, 255};+ /* Contrast with background since we are not showing the large document image. */+ ui::theme::get_color_4ubv(TH_TEXT, icon_color);++ const int cent_x = tile_draw_rect->xmin + layout->prv_border_x + (layout->prv_w / 2.0f) + 0.5f;+ const int cent_y = tile_draw_rect->ymax - layout->prv_border_y - (layout->prv_h / 2.0f) + 0.5f;+ const float aspect = preview_icon_aspect / UI_SCALE_FAC;++ ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH / aspect / 2.0f),+ cent_y - (ICON_DEFAULT_HEIGHT / aspect / 2.0f),+ ICON_PREVIEW_LOADING,+ aspect,+ 1.0f,+ 0.0f,+ icon_color,+ false,+ UI_NO_ICON_OVERLAY_TEXT);+}++static void file_draw_indicator_icons(const FileList *files,+ const FileDirEntry *file,+ const FileLayout *layout,+ const rcti *tile_draw_rect,+ const float preview_icon_aspect,+ const int file_type_icon,+ const bool has_special_file_image,+ const eDirEntry_SelectFlag file_selflag)+{+ const bool is_offline = (file->attributes & FILE_ATTR_OFFLINE);+ const bool is_link = (file->attributes & FILE_ATTR_ANY_LINK);+ const bool is_loading = filelist_file_is_preview_pending(files, file);+ const bool selected = file_selflag & FILE_SEL_SELECTED;++ const uiWidgetColors wcol = ui::theme::theme_get()->tui.wcol_list_item;+ const uchar *icon_color = !selected ? wcol.text : wcol.text_sel;+ const uchar icon_color_lightness = srgb_to_grayscale_byte(icon_color);+ const bool show_icon_border = (icon_color_lightness > 96);++ /* Don't draw these icons if the preview image is small. They are just indicators and shouldn't+ * cover the preview. */+ if (preview_icon_aspect < 2.0f) {+ const float icon_x = float(tile_draw_rect->xmin) + (3.0f * UI_SCALE_FAC);+ const float icon_y = float(tile_draw_rect->ymax) - layout->prv_border_y - layout->prv_h;+ if (is_offline) {+ /* Icon at bottom to indicate the file is offline. */+ ui::icon_draw_ex(icon_x,+ icon_y,+ ICON_INTERNET,+ 1.0f / UI_SCALE_FAC,+ 1.0f,+ 0.0f,+ icon_color,+ show_icon_border,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ else if (is_link) {+ /* Icon at bottom to indicate it is a shortcut, link, or alias. */+ ui::icon_draw_ex(icon_x,+ icon_y,+ ICON_FILE_ALIAS,+ 1.0f / UI_SCALE_FAC,+ 0.6f,+ 0.0f,+ nullptr,+ false,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ else if (file_type_icon) {+ /* Smaller, fainter type icon at bottom-left.+ *+ * Always draw while loading, the preview shows a loading icon and doesn't indicate the type+ * yet then. After loading, the special file image may already draw the type icon in+ * #file_draw_preview(), don't draw it again here. Also don't draw it for font files, they+ * render a font preview already, the type indicator would be redundant.+ */+ if (is_loading || !(has_special_file_image || (file->typeflag & FILE_TYPE_FTFONT))) {+ ui::icon_draw_ex(icon_x,+ icon_y,+ file_type_icon,+ 1.0f / UI_SCALE_FAC,+ 1.0f,+ 0.0f,+ icon_color,+ show_icon_border,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ }+ }++ {+ const float icon_x = float(tile_draw_rect->xmax) - (16.0f * UI_SCALE_FAC);+ const float icon_y = float(tile_draw_rect->ymax) - (20.0f * UI_SCALE_FAC);++ const bool is_current_main_data = filelist_file_get_id(file) != nullptr;+ if (is_current_main_data) {+ /* Smaller, fainter icon at the top-right indicating that the file represents data from the+ * current file (from current #Main in fact). */+ ui::icon_draw_ex(icon_x,+ icon_y,+ ICON_CURRENT_FILE,+ 1.0f / UI_SCALE_FAC,+ 1.0f,+ 0.0f,+ icon_color,+ show_icon_border,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ else if ((file->typeflag & FILE_TYPE_ASSET_ONLINE) != 0) {+ ui::icon_draw_ex(icon_x,+ icon_y,+ ICON_INTERNET,+ 1.0f / UI_SCALE_FAC,+ 1.0f,+ 0.0f,+ icon_color,+ show_icon_border,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ else if (file->asset &&+ file->asset->remote_file_status() == asset_system::RemoteAssetFileStatus::NO_MATCH)+ {+ /* This on-disk asset no longer matches the asset listing it was downloaded from. */+ ui::icon_draw_ex(icon_x,+ icon_y,+ ICON_STATUS_WARNING_FILLED,+ 1.0f / UI_SCALE_FAC,+ 1.0f,+ 0.0f,+ icon_color,+ show_icon_border,+ UI_NO_ICON_OVERLAY_TEXT);+ }+ }+}++static void renamebutton_cb(bContext &C, StringRefNull oldname)+{+ char newname[FILE_MAX + 12];+ char orgname[FILE_MAX + 12];+ char filename[FILE_MAX + 12];+ wmWindowManager *wm = CTX_wm_manager(&C);+ wmWindow *win = CTX_wm_window(&C);+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(CTX_wm_space_data(&C));+ ARegion *region = CTX_wm_region(&C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ BLI_path_join(orgname, params->dir, oldname.c_str());+ STRNCPY(filename, params->renamefile);+ BLI_path_make_safe_filename(filename);+ BLI_path_join(newname, params->dir, filename);++ if (!STREQ(orgname, newname)) {+ errno = 0;+ if ((BLI_rename(orgname, newname) != 0) || !BLI_exists(newname)) {+ WM_global_reportf(+ RPT_ERROR, "Could not rename: %s", errno ? strerror(errno) : "unknown error");+ WM_report_banner_show(wm, win);+ /* Renaming failed, reset the name for further renaming handling. */+ STRNCPY(params->renamefile, oldname.c_str());+ }+ else {+ /* If rename is successful, set renamefile to newly renamed entry.+ * This is used later to select and scroll to the file.+ */+ STRNCPY(params->renamefile, filename);+ }++ /* Ensure we select and scroll to the renamed file.+ * This is done even if the rename fails as we want to make sure that the file we tried to+ * rename is still selected and in view. (it can move if something added files/folders to the+ * directory while we were renaming).+ */+ file_params_invoke_rename_postscroll(wm, win, sfile);+ /* to make sure we show what is on disk */+ ED_fileselect_clear(wm, sfile);+ ED_region_tag_redraw(region);+ }+}++static void draw_background(FileLayout *layout, View2D *v2d)+{+ const int item_height = layout->tile_h + (2 * layout->tile_border_y);+ int i;+ int sy;++ uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);+ immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);+ float col_alternating[4];+ ui::theme::get_color_4fv(TH_ROW_ALTERNATE, col_alternating);+ immUniformThemeColorBlend(TH_BACK, TH_ROW_ALTERNATE, col_alternating[3]);++ /* alternating flat shade background */+ for (i = 2; (i <= layout->rows + 1); i += 2) {+ sy = int(v2d->cur.ymax) - layout->offset_top - i * item_height - layout->list_padding_top;++ /* Offset pattern slightly to add scroll effect. */+ sy += round_fl_to_int(item_height * (v2d->tot.ymax - v2d->cur.ymax) / item_height);++ immRectf(pos,+ v2d->cur.xmin,+ float(sy),+ v2d->cur.xmax,+ float(sy + layout->tile_h + 2 * layout->tile_border_y));+ }++ immUnbindProgram();+}++static void draw_dividers(FileLayout *layout, View2D *v2d)+{+ /* vertical column dividers */++ const int step = (layout->tile_w + 2 * layout->tile_border_x);++ uint vertex_len = 0;+ int sx = int(v2d->tot.xmin);+ while (sx < v2d->cur.xmax) {+ sx += step;+ vertex_len += 4; /* vertex_count = 2 points per line * 2 lines per divider */+ }++ if (vertex_len > 0) {+ float v1[2], v2[2];+ float col_hi[3], col_lo[3];++ ui::theme::get_color_shade_3fv(TH_BACK, 30, col_hi);+ ui::theme::get_color_shade_3fv(TH_BACK, -30, col_lo);++ v1[1] = v2d->cur.ymax - layout->tile_border_y;+ v2[1] = v2d->cur.ymin;++ GPUVertFormat *format = immVertexFormat();+ uint pos = GPU_vertformat_attr_add(format, "pos", gpu::VertAttrType::SFLOAT_32_32);+ uint color = GPU_vertformat_attr_add(format, "color", gpu::VertAttrType::SFLOAT_32_32_32);++ immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);+ immBegin(GPU_PRIM_LINES, vertex_len);++ sx = int(v2d->tot.xmin);+ while (sx < v2d->cur.xmax) {+ sx += step;++ v1[0] = v2[0] = sx;+ immAttrSkip(color);+ immVertex2fv(pos, v1);+ immAttr3fv(color, col_lo);+ immVertex2fv(pos, v2);++ v1[0] = v2[0] = sx + 1;+ immAttrSkip(color);+ immVertex2fv(pos, v1);+ immAttr3fv(color, col_hi);+ immVertex2fv(pos, v2);+ }++ immEnd();+ immUnbindProgram();+ }+}++static void draw_fixed_header_background(const View2D *v2d, const float height)+{+ uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);++ immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);+ immUniformThemeColorShade(TH_BACK, 11);++ immRectf(pos, v2d->cur.xmin, v2d->cur.ymax - height, v2d->cur.xmax, v2d->cur.ymax);++ immUnbindProgram();+}++static void draw_columnheader_columns(const FileSelectParams *params,+ FileLayout *layout,+ const View2D *v2d,+ const uchar text_col[4])+{+ const float divider_pad = 0.2 * layout->attribute_column_header_h;+ int sx = v2d->cur.xmin, sy = v2d->cur.ymax;++ for (int column_type = 0; column_type < ATTRIBUTE_COLUMN_MAX; column_type++) {+ if (!file_attribute_column_type_enabled(params, FileAttributeColumnType(column_type), layout))+ {+ continue;+ }+ const FileAttributeColumn *column = &layout->attribute_columns[column_type];++ /* Active sort type triangle */+ if (params->sort == column->sort_type) {+ float tri_color[4];++ rgba_uchar_to_float(tri_color, text_col);+ ui::draw_icon_tri(sx + column->width - (0.3f * U.widget_unit) -+ ATTRIBUTE_COLUMN_PADDING / 2.0f,+ sy + (0.1f * U.widget_unit) - (layout->attribute_column_header_h / 2),+ (params->flag & FILE_SORT_INVERT) ? 't' : 'v',+ tri_color);+ }++ file_draw_string(sx + ATTRIBUTE_COLUMN_PADDING,+ sy - layout->tile_border_y,+ IFACE_(column->name),+ column->width - 2 * ATTRIBUTE_COLUMN_PADDING,+ layout->attribute_column_header_h - layout->tile_border_y,+ ui::UI_STYLE_TEXT_LEFT,+ text_col);++ /* Separator line */+ if (column_type != COLUMN_NAME) {+ uint pos = GPU_vertformat_attr_add(+ immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);++ immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);+ immUniformThemeColorShade(TH_BACK, -10);+ immBegin(GPU_PRIM_LINES, 2);+ immVertex2f(pos, sx - 1, sy - divider_pad);+ immVertex2f(pos, sx - 1, sy - layout->attribute_column_header_h + divider_pad);+ immEnd();+ immUnbindProgram();+ }++ sx += column->width;+ }++ /* Vertical separator lines line */+ {+ uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);+ immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);+ immUniformThemeColorShade(TH_BACK, -10);+ immBegin(GPU_PRIM_LINES, 4);+ immVertex2f(pos, v2d->cur.xmin, sy);+ immVertex2f(pos, v2d->cur.xmax, sy);+ immVertex2f(pos, v2d->cur.xmin, sy - layout->attribute_column_header_h);+ immVertex2f(pos, v2d->cur.xmax, sy - layout->attribute_column_header_h);+ immEnd();+ immUnbindProgram();+ }+}++/**+ * Updates the stat string stored in file->entry if necessary.+ */+static const char *filelist_get_details_column_string(+ FileAttributeColumnType column,+ /* Generated string will be cached in the file, so non-const. */+ FileDirEntry *file,+ const bool compact,+ const bool update_stat_strings)+{+ switch (column) {+ case COLUMN_DATETIME:+ if (!(file->typeflag & FILE_TYPE_BLENDERLIB) && !FILENAME_IS_CURRPAR(file->relpath)) {+ if (file->draw_data.datetime_str[0] == '\0' || update_stat_strings) {+ const time_t file_time = (time_t)file->time;+ const std::tm mod_time = date_string::localtime_safe(file_time);+ const time_t ts_now = time(nullptr);+ const std::tm now = date_string::localtime_safe(ts_now);+ const char *lang = BLT_lang_get();+ std::string modified_s =+ compact ? date_string::date(mod_time, lang, date_string::DateFormat(U.date_format)) :+ date_string::datetime(mod_time,+ lang,+ date_string::DateFormat(U.date_format),+ date_string::TimeFormat(U.time_format),+ &now,+ TIP_("Today"),+ TIP_("Yesterday"));+ STRNCPY_UTF8(file->draw_data.datetime_str, modified_s.c_str());+ }+ return file->draw_data.datetime_str;+ }+ break;+ case COLUMN_SIZE:+ if ((file->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) ||+ !(file->typeflag & (FILE_TYPE_DIR | FILE_TYPE_BLENDERLIB)))+ {+ if (file->draw_data.size_str[0] == '\0' || update_stat_strings) {+ BLI_filelist_entry_size_to_string(+ nullptr, file->size, compact, file->draw_data.size_str);+ }++ return file->draw_data.size_str;+ }+ break;+ default:+ break;+ }++ return nullptr;+}++static void draw_details_columns(const FileSelectParams *params,+ const FileLayout *layout,+ FileDirEntry *file,+ const rcti *tile_draw_rect,+ const uchar text_col[4])+{+ const bool compact = FILE_LAYOUT_COMPACT(layout);+ const bool update_stat_strings = layout->width != layout->curr_size;+ int sx = tile_draw_rect->xmin - layout->tile_border_x;++ for (int column_type = 0; column_type < ATTRIBUTE_COLUMN_MAX; column_type++) {+ const FileAttributeColumn *column = &layout->attribute_columns[column_type];++ /* Name column is not a detail column (should already be drawn), always skip here. */+ if (column_type == COLUMN_NAME) {+ sx += column->width;+ continue;+ }+ if (!file_attribute_column_type_enabled(params, FileAttributeColumnType(column_type), layout))+ {+ continue;+ }++ const char *str = filelist_get_details_column_string(+ FileAttributeColumnType(column_type), file, compact, update_stat_strings);++ if (str) {+ file_draw_string(sx + ATTRIBUTE_COLUMN_PADDING,+ tile_draw_rect->ymax,+ IFACE_(str),+ column->width - 2 * ATTRIBUTE_COLUMN_PADDING,+ layout->tile_h,+ ui::FontStyleAlign(column->text_align),+ text_col);+ }++ sx += column->width;+ }+}++static rcti tile_draw_rect_get(const View2D *v2d, const FileLayout *layout, const int file_idx)+{+ int tile_pos_x, tile_pos_y;+ ED_fileselect_layout_tilepos(layout, file_idx, &tile_pos_x, &tile_pos_y);+ tile_pos_x += int(v2d->tot.xmin);+ tile_pos_y = int(v2d->tot.ymax - tile_pos_y);++ rcti rect;+ rect.xmin = tile_pos_x;+ rect.xmax = rect.xmin + layout->tile_w;+ rect.ymax = tile_pos_y;+ rect.ymin = rect.ymax - layout->tile_h;++ return rect;+}++/**+ * Get the boundaries to display the name label in (this isn't the rectangle of the text itself).+ */+static rcti text_draw_rect_get(const View2D *v2d,+ const eFileDisplayType display_type,+ const FileLayout *layout,+ const int file_idx,+ const int icon_ofs_x)+{+ rcti tile_rect = tile_draw_rect_get(v2d, layout, file_idx);++ rcti rect = tile_rect;+ if (display_type == FILE_IMGDISPLAY) {+ rect.ymin += round_fl_to_int(layout->prv_border_y * 0.5f);+ rect.ymax = rect.ymin + layout->text_line_height * layout->text_lines_count;+ }+ else {+ rect.xmin += icon_ofs_x + 1;+ rect.xmax = tile_rect.xmin + round_fl_to_int(layout->attribute_columns[COLUMN_NAME].width) -+ layout->tile_border_x;+ }++ return rect;+}++void file_draw_list(const bContext *C, ARegion *region)+{+ wmWindowManager *wm = CTX_wm_manager(C);+ wmWindow *win = CTX_wm_window(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileLayout *layout = ED_fileselect_get_layout(sfile, region);+ View2D *v2d = ®ion->v2d;+ FileList *files = sfile->files;+ FileDirEntry *file;+ ui::Block *block = block_begin(C, region, __func__, ui::EmbossType::Emboss);+ int numfiles;+ int numfiles_layout;+ int offset;+ int i;+ ui::FontStyleAlign align;+ bool do_drag;+ uchar text_col[4];+ const uiWidgetColors wcol = ui::theme::theme_get()->tui.wcol_list_item;+ const bool draw_columnheader = (params->display == FILE_VERTICALDISPLAY);+ const float thumb_icon_aspect = std::min(64.0f / float(params->thumbnail_size), 4.0f);++ numfiles = filelist_files_ensure(files);++ if (params->display != FILE_IMGDISPLAY) {+ draw_background(layout, v2d);+ draw_dividers(layout, v2d);+ }++ offset = ED_fileselect_layout_offset(+ layout, int(region->v2d.cur.xmin), int(-region->v2d.cur.ymax) + layout->offset_top);+ offset = std::max(offset, 0);++ numfiles_layout = ED_fileselect_layout_numfiles(layout, region);++ /* adjust, so the next row is already drawn when scrolling */+ if (layout->flag & FILE_LAYOUT_HOR) {+ numfiles_layout += layout->rows;+ }+ else {+ numfiles_layout += layout->flow_columns;+ }++ filelist_file_cache_slidingwindow_set(files, numfiles_layout);++ align = (FILE_IMGDISPLAY == params->display) ? ui::UI_STYLE_TEXT_CENTER : ui::UI_STYLE_TEXT_LEFT;++ if (numfiles > 0) {+ const bool success = filelist_file_cache_block(+ files, min_ii(offset + (numfiles_layout / 2), numfiles - 1));+ BLI_assert(success);+ UNUSED_VARS_NDEBUG(success);++ filelist_cache_previews_update(files);++ /* Handle preview timer here,+ * since it's filelist_file_cache_block() and filelist_cache_previews_update()+ * which controls previews task.+ * Note that online assets don't use this system.+ */+ {+ const bool previews_running = filelist_cache_previews_running(files) &&+ !filelist_cache_previews_done(files);+ // printf("%s: preview task: %d\n", __func__, previews_running);+ if (previews_running && !sfile->previews_timer) {+ sfile->previews_timer = WM_event_timer_add_notifier(+ wm, win, NC_SPACE | ND_SPACE_FILE_PREVIEW, 0.01);+ }+ if (!previews_running && sfile->previews_timer) {+ /* Preview is not running, no need to keep generating update events! */+ // printf("%s: Inactive preview task, sleeping!\n", __func__);+ WM_event_timer_remove_notifier(wm, win, sfile->previews_timer);+ sfile->previews_timer = nullptr;+ }+ }+ }++ BLF_batch_draw_begin();++ /* Default text color, used for the empty/not-ready message and column headers when the+ * per-file loop below does not run (empty directory, no search matches, still loading). */+ ui::theme::get_color_4ubv(TH_TEXT, text_col);++ const bool filelist_loading = !filelist_is_ready(files);++ for (i = offset; (i < numfiles) && (i < offset + numfiles_layout); i++) {+ const int padx = 0.1f * UI_UNIT_X;+ int icon_ofs = 0;++ const rcti tile_draw_rect = tile_draw_rect_get(v2d, layout, i);++ file = filelist_file(files, i);+ eDirEntry_SelectFlag file_selflag = filelist_entry_select_get(sfile->files, file, CHECK_ALL);+ if (params->highlight_file == i) {+ file_selflag |= FILE_SEL_HIGHLIGHTED;+ }++ char path[FILE_MAX_LIBEXTRA];+ filelist_file_get_full_path(files, file, path);++ const bool is_selected = file_selflag & FILE_SEL_SELECTED;+ const bool is_highlighted = file_selflag & FILE_SEL_HIGHLIGHTED;+ copy_v4_v4_uchar(text_col, is_selected ? wcol.text_sel : wcol.text);++ if (!(file_selflag & FILE_SEL_EDITING)) {+ BLI_assert(i == 0 || !FILENAME_IS_CURRPAR(file->relpath));+ draw_tile_background(&tile_draw_rect, is_selected, is_highlighted);+ }+ draw_roundbox_corner_set(ui::CNR_NONE);++ /* don't drag parent or refresh items */+ do_drag = !FILENAME_IS_CURRPAR(file->relpath);+ const bool is_hidden = (file->attributes & FILE_ATTR_HIDDEN);++ if (FILE_IMGDISPLAY == params->display) {+ if ((file->typeflag & FILE_TYPE_ASSET_ONLINE) && !filelist_loading) {+ filelist_online_asset_preview_request(C, file);+ /* Trigger the preview loader to wait until the download is done and load the preview from+ * disk. Has to be done explicitly here because the preview isn't attached to a button. */+ if (!file->asset->is_local_id()) {+ if (PreviewImage *preview = file->asset->get_preview()) {+ ui::icon_render_id_ex(C, nullptr, nullptr, ICON_SIZE_PREVIEW, true, preview);+ }+ }+ }++ const int file_type_icon = filelist_geticon_file_type(files, i, false);+ std::optional<IconBufferRef> preview_buf = file->preview_icon_id ?+ BKE_icon_get_buffer(file->preview_icon_id,+ ICON_SIZE_PREVIEW) :+ std::nullopt;++ bool has_special_file_image = false;++ const bool is_loading = filelist_file_is_preview_pending(files, file);+ if (is_loading) {+ file_draw_loading_icon(&tile_draw_rect, thumb_icon_aspect, layout);+ }+ else if (preview_buf) {+ file_draw_preview(file, &tile_draw_rect, *preview_buf, layout, is_hidden);+ }+ else {+ /* Larger folder or document icon, with file/folder type icon in the middle (if any). */+ file_draw_special_image(file,+ &tile_draw_rect,+ file_type_icon,+ thumb_icon_aspect,+ layout,+ is_hidden,+ file_selflag);+ has_special_file_image = true;+ }++ file_draw_indicator_icons(files,+ file,+ layout,+ &tile_draw_rect,+ thumb_icon_aspect,+ file_type_icon,+ has_special_file_image,+ file_selflag);++ if (do_drag) {+ file_add_preview_drag_but(sfile, block, file, path, &tile_draw_rect, file_type_icon);+ }++ if (is_highlighted && file->asset && file->asset->needs_download()) {+ file_add_asset_download_but(block, layout, file, &tile_draw_rect);+ }+ }+ else {+ const BIFIconID icon = [&]() {+ if (file->asset) {+ file->asset->ensure_previewable(*C);++ if (filelist_loading) {+ return BIFIconID(ICON_PREVIEW_LOADING);+ }+ return ed::asset::asset_preview_or_icon(*file->asset);+ }+ return filelist_geticon_file_type(files, i, true);+ }();++ icon_ofs += layout->prv_w + 2 * padx;++ /* Add dummy draggable button covering the icon and the label. */+ if (do_drag) {+ const uiStyle *style = ui::style_get();+ const int str_width = ui::fontstyle_string_width(&style->widget, file->name);+ const int drag_width = std::min(+ str_width + icon_ofs,+ int(layout->attribute_columns[COLUMN_NAME].width - ATTRIBUTE_COLUMN_PADDING));+ if (drag_width > 0) {+ /* Uses full row height (tile height plus 2 * tile border padding) so there's no space+ * between rows. */+ ui::Button *drag_but = uiDefBut(block,+ ui::ButtonType::Label,+ "",+ tile_draw_rect.xmin,+ tile_draw_rect.ymin - layout->tile_border_y,+ drag_width,+ layout->tile_h + layout->tile_border_y * 2,+ nullptr,+ 0,+ 0,+ std::nullopt);+ button_dragflag_enable(drag_but, ui::BUT_DRAG_FULL_BUT);+ file_but_enable_drag(drag_but, sfile, file, path, nullptr, icon, UI_SCALE_FAC);+ file_but_tooltip_func_set(sfile, file, drag_but);+ }+ }++ /* Add this after the fake draggable button, so the icon button tooltip is displayed. */+ ui::Button *icon_but = file_add_icon_but(sfile,+ block,+ path,+ file,+ &tile_draw_rect,+ icon,+ layout->prv_w,+ layout->prv_h,+ padx,+ is_hidden);+ if (do_drag) {+ /* For some reason the dragging is unreliable for the icon button if we don't explicitly+ * enable dragging, even though the dummy drag button above covers the same area. */+ file_but_enable_drag(icon_but, sfile, file, path, nullptr, icon, UI_SCALE_FAC);+ }++ if (layout->prv_w >= round_fl_to_int(ICON_DEFAULT_WIDTH_SCALE * 2) &&+ (filelist_loading || icon >= BIFICONID_LAST_STATIC))+ {+ const BIFIconID type_icon = filelist_geticon_file_type(files, i, true);+ file_add_overlay_icon_but(block,+ tile_draw_rect.xmin + padx - 2,+ tile_draw_rect.ymin - 2 * UI_SCALE_FAC,+ type_icon);+ }+ }++ const rcti text_rect = text_draw_rect_get(+ v2d, eFileDisplayType(params->display), layout, i, icon_ofs);++ if (file_selflag & FILE_SEL_EDITING) {+ const int but_height =+ (params->display == FILE_IMGDISPLAY) ?+ layout->text_line_height * 1.4f :+ /* Just a little smaller than the tile height, clamped to #UI_UNIT_Y as maximum. */+ std::min(short(BLI_rcti_size_y(&text_rect) - 1.0f * UI_SCALE_FAC), UI_UNIT_Y);+ ui::Button *but = uiDefBut(block,+ ui::ButtonType::Text,+ "",+ text_rect.xmin,+ /* First line only, when name is displayed in multiple lines. */+ text_rect.ymax - but_height,+ BLI_rcti_size_x(&text_rect),+ but_height,+ params->renamefile,+ 1.0f,+ float(sizeof(params->renamefile)),+ "");+ text_button_func_rename_set(but, renamebutton_cb);+ button_flag_enable(but, ui::BUT_NO_UTF8); /* Allow non UTF8 names. */+ button_flag_disable(but, ui::BUT_UNDO);+ if (false == button_active_only(C, region, block, but)) {+ /* Note that this is the only place where we can also handle a cancelled renaming. */++ file_params_rename_end(wm, win, sfile, file);++ /* After the rename button is removed, we need to make sure the view is redrawn once more,+ * in case selection changed. Usually UI code would trigger that redraw, but the rename+ * operator may have been called from a different region.+ * Tagging regions for redrawing while drawing is rightfully prevented. However, this+ * active button removing basically introduces handling logic to drawing code. So a+ * notifier should be an acceptable workaround. */+ WM_event_add_notifier_ex(wm, win, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);++ file_selflag = filelist_entry_select_get(sfile->files, file, CHECK_ALL);+ }+ }++ /* file_selflag might have been modified by branch above. */+ if ((file_selflag & FILE_SEL_EDITING) == 0) {+ if (layout->text_lines_count == 1) {+ file_draw_string(text_rect.xmin,+ text_rect.ymax,+ file->name,+ BLI_rcti_size_x(&text_rect),+ BLI_rcti_size_y(&text_rect),+ align,+ text_col);+ }+ else {+ file_draw_string_mulitline_clipped(&text_rect, file->name, align, text_col);+ }+ }++ ui::theme::get_color_4ubv(TH_TEXT, text_col);+ if (params->display != FILE_IMGDISPLAY) {+ draw_details_columns(params, layout, file, &tile_draw_rect, text_col);+ }+ }++ if (numfiles < 1) {+ const rcti tile_draw_rect = tile_draw_rect_get(v2d, layout, 0);+ const uiStyle *style = ui::style_get();++ const bool is_filtered = params->filter_search[0] != '\0';++ uchar text_col_mod[4];+ copy_v4_v4_uchar(text_col_mod, text_col);+ if (!is_filtered) {+ text_col_mod[3] /= 2;+ }++ const char *message = [&]() {+ if (!filelist_is_ready(files)) {+ return IFACE_("Loading...");+ }+ if (is_filtered) {+ return IFACE_("No results match the search filter");+ }+ FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);+ if (asset_params && (asset_params->asset_access == AssetAccess::OnlyOnline)) {+ return IFACE_("No items. Note: The \"Only Online\" filter option is enabled.");+ }+ if (asset_params && (asset_params->asset_access == AssetAccess::OnlyOffline)) {+ return IFACE_("No items. Note: The \"Only Offline\" filter option is enabled.");+ }+ return IFACE_("No items");+ }();++ ui::fontstyle_draw_simple(&style->widget,+ tile_draw_rect.xmin + UI_UNIT_X,+ tile_draw_rect.ymax - UI_UNIT_Y,+ message,+ text_col_mod);+ }++ BLF_batch_draw_end();++ block_end(C, block);+ block_draw(C, block);++ /* Draw last, on top of file list. */+ if (draw_columnheader) {+ draw_fixed_header_background(v2d, layout->attribute_column_header_h);+ draw_columnheader_columns(params, layout, v2d, text_col);+ }++ if (numfiles != -1) {+ /* Only save current size if there is something to show. */+ layout->curr_size = layout->width;+ }+}++void file_draw_banner(const bContext *C, const SpaceFile *sfile, ARegion *region)+{+ /* Passed into lambda as block ID-name. */+ static const char *funcname = __func__;++ file_banners_for_first_visible(*sfile, [&](const BannerType &banner) {+ draw_fixed_header_background(®ion->v2d, sfile->layout->offset_top);++ ui::Block *block = block_begin(C, region, funcname, ui::EmbossType::Emboss);+ ui::Layout &layout = ui::block_layout(+ block,+ ui::LayoutDirection::Vertical,+ ui::LayoutType::Panel,+ sfile->layout->tile_border_x,+ -sfile->layout->tile_border_y + region->v2d.cur.ymax,+ std::max(0, region->winx - 2 * sfile->layout->tile_border_x),+ 0,+ 0,+ ui::style_get_dpi());++ banner.layout(*sfile, layout.row(false));++ block_layout_resolve(block);+ block_end(C, block);+ block_draw(C, block);+ });+}++static void file_draw_invalid_asset_library_hint(const bContext *C,+ const SpaceFile *sfile,+ ARegion *region,+ FileAssetSelectParams *asset_params,+ bool is_project_library)+{+ char library_ui_path[FILE_MAX_LIBEXTRA];+ file_path_to_ui_path(asset_params->base_params.dir, library_ui_path);++ uchar text_col[4];+ ui::theme::get_color_4ubv(TH_TEXT, text_col);++ const View2D *v2d = ®ion->v2d;+ const int pad = sfile->layout->tile_border_x;+ const int width = BLI_rctf_size_x(&v2d->tot) - (2 * pad);+ const int line_height = sfile->layout->text_line_height;+ int sx = v2d->tot.xmin + pad;+ /* For some reason no padding needed. */+ int sy = v2d->tot.ymax;++ {+ const char *message = RPT_("Path to asset library does not exist:");+ file_draw_string_multiline(sx, sy, message, width, line_height, text_col, nullptr, &sy);++ sy -= line_height;+ file_draw_string(+ sx, sy, library_ui_path, width, line_height, ui::UI_STYLE_TEXT_LEFT, text_col);+ }++ /* Separate a bit further. */+ sy -= line_height * 2.2f;++ {+ ui::icon_draw(sx, sy - UI_UNIT_Y, ICON_STATUS_INFO);++ const char *suggestion = RPT_(+ "Asset Libraries are local directories that can contain .blend files with assets inside.\n"+ "Manage Asset Libraries from the Asset Libraries section in the Preferences");+ file_draw_string_multiline(+ sx + UI_UNIT_X, sy, suggestion, width - UI_UNIT_X, line_height, text_col, nullptr, &sy);++ ui::Block *block = block_begin(C, region, __func__, ui::EmbossType::Emboss);+ wmOperatorType *ot;+ if (is_project_library) {+ ot = WM_operatortype_find("SCREEN_OT_project_settings_show", false);+ }+ else {+ ot = WM_operatortype_find("SCREEN_OT_userpref_show", false);+ }+ ui::Button *but = uiDefIconTextButO_ptr(block,+ ui::ButtonType::But,+ ot,+ wm::OpCallContext::InvokeDefault,+ ICON_PREFERENCES,+ WM_operatortype_name(ot, nullptr),+ sx + UI_UNIT_X,+ sy - line_height - UI_UNIT_Y * 1.2f,+ UI_UNIT_X * 8,+ UI_UNIT_Y,+ std::nullopt);+ PointerRNA *but_opptr = button_operator_ptr_ensure(but);+ if (is_project_library) {+ RNA_string_set(but_opptr, "section", "Asset Libraries");+ }+ else {+ RNA_enum_set(but_opptr, "section", USER_SECTION_ASSETS);+ }++ block_end(C, block);+ block_draw(C, block);+ }+}++static void file_draw_asset_library_internet_access_required_hint(const bContext *C,+ const SpaceFile *sfile,+ ARegion *region)+{+ using namespace blender;++ uchar text_col[4];+ ui::theme::get_color_4ubv(TH_TEXT, text_col);++ const View2D *v2d = ®ion->v2d;+ const int pad_x = sfile->layout->tile_border_x * 2;+ const int pad_y = sfile->layout->tile_border_y * 2;+ const int available_width = BLI_rctf_size_x(&v2d->tot) - (2 * pad_x);+ const int line_height = sfile->layout->text_line_height;+ const char *message = RPT_(+ "Allow Online Access in order to browse and download online assets, or turn off the "+ "\"Remote Assets\" filter to show only the downloaded assets.\n\nYou can adjust this "+ "later from the \"System\" preferences.");++ const int box_width = std::min(available_width, UI_UNIT_X * 28);+ /* The width we have available inside the box. */+ const int wrap_width = box_width - 2 * pad_x;+ const rcti message_textbox = file_measure_string_multiline(message, wrap_width);+ /* The text box doesn't seem to encompass all text, apparently half a line too little. */+ const int message_height = BLI_rcti_size_y(&message_textbox) + 0.5f * line_height;++ const int heading_height = UI_UNIT_Y;+ const int box_height = heading_height + message_height ++ /* Extra spacing after header and after main message. */+ 2 * pad_y ++ /* Button height. */+ UI_UNIT_Y ++ /* Top and bottom padding. */+ 2 * pad_y;++ int sx = round_fl_to_int(BLI_rctf_cent_x(&v2d->tot) - box_width / 2.0f);+ int sy = round_fl_to_int(BLI_rctf_cent_y(&v2d->tot) + box_height / 2.0f);++ ui::Block *block = ui::block_begin(C, region, __func__, ui::EmbossType::Emboss);++ uiDefBut(block,+ ui::ButtonType::Roundbox,+ "",+ sx,+ sy - box_height,+ box_width,+ box_height,+ nullptr,+ 0.0,+ 0.0,+ "");++ /* Top left padding within the box. */+ sx += pad_x;+ sy -= pad_y;++ {+ uiDefIconTextBut(block,+ ui::ButtonType::Label,+ ICON_INTERNET_OFFLINE,+ "Internet Access Required",+ sx,+ sy - heading_height,+ wrap_width,+ heading_height,+ nullptr,+ {});++ const int button_width = (wrap_width - pad_x) * 0.5f;+ ui::Button *but = uiDefIconTextButO(block,+ ui::ButtonType::But,+ "WM_OT_context_set_boolean",+ wm::OpCallContext::InvokeDefault,+ ICON_X,+ "Continue Offline",+ sx,+ sy + pad_y - box_height + pad_y,+ button_width,+ UI_UNIT_Y,+ {});+ PointerRNA *but_opptr = ui::button_operator_ptr_ensure(but);+ RNA_string_set(but_opptr, "data_path", "preferences.extensions.use_online_access_handled");+ RNA_boolean_set(but_opptr, "value", true);++ uiDefIconTextButO(block,+ ui::ButtonType::But,+ "extensions.userpref_allow_online",+ wm::OpCallContext::InvokeDefault,+ ICON_CHECKMARK,+ "Allow Online Access",+ sx + button_width + pad_x,+ sy + pad_y - box_height + pad_y,+ button_width,+ UI_UNIT_Y,+ {});+ }++ ui::block_end(C, block);+ ui::block_draw(C, block);++ /* Draw multi-line text on top of widget drawing. */+ file_draw_string_multiline(sx,+ sy - heading_height - pad_y,+ message,+ wrap_width,+ line_height,+ text_col,+ nullptr,+ nullptr);+}++static void file_draw_asset_library_remote_loading_failed_hint(const bContext *C,+ const SpaceFile *sfile,+ ARegion *region,+ const bUserAssetLibrary *library)+{+ using namespace blender;++ uchar text_col[4];+ ui::theme::get_color_4ubv(TH_TEXT, text_col);++ const View2D *v2d = ®ion->v2d;+ const int pad_x = sfile->layout->tile_border_x * 2;+ const int pad_y = sfile->layout->tile_border_y * 2;+ const int available_width = BLI_rctf_size_x(&v2d->tot) - (2 * pad_x);+ const int line_height = sfile->layout->text_line_height;+ StringRefNull message =+ RemoteLibraryLoadingStatus::failure_message(library->remote_url).value_or("Unknown reason");++ const int message_width = ui::fontstyle_string_width(&ui::style_get()->widget, message.c_str());+ const int box_width = std::min({available_width, UI_UNIT_X * 28, message_width + (2 * pad_x)});+ /* The width we have available inside the box. */+ const int wrap_width = box_width - 2 * pad_x;+ const rcti message_textbox = file_measure_string_multiline(message, wrap_width);+ /* The text box doesn't seem to encompass all text, apparently half a line too little. */+ const int message_height = BLI_rcti_size_y(&message_textbox) + 0.5f * line_height;++ const int heading_height = UI_UNIT_Y;+ const int box_height = heading_height + message_height ++ /* Extra spacing after header. */+ pad_y ++ /* Top and bottom padding. */+ 2 * pad_y;++ int sx = round_fl_to_int(BLI_rctf_cent_x(&v2d->tot) - box_width / 2.0f);+ int sy = round_fl_to_int(BLI_rctf_cent_y(&v2d->tot) + box_height / 2.0f);++ ui::Block *block = ui::block_begin(C, region, __func__, ui::EmbossType::Emboss);++ uiDefBut(block,+ ui::ButtonType::Roundbox,+ "",+ sx,+ sy - box_height,+ box_width,+ box_height,+ nullptr,+ 0.0,+ 0.0,+ "");++ /* Top left padding within the box. */+ sx += pad_x;+ sy -= pad_y;++ {+ uiDefIconTextBut(block,+ ui::ButtonType::Label,+ ICON_STATUS_ERROR_FILLED,+ "Asset Library Download Failed",+ sx,+ sy - heading_height,+ wrap_width,+ heading_height,+ nullptr,+ {});+ }++ ui::block_end(C, block);+ ui::block_draw(C, block);++ /* Draw multi-line text on top of widget drawing. */+ file_draw_string_multiline(sx,+ sy - heading_height - pad_y,+ message,+ wrap_width,+ line_height,+ text_col,+ nullptr,+ nullptr);+}++static void file_draw_invalid_library_hint(const bContext * /*C*/,+ const SpaceFile *sfile,+ ARegion *region,+ const char *blendfile_path,+ ReportList *reports)+{+ uchar text_col[4];+ ui::theme::get_color_4ubv(TH_TEXT, text_col);++ const View2D *v2d = ®ion->v2d;+ const int pad = sfile->layout->tile_border_x;+ const int width = BLI_rctf_size_x(&v2d->tot) - (2 * pad);+ const int line_height = sfile->layout->text_line_height;+ int sx = v2d->tot.xmin + pad;+ /* For some reason no padding needed. */+ int sy = v2d->tot.ymax;++ {+ const char *message = RPT_("Unreadable Blender library file:");+ file_draw_string_multiline(sx, sy, message, width, line_height, text_col, nullptr, &sy);++ sy -= line_height;+ file_draw_string(sx, sy, blendfile_path, width, line_height, ui::UI_STYLE_TEXT_LEFT, text_col);+ }++ /* Separate a bit further. */+ sy -= line_height * 2.2f;++ for (Report &report : reports->list) {+ const short report_type = report.type;+ if (report_type <= RPT_INFO) {+ continue;+ }++ int icon = ICON_STATUS_INFO;+ if (report_type > RPT_WARNING) {+ icon = ICON_STATUS_WARNING_FILLED;+ }+ ui::icon_draw(sx, sy - UI_UNIT_Y, icon);++ file_draw_string_multiline(sx + UI_UNIT_X,+ sy,+ RPT_(report.message),+ width - UI_UNIT_X,+ line_height,+ text_col,+ nullptr,+ &sy);+ sy -= line_height;+ }+}++static const bUserAssetLibrary *assetlib_ref_as_library(+ const AssetLibraryReference &asset_library_ref)+{+ if (asset_library_ref.type != ASSET_LIBRARY_CUSTOM) {+ return nullptr;+ }++ const bUserAssetLibrary *library = BKE_preferences_asset_library_find_index(+ &U, asset_library_ref.custom_library_index);+ if (!library) {+ return nullptr;+ }++ return library;+}++static bool show_asset_library_message(const bContext *C,+ const SpaceFile *sfile,+ ARegion *region,+ const auto setup_view)+{+ FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);++ const bUserAssetLibrary *library = assetlib_ref_as_library(asset_params->asset_library_ref);++ if (!library) {+ /* We do not need to draw or check for any error in non user defined asset libraries.+ * This is because we do not expect the paths to ever be invalid for these.+ */+ return false;+ }++ const bool is_remote_library = library->flag & ASSET_LIBRARY_USE_REMOTE_URL;+ const bool is_project_library = library->flag & ASSET_LIBRARY_PROJECT_DEFINED;++ if (is_remote_library) {+ /* With remote libraries, there may be already-downloaded assets available that should be+ * displayed. Don't show the "internet access required" hint until done loading, and only if+ * there are no already-downloaded assets to display. */+ if (!filelist_is_ready(sfile->files) || !filelist_files_num_entries(sfile->files)) {+ return false;+ }++ const bool is_online_allowed = G.f & G_FLAG_INTERNET_ALLOW;+ const bool was_choice_made = U.extension_flag & USER_EXTENSION_FLAG_ONLINE_ACCESS_HANDLED;+ if (!is_online_allowed && !was_choice_made) {+ setup_view();+ file_draw_asset_library_internet_access_required_hint(C, sfile, region);+ return true;+ }+ if (RemoteLibraryLoadingStatus::status(library->remote_url) ==+ RemoteLibraryLoadingStatus::Failure)+ {+ setup_view();+ file_draw_asset_library_remote_loading_failed_hint(C, sfile, region, library);+ return true;+ }+ }++ const bool is_on_disk_library = !ELEM(asset_params->asset_library_ref.type,+ ASSET_LIBRARY_LOCAL,+ ASSET_LIBRARY_ALL) &&+ !is_remote_library;++ /* Check if the asset library exists. */+ if (is_on_disk_library && !filelist_is_dir(sfile->files, asset_params->base_params.dir)) {+ setup_view();+ file_draw_invalid_asset_library_hint(C, sfile, region, asset_params, is_project_library);+ return true;+ }++ /* We didn't draw any messages. */+ return false;+}++bool file_draw_hint_if_invalid(const bContext *C, const SpaceFile *sfile, ARegion *region)+{+ char blendfile_path[FILE_MAX_LIBEXTRA];+ const bool is_asset_browser = ED_fileselect_is_asset_browser(sfile);+ const bool is_library_browser = !is_asset_browser &&+ filelist_islibrary(sfile->files, blendfile_path, nullptr);+ /* Call this before drawing a hint, otherwise drawing will not be visible. */+ const auto setup_view = [region]() {+ ui::view2d_totRect_set(®ion->v2d, region->winx, region->winy);+ ui::view2d_view_ortho(®ion->v2d);+ };++ if (is_asset_browser && show_asset_library_message(C, sfile, region, setup_view)) {+ return true;+ }++ /* Check if the blendfile library is valid (has entries). */+ if (is_library_browser) {+ if (!filelist_is_ready(sfile->files)) {+ return false;+ }++ const int numfiles = filelist_files_num_entries(sfile->files);+ if (numfiles > 0) {+ return false;+ }++ /* This could all be part of the file-list loading:+ * - When loading fails this could be saved in the file-list, e.g. when+ * `BLO_blendhandle_from_file()` returns null in `filelist_readjob_list_lib()`, a+ * `FL_HAS_INVALID_LIBRARY` file-list flag could be set.+ * - Reports from it could also be stored in `FileList` rather than being ignored+ * (`RPT_STORE` must be set!).+ * - Then we could just check for `is_library_browser` and the `FL_HAS_INVALID_LIBRARY` flag+ * here, and draw the hint with the reports in the file-list. (We would not draw a hint for+ * recursive loading, even if the file-list has the "has invalid library" flag set, which+ * seems like the wanted behavior.)+ * - The call to BKE_blendfile_is_readable() would not be needed then.+ */+ if (!sfile->runtime->is_blendfile_status_set) {+ BKE_reports_clear(&sfile->runtime->is_blendfile_readable_reports);+ sfile->runtime->is_blendfile_readable = BKE_blendfile_is_readable(+ blendfile_path, &sfile->runtime->is_blendfile_readable_reports);+ sfile->runtime->is_blendfile_status_set = true;+ }+ if (!sfile->runtime->is_blendfile_readable) {+ setup_view();+ file_draw_invalid_library_hint(+ C, sfile, region, blendfile_path, &sfile->runtime->is_blendfile_readable_reports);+ return true;+ }+ }++ return false;+}++} // namespace blenderdiff --git a/ui/space_file/file_intern.hh b/ui/space_file/file_intern.hhnew file mode 100644index 0000000..30be48e--- /dev/null+++ b/ui/space_file/file_intern.hh@@ -0,0 +1,288 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#pragma once++#include "BLI_span.hh"++#include "DNA_space_types.h"++#include "BKE_report.hh"++#include "ED_fileselect.hh"++namespace blender {++/* internal exports only */++struct ARegion;+struct ARegionType;+struct bContextDataResult;+struct FileAssetSelectParams;+struct FileSelectParams;+struct FolderList;+struct Main;+struct SpaceFile;+struct View2D;+namespace asset_system {+class AssetLibrary;+}+namespace ui {+struct Layout;+} // namespace ui++bool file_main_region_needs_refresh_before_draw(SpaceFile *sfile);++/* `file_context.cc` */++int /*eContextResult*/ file_context(const bContext *C,+ const char *member,+ bContextDataResult *result);++/* `file_draw.cc` */++#define ATTRIBUTE_COLUMN_PADDING (0.5f * UI_UNIT_X)++#define FILE_LAYOUT_COMPACT(_layout) \+ (_layout->flag & FILE_LAYOUT_VER && (_layout->width / UI_SCALE_FAC) < 500)+#define FILE_LAYOUT_HIDE_DATE(_layout) \+ (_layout->flag & FILE_LAYOUT_VER && (_layout->width / UI_SCALE_FAC) < 250)+#define FILE_LAYOUT_HIDE_SIZE(_layout) \+ (_layout->flag & FILE_LAYOUT_VER && (_layout->width / UI_SCALE_FAC) < 350)++void file_draw_list(const bContext *C, ARegion *region);+bool file_banner_poll(const SpaceFile *sfile);+void file_draw_banner(const bContext *C, const SpaceFile *sfile, ARegion *region);+/**+ * Draw a string hint if the file list is invalid.+ * \return true if the list is invalid and a hint was drawn.+ */+bool file_draw_hint_if_invalid(const bContext *C, const SpaceFile *sfile, ARegion *region);++void file_draw_check_ex(bContext *C, ScrArea *area);+void file_draw_check(bContext *C);+/**+ * For use with; #block_func_set.+ */+void file_draw_check_cb(bContext *C, void *arg1, void *arg2);+bool file_draw_check_exists(SpaceFile *sfile);++/* file_ops.h */++struct wmOperator;+struct wmOperatorType;++void FILE_OT_highlight(wmOperatorType *ot);+void FILE_OT_sort_column_ui_context(wmOperatorType *ot);+void FILE_OT_select(wmOperatorType *ot);+void FILE_OT_select_walk(wmOperatorType *ot);+void FILE_OT_select_all(wmOperatorType *ot);+void FILE_OT_select_box(wmOperatorType *ot);+void FILE_OT_select_bookmark(wmOperatorType *ot);+void FILE_OT_bookmark_add(wmOperatorType *ot);+void FILE_OT_bookmark_delete(wmOperatorType *ot);+void FILE_OT_bookmark_cleanup(wmOperatorType *ot);+void FILE_OT_bookmark_move(wmOperatorType *ot);+void FILE_OT_reset_recent(wmOperatorType *ot);+void FILE_OT_hidedot(wmOperatorType *ot);+void FILE_OT_execute(wmOperatorType *ot);++void FILE_OT_external_operation(wmOperatorType *ot);+void file_external_operations_menu_register();++/**+ * Variation of #FILE_OT_execute that accounts for some mouse specific handling.+ * Otherwise calls the same logic.+ */+void FILE_OT_mouse_execute(wmOperatorType *ot);+void FILE_OT_cancel(wmOperatorType *ot);+void FILE_OT_parent(wmOperatorType *ot);+void FILE_OT_directory_new(wmOperatorType *ot);+void FILE_OT_previous(wmOperatorType *ot);+void FILE_OT_next(wmOperatorType *ot);+void FILE_OT_refresh(wmOperatorType *ot);+void FILE_OT_filenum(wmOperatorType *ot);+void FILE_OT_delete(wmOperatorType *ot);+void FILE_OT_rename(wmOperatorType *ot);+void FILE_OT_smoothscroll(wmOperatorType *ot);+void FILE_OT_filepath_drop(wmOperatorType *ot);+void FILE_OT_start_filter(wmOperatorType *ot);+void FILE_OT_edit_directory_path(wmOperatorType *ot);+void FILE_OT_view_selected(wmOperatorType *ot);++/**+ * This callback runs when the user has entered a new path in the file selectors directory field.+ *+ * Expand & normalize the path then:+ * - Change the path when it exists.+ * - Prompt the user to create the path if it doesn't+ * (providing it passes basic sanity checks).+ */+void file_directory_enter_handle(bContext *C, void *arg_unused, void *arg_but);+void file_filename_enter_handle(bContext *C, void *arg_unused, void *arg_but);++int file_highlight_set(SpaceFile *sfile, ARegion *region, int mx, int my);++/**+ * Use to set the file selector path from some arbitrary source.+ */+void file_sfile_filepath_set(SpaceFile *sfile, const char *filepath);+void file_sfile_to_operator_ex(+ bContext *C, Main *bmain, wmOperator *op, SpaceFile *sfile, char *filepath);+void file_sfile_to_operator(bContext *C, Main *bmain, wmOperator *op, SpaceFile *sfile);++void file_operator_to_sfile(Main *bmain, SpaceFile *sfile, wmOperator *op);++/* `space_file.cc` */++extern "C" const char *file_context_dir[]; /* doc access */++/* `filesel.cc` */++void fileselect_refresh_params(SpaceFile *sfile);+/**+ * Sets #FileSelectParams.file (name of selected file)+ */+void fileselect_file_set(bContext *C, SpaceFile *sfile, int index);+bool file_attribute_column_type_enabled(const FileSelectParams *params,+ FileAttributeColumnType column,+ const FileLayout *layout);+/**+ * Check if the region coordinate defined by \a x and \a y are inside the column header.+ */+bool file_attribute_column_header_is_inside(const View2D *v2d,+ const FileLayout *layout,+ int x,+ int y);+/**+ * Find the column type at region coordinate given by \a x (y doesn't matter for this).+ */+FileAttributeColumnType file_attribute_column_type_find_isect(const View2D *v2d,+ const FileSelectParams *params,+ FileLayout *layout,+ int x);+float file_string_width(const char *str);++float file_font_pointsize();+void file_select_deselect_all(SpaceFile *sfile, eDirEntry_SelectFlag flag);+int file_select_match(SpaceFile *sfile, const char *pattern, char *matched_file);+int autocomplete_directory(bContext *C, char *str, void *arg_v);+int autocomplete_file(bContext *C, char *str, void *arg_v);++void file_params_smoothscroll_timer_clear(wmWindowManager *wm, wmWindow *win, SpaceFile *sfile);+void file_params_renamefile_clear(FileSelectParams *params);+/**+ * Set the renaming-state to #FILE_PARAMS_RENAME_POSTSCROLL_PENDING and trigger the smooth-scroll+ * timer. To be used right after a file was renamed.+ * Note that the caller is responsible for setting the correct rename-file info+ * (#FileSelectParams.renamefile or #FileSelectParams.rename_id).+ */+void file_params_invoke_rename_postscroll(wmWindowManager *wm, wmWindow *win, SpaceFile *sfile);+/**+ * To be executed whenever renaming ends (successfully or not).+ */+void file_params_rename_end(wmWindowManager *wm,+ wmWindow *win,+ SpaceFile *sfile,+ const FileDirEntry *rename_file);+/**+ * Helper used by both main update code, and smooth-scroll timer,+ * to try to enable rename editing from #FileSelectParams.renamefile name.+ */+void file_params_renamefile_activate(SpaceFile *sfile, FileSelectParams *params);++/**+ * Information about the current state of banners that needs preserving over redraws.+ */+struct BannersState {+ bool any_visible;+};++using onReloadFnData = void *;+using onReloadFn = void (*)(SpaceFile *space_data, onReloadFnData custom_data);+struct SpaceFile_Runtime {+ /* Called once after the file browser has reloaded. Reset to NULL after calling.+ * Use file_on_reload_callback_register() to register a callback. */+ onReloadFn on_reload;+ onReloadFnData on_reload_custom_data;++ /* Indicates, if the current filepath is a blendfile library one, if its status has been checked,+ * and if it is readable. */+ bool is_blendfile_status_set;+ bool is_blendfile_readable;+ ReportList is_blendfile_readable_reports;++ BannersState banners_state;+};++/**+ * Register an on-reload callback function. Note that there can only be one such function at a+ * time; registering a new one will overwrite the previous one.+ */+void file_on_reload_callback_register(SpaceFile *sfile,+ onReloadFn callback,+ onReloadFnData custom_data);++/* folder_history.cc */++/* not listbase itself */+void folderlist_free(ListBaseT<FolderList> *folderlist);+void folderlist_popdir(ListBaseT<FolderList> *folderlist, char *dir);+void folderlist_pushdir(ListBaseT<FolderList> *folderlist, const char *dir);+const char *folderlist_peeklastdir(ListBaseT<FolderList> *folderlist);+bool folderlist_clear_next(SpaceFile *sfile);++void folder_history_list_ensure_for_active_browse_mode(SpaceFile *sfile);+void folder_history_list_free(SpaceFile *sfile);+ListBaseT<FileFolderHistory> folder_history_list_duplicate(ListBaseT<FileFolderHistory> *listbase);++/* `file_panels.cc` */++void file_tool_props_region_panels_register(ARegionType *art);+void file_execute_region_panels_register(ARegionType *art);+void file_tools_region_panels_register(ARegionType *art);++/* `file_utils.cc` */++void file_tile_boundbox(const ARegion *region, FileLayout *layout, int file, rcti *r_bounds);++/**+ * If \a path leads to a .blend, remove the trailing slash (if needed).+ */+void file_path_to_ui_path(const char *path, MutableCStr r_path);++/* asset_catalog_tree_view.cc */++namespace ed::asset_browser {++void file_create_asset_catalog_tree_view_in_layout(const bContext *C,+ asset_system::AssetLibrary *asset_library,+ ui::Layout &layout,+ SpaceFile *space_file,+ FileAssetSelectParams *params);++class AssetCatalogFilterSettings;++AssetCatalogFilterSettings *file_create_asset_catalog_filter_settings();+void file_delete_asset_catalog_filter_settings(AssetCatalogFilterSettings **filter_settings);+/**+ * \return True if the file list should update its filtered results+ * (e.g. because filtering parameters changed).+ */+bool file_set_asset_catalog_filter_settings(+ AssetCatalogFilterSettings *filter_settings,+ eFileSel_Params_AssetCatalogVisibility catalog_visibility,+ const bUUID &catalog_id);+void file_ensure_updated_catalog_filter_data(AssetCatalogFilterSettings *filter_settings,+ const asset_system::AssetLibrary *asset_library);+bool file_is_asset_visible_in_catalog_filter_settings(+ const AssetCatalogFilterSettings *filter_settings, const AssetMetaData *asset_data);++} // namespace ed::asset_browser++} // namespace blenderdiff --git a/ui/space_file/file_ops.cc b/ui/space_file/file_ops.ccnew file mode 100644index 0000000..3f67cf1--- /dev/null+++ b/ui/space_file/file_ops.cc@@ -0,0 +1,3445 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "BLI_fileops.hh"+#include "BLI_linklist.h"+#include "BLI_listbase.h"+#include "BLI_math_base.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_string_utf8.h"+#include "BLI_utildefines.h"++#include "BKE_appdir.hh"+#include "BKE_blendfile.hh"+#include "BKE_context.hh"+#include "BKE_main.hh"+#include "BKE_report.hh"+#include "BKE_screen.hh"++#include "BLT_translation.hh"++#ifdef WIN32+# include "BLI_winstuff.hh"+#endif++#include "ED_fileselect.hh"+#include "ED_screen.hh"+#include "ED_select_utils.hh"++#include "UI_interface.hh"+#include "UI_interface_icons.hh"+#include "UI_interface_layout.hh"+#include "UI_resources.hh"++#include "MEM_guardedalloc.h"++#include "RNA_access.hh"+#include "RNA_define.hh"++#include "UI_view2d.hh"++#include "WM_api.hh"+#include "WM_types.hh"++#include "file_intern.hh"+#include "filelist.hh"+#include "fsmenu.hh"++#include <algorithm>+#include <cctype>+#include <cerrno>+#include <cstdio>+#include <cstdlib>+#include <cstring>++namespace blender {++/* -------------------------------------------------------------------- */+/** \name File Selection Utilities+ * \{ */++static FileSelection find_file_mouse_rect(SpaceFile *sfile,+ ARegion *region,+ const rcti *rect_region)+{+ FileSelection sel;++ View2D *v2d = ®ion->v2d;+ rcti rect_view;+ rctf rect_view_fl;+ rctf rect_region_fl;++ BLI_rctf_rcti_copy(&rect_region_fl, rect_region);++ /* Okay, manipulating v2d rects here is hacky... */+ v2d->mask.ymax -= sfile->layout->offset_top;+ v2d->cur.ymax -= sfile->layout->offset_top;+ ui::view2d_region_to_view_rctf(v2d, &rect_region_fl, &rect_view_fl);+ v2d->mask.ymax += sfile->layout->offset_top;+ v2d->cur.ymax += sfile->layout->offset_top;++ BLI_rcti_init(&rect_view,+ int(v2d->tot.xmin + rect_view_fl.xmin),+ int(v2d->tot.xmin + rect_view_fl.xmax),+ int(v2d->tot.ymax - rect_view_fl.ymin),+ int(v2d->tot.ymax - rect_view_fl.ymax));++ sel = ED_fileselect_layout_offset_rect(sfile->layout, &rect_view);++ return sel;+}++enum FileSelect {+ FILE_SELECT_NOTHING = 0,+ FILE_SELECT_DIR = 1,+ FILE_SELECT_FILE = 2,+};++static void clamp_to_filelist(int numfiles, FileSelection *sel)+{+ /* box select before the first file */+ if ((sel->first < 0) && (sel->last >= 0)) {+ sel->first = 0;+ }+ /* don't select if everything is outside filelist */+ if ((sel->first >= numfiles) && ((sel->last < 0) || (sel->last >= numfiles))) {+ sel->first = -1;+ sel->last = -1;+ }++ /* fix if last file invalid */+ if ((sel->first > 0) && (sel->last < 0)) {+ sel->last = numfiles - 1;+ }++ /* clamp */+ if (sel->first >= numfiles) {+ sel->first = numfiles - 1;+ }+ if (sel->last >= numfiles) {+ sel->last = numfiles - 1;+ }+}++static FileSelection file_selection_get(bContext *C, const rcti *rect, bool fill)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ int numfiles = filelist_files_ensure(sfile->files);+ FileSelection sel;++ sel = find_file_mouse_rect(sfile, region, rect);+ if (!((sel.first == -1) && (sel.last == -1))) {+ clamp_to_filelist(numfiles, &sel);+ }++ /* if desired, fill the selection up from the last selected file to the current one */+ if (fill && (sel.last >= 0) && (sel.last < numfiles)) {+ int f;+ /* Try to find a smaller-index selected item. */+ for (f = sel.last; f >= 0; f--) {+ if (filelist_entry_select_index_get(sfile->files, f, CHECK_ALL)) {+ break;+ }+ }+ if (f >= 0) {+ sel.first = f + 1;+ }+ /* If none found, try to find a higher-index selected item. */+ else {+ for (f = sel.first; f < numfiles; f++) {+ if (filelist_entry_select_index_get(sfile->files, f, CHECK_ALL)) {+ break;+ }+ }+ if (f < numfiles) {+ sel.last = f - 1;+ }+ }+ }+ return sel;+}++static FileSelect file_select_do(bContext *C, int selected_idx, bool do_diropen)+{+ Main *bmain = CTX_data_main(C);+ FileSelect retval = FILE_SELECT_NOTHING;+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ int numfiles = filelist_files_ensure(sfile->files);+ const FileDirEntry *file;++ /* make the selected file active */+ if ((selected_idx >= 0) && (selected_idx < numfiles) &&+ (file = filelist_file(sfile->files, selected_idx)))+ {+ params->highlight_file = selected_idx;+ params->active_file = selected_idx;++ if (file->typeflag & FILE_TYPE_DIR) {+ const bool is_parent_dir = FILENAME_IS_PARENT(file->relpath);++ if (do_diropen == false) {+ retval = FILE_SELECT_DIR;+ }+ /* the path is too long and we are not going up! */+ else if (!is_parent_dir && strlen(params->dir) + strlen(file->relpath) >= FILE_MAX) {+ // XXX error("Path too long, cannot enter this directory");+ }+ else {+ if (is_parent_dir) {+ /* Avoids `/../../`. */+ BLI_path_parent_dir(params->dir);++ if (params->recursion_level > 1) {+ /* Disable `dirtree` recursion when going up in tree. */+ params->recursion_level = 0;+ filelist_setrecursion(sfile->files, params->recursion_level);+ }+ }+ else if (file->redirection_path) {+ STRNCPY(params->dir, file->redirection_path);+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_dir(params->dir);+ }+ else {+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_dir(params->dir);+ BLI_path_append_dir(params->dir, file->relpath);+ }++ ED_file_change_dir(C);+ retval = FILE_SELECT_DIR;+ }+ }+ else {+ retval = FILE_SELECT_FILE;+ }+ fileselect_file_set(C, sfile, selected_idx);+ }+ return retval;+}++/**+ * \warning Loops over all files so better use cautiously.+ */+static bool file_is_any_selected(FileList *files)+{+ const int numfiles = filelist_files_ensure(files);+ int i;++ /* Is any file selected ? */+ for (i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(files, i, CHECK_ALL)) {+ return true;+ }+ }++ return false;+}++static FileSelection file_current_selection_range_get(FileList *files)+{+ const int numfiles = filelist_files_ensure(files);+ FileSelection selection = {-1, -1};++ /* Iterate over the files once but in two loops, one to find the first selected file, and the+ * other to find the last. */++ int file_index;+ for (file_index = 0; file_index < numfiles; file_index++) {+ if (filelist_entry_is_selected(files, file_index)) {+ /* First selected entry found. */+ selection.first = file_index;+ break;+ }+ }++ for (; file_index < numfiles; file_index++) {+ if (filelist_entry_is_selected(files, file_index)) {+ selection.last = file_index;+ /* Keep looping, we may find more selected files. */+ }+ }++ return selection;+}++/**+ * If \a file is outside viewbounds, this adjusts view to make sure it's inside+ */+static void file_ensure_inside_viewbounds(ARegion *region, SpaceFile *sfile, const int file)+{+ FileLayout *layout = ED_fileselect_get_layout(sfile, region);+ rctf *cur = ®ion->v2d.cur;+ rcti rect;+ bool changed = true;++ file_tile_boundbox(region, layout, file, &rect);++ /* down - also use if tile is higher than viewbounds so view is aligned to file name */+ if (cur->ymin > rect.ymin || layout->tile_h > region->winy) {+ cur->ymin = rect.ymin - (2 * layout->tile_border_y);+ cur->ymax = cur->ymin + region->winy;+ }+ /* up */+ else if ((cur->ymax - layout->offset_top) < rect.ymax) {+ cur->ymax = rect.ymax + layout->tile_border_y + layout->offset_top;+ cur->ymin = cur->ymax - region->winy;+ }+ /* left - also use if tile is wider than viewbounds so view is aligned to file name */+ else if (cur->xmin > rect.xmin || layout->tile_w > region->winx) {+ cur->xmin = rect.xmin - layout->tile_border_x;+ cur->xmax = cur->xmin + region->winx;+ }+ /* right */+ else if (cur->xmax < rect.xmax) {+ cur->xmax = rect.xmax + (2 * layout->tile_border_x);+ cur->xmin = cur->xmax - region->winx;+ }+ else {+ BLI_assert(cur->xmin <= rect.xmin && cur->xmax >= rect.xmax && cur->ymin <= rect.ymin &&+ (cur->ymax - layout->offset_top) >= rect.ymax);+ changed = false;+ }++ if (changed) {+ ui::view2d_curRect_validate(®ion->v2d);+ }+}++static void file_ensure_selection_inside_viewbounds(ARegion *region,+ SpaceFile *sfile,+ FileSelection *sel)+{+ const FileLayout *layout = ED_fileselect_get_layout(sfile, region);++ if (((layout->flag & FILE_LAYOUT_HOR) && region->winx <= (1.2f * layout->tile_w)) &&+ ((layout->flag & FILE_LAYOUT_VER) && region->winy <= (2.0f * layout->tile_h)))+ {+ return;+ }++ /* Adjust view to display selection. Doing iterations for first and last+ * selected item makes view showing as much of the selection possible.+ * Not really useful if tiles are (almost) bigger than viewbounds though. */+ file_ensure_inside_viewbounds(region, sfile, sel->last);+ file_ensure_inside_viewbounds(region, sfile, sel->first);+}++static FileSelect file_select(+ bContext *C, const rcti *rect, FileSelType select, bool fill, bool do_diropen)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileSelect retval = FILE_SELECT_NOTHING;+ FileSelection sel = file_selection_get(C, rect, fill); /* get the selection */+ const FileCheckType check_type = (params->flag & FILE_DIRSEL_ONLY) ? CHECK_DIRS : CHECK_ALL;++ /* flag the files as selected in the filelist */+ filelist_entries_select_index_range_set(+ sfile->files, &sel, select, FILE_SEL_SELECTED, check_type);++ /* Don't act on multiple selected files */+ if (sel.first != sel.last) {+ select = FileSelType(0);+ }++ /* Do we have a valid selection and are we actually selecting */+ if ((sel.last >= 0) && (select != FILE_SEL_REMOVE)) {+ /* Check last selection, if selected, act on the file or dir */+ if (filelist_entry_select_index_get(sfile->files, sel.last, check_type)) {+ retval = file_select_do(C, sel.last, do_diropen);+ }+ }++ if (select != FILE_SEL_ADD && !file_is_any_selected(sfile->files)) {+ params->active_file = -1;+ }+ else if (sel.last >= 0) {+ ARegion *region = CTX_wm_region(C);+ file_ensure_selection_inside_viewbounds(region, sfile, &sel);+ }++ /* update operator for name change event */+ file_draw_check(C);++ return retval;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Bookmark Utilities+ * \{ */++/**+ * Local utility to write #BLENDER_BOOKMARK_FILE, reporting an error on failure.+ */+static bool fsmenu_write_file_and_refresh_or_report_error(FSMenu *fsmenu,+ ScrArea *area,+ ReportList *reports)+{+ /* NOTE: use warning instead of error here, because the bookmark operation may be part of+ * other actions which should not cause the operator to fail entirely. */+ const std::optional<std::string> cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG,+ nullptr);+ if (!cfgdir.has_value()) {+ BKE_report(reports, RPT_ERROR, "Unable to create configuration directory to write bookmarks");+ return false;+ }++ char filepath[FILE_MAX];+ BLI_path_join(filepath, cfgdir->c_str(), BLENDER_BOOKMARK_FILE);+ if (!fsmenu_write_file(fsmenu, filepath)) {+ BKE_reportf(reports, RPT_ERROR, "Unable to open or write bookmark file \"%s\"", filepath);+ return false;+ }++ ED_area_tag_refresh(area);+ ED_area_tag_redraw(area);+ return true;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Box Select Operator+ * \{ */++static int file_box_select_find_last_selected(SpaceFile *sfile,+ ARegion *region,+ const FileSelection *sel,+ const int mouse_xy[2])+{+ FileLayout *layout = ED_fileselect_get_layout(sfile, region);+ rcti bounds_first, bounds_last;+ int dist_first, dist_last;+ float mouseco_view[2];++ ui::view2d_region_to_view(®ion->v2d, UNPACK2(mouse_xy), &mouseco_view[0], &mouseco_view[1]);++ file_tile_boundbox(region, layout, sel->first, &bounds_first);+ file_tile_boundbox(region, layout, sel->last, &bounds_last);++ /* are first and last in the same column (horizontal layout)/row (vertical layout)? */+ if ((layout->flag & FILE_LAYOUT_HOR && bounds_first.xmin == bounds_last.xmin) ||+ (layout->flag & FILE_LAYOUT_VER && bounds_first.ymin != bounds_last.ymin))+ {+ /* use vertical distance */+ const int my_loc = int(mouseco_view[1]);+ dist_first = BLI_rcti_length_y(&bounds_first, my_loc);+ dist_last = BLI_rcti_length_y(&bounds_last, my_loc);+ }+ else {+ /* use horizontal distance */+ const int mx_loc = int(mouseco_view[0]);+ dist_first = BLI_rcti_length_x(&bounds_first, mx_loc);+ dist_last = BLI_rcti_length_x(&bounds_last, mx_loc);+ }++ return (dist_first < dist_last) ? sel->first : sel->last;+}++static wmOperatorStatus file_box_select_modal(bContext *C, wmOperator *op, const wmEvent *event)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileSelection sel;+ rcti rect;++ wmOperatorStatus result;++ result = WM_gesture_box_modal(C, op, event);++ if (result == OPERATOR_RUNNING_MODAL) {+ WM_operator_properties_border_to_rcti(op, &rect);++ ED_fileselect_layout_isect_rect(sfile->layout, ®ion->v2d, &rect, &rect);++ sel = file_selection_get(C, &rect, false);+ if ((sel.first != params->sel_first) || (sel.last != params->sel_last)) {+ int idx;++ file_select_deselect_all(sfile, FILE_SEL_HIGHLIGHTED);+ filelist_entries_select_index_range_set(+ sfile->files, &sel, FILE_SEL_ADD, FILE_SEL_HIGHLIGHTED, CHECK_ALL);+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);++ for (idx = sel.last; idx >= 0; idx--) {+ const FileDirEntry *file = filelist_file(sfile->files, idx);++ /* Don't highlight read-only file (".." or ".") on box select. */+ if (FILENAME_IS_CURRPAR(file->relpath)) {+ filelist_entry_select_set(+ sfile->files, file, FILE_SEL_REMOVE, FILE_SEL_HIGHLIGHTED, CHECK_ALL);+ }++ /* make sure highlight_file is no readonly file */+ if (sel.last == idx) {+ params->highlight_file = idx;+ }+ }+ }+ params->sel_first = sel.first;+ params->sel_last = sel.last;+ params->active_file = file_box_select_find_last_selected(sfile, region, &sel, event->mval);+ }+ else {+ params->highlight_file = -1;+ params->sel_first = params->sel_last = -1;+ fileselect_file_set(C, sfile, params->active_file);+ file_select_deselect_all(sfile, FILE_SEL_HIGHLIGHTED);+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ }++ return result;+}++static wmOperatorStatus file_box_select_exec(bContext *C, wmOperator *op)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ rcti rect;+ FileSelect ret;++ if (sfile->files == nullptr || sfile->layout == nullptr) {+ return OPERATOR_CANCELLED;+ }++ WM_operator_properties_border_to_rcti(op, &rect);++ const eSelectOp sel_op = eSelectOp(RNA_enum_get(op->ptr, "mode"));+ const bool select = (sel_op != SEL_OP_SUB);+ if (SEL_OP_USE_PRE_DESELECT(sel_op)) {+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);+ }++ ED_fileselect_layout_isect_rect(sfile->layout, ®ion->v2d, &rect, &rect);++ ret = file_select(C, &rect, select ? FILE_SEL_ADD : FILE_SEL_REMOVE, false, false);++ /* unselect '..' parent entry - it's not supposed to be selected if more than+ * one file is selected */+ filelist_entry_parent_select_set(sfile->files, FILE_SEL_REMOVE, FILE_SEL_SELECTED, CHECK_ALL);++ if (FILE_SELECT_DIR == ret) {+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+ }+ else if (FILE_SELECT_FILE == ret) {+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ }+ return OPERATOR_FINISHED;+}++void FILE_OT_select_box(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Box Select";+ ot->description = "Activate/select the file(s) contained in the border";+ ot->idname = "FILE_OT_select_box";++ /* API callbacks. */+ ot->invoke = WM_gesture_box_invoke;+ ot->exec = file_box_select_exec;+ ot->modal = file_box_select_modal;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;+ ot->cancel = WM_gesture_box_cancel;++ /* properties */+ WM_operator_properties_gesture_box(ot);+ WM_operator_properties_select_operation_simple(ot);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Select Pick Operator+ * \{ */++static rcti file_select_mval_to_select_rect(const int mval[2])+{+ rcti rect;+ rect.xmin = rect.xmax = mval[0];+ rect.ymin = rect.ymax = mval[1];+ return rect;+}++static wmOperatorStatus file_select_exec(bContext *C, wmOperator *op)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelect ret;+ rcti rect;+ const bool extend = RNA_boolean_get(op->ptr, "extend");+ const bool fill = RNA_boolean_get(op->ptr, "fill");+ const bool do_diropen = RNA_boolean_get(op->ptr, "open");+ const bool deselect_all = RNA_boolean_get(op->ptr, "deselect_all");+ const bool only_activate_if_selected = RNA_boolean_get(op->ptr, "only_activate_if_selected");+ /* Used so right mouse clicks can do both, activate and spawn the context menu. */+ const bool pass_through = RNA_boolean_get(op->ptr, "pass_through");+ bool wait_to_deselect_others = RNA_boolean_get(op->ptr, "wait_to_deselect_others");++ int mval[2];+ mval[0] = RNA_int_get(op->ptr, "mouse_x");+ mval[1] = RNA_int_get(op->ptr, "mouse_y");+ rect = file_select_mval_to_select_rect(mval);++ if (sfile->files == nullptr || sfile->layout == nullptr) {+ return OPERATOR_CANCELLED;+ }+ if (!ED_fileselect_layout_is_inside_pt(sfile->layout, ®ion->v2d, rect.xmin, rect.ymin)) {+ return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;+ }++ if (extend || fill) {+ wait_to_deselect_others = false;+ }++ wmOperatorStatus ret_val = OPERATOR_FINISHED;++ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params) {+ int idx = params->highlight_file;+ int numfiles = filelist_files_ensure(sfile->files);++ if ((idx >= 0) && (idx < numfiles)) {+ const bool is_selected = filelist_entry_select_index_get(sfile->files, idx, CHECK_ALL) &+ FILE_SEL_SELECTED;+ if (only_activate_if_selected && is_selected) {+ /* Don't deselect other items. */+ }+ else if (wait_to_deselect_others && is_selected) {+ ret_val = OPERATOR_RUNNING_MODAL;+ }+ /* single select, deselect all selected first */+ else if (!extend) {+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);+ }+ }+ }++ ret = file_select(C, &rect, extend ? FILE_SEL_TOGGLE : FILE_SEL_ADD, fill, do_diropen);++ if (extend) {+ /* unselect '..' parent entry - it's not supposed to be selected if more+ * than one file is selected */+ filelist_entry_parent_select_set(sfile->files, FILE_SEL_REMOVE, FILE_SEL_SELECTED, CHECK_ALL);+ }++ if (ret == FILE_SELECT_NOTHING) {+ if (deselect_all) {+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);+ }+ }+ else if (ret == FILE_SELECT_DIR) {+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+ }+ else if (ret == FILE_SELECT_FILE) {+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ }++ WM_event_add_mousemove(CTX_wm_window(C)); /* for directory changes */+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);++ if ((ret_val == OPERATOR_FINISHED) && pass_through) {+ ret_val |= OPERATOR_PASS_THROUGH;+ }+ return ret_val;+}++void FILE_OT_select(wmOperatorType *ot)+{+ PropertyRNA *prop;++ /* identifiers */+ ot->name = "Select";+ ot->idname = "FILE_OT_select";+ ot->description = "Handle mouse clicks to select and activate items";++ /* API callbacks. */+ ot->invoke = WM_generic_select_invoke;+ ot->exec = file_select_exec;+ ot->modal = WM_generic_select_modal;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_region_file_active;++ /* properties */+ WM_operator_properties_generic_select(ot);+ prop = RNA_def_boolean(ot->srna,+ "extend",+ false,+ "Extend",+ "Extend selection instead of deselecting everything first");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(+ ot->srna, "fill", false, "Fill", "Select everything beginning with the last selection");+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_EDITOR_FILEBROWSER);+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(ot->srna, "open", true, "Open", "Open a directory when selecting it");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(ot->srna,+ "deselect_all",+ false,+ "Deselect On Nothing",+ "Deselect all when nothing under the cursor");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(ot->srna,+ "only_activate_if_selected",+ false,+ "Only Activate if Selected",+ "Do not change selection if the item under the cursor is already "+ "selected, only activate it");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(ot->srna,+ "pass_through",+ false,+ "Pass Through",+ "Even on successful execution, pass the event on so other operators can "+ "execute on it as well");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Select Walk Operator+ * \{ */++/**+ * \returns true if selection has changed+ */+static bool file_walk_select_selection_set(bContext *C,+ wmWindow *win,+ ARegion *region,+ SpaceFile *sfile,+ const int direction,+ const int numfiles,+ const int active_old,+ const int active_new,+ const int other_site,+ const bool has_selection,+ const bool extend,+ const bool fill)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileList *files = sfile->files;+ const int last_sel = params->active_file; /* store old value */+ int active = active_old; /* could use active_old instead, just for readability */+ bool deselect = false;++ BLI_assert(params);++ if (numfiles == 0) {+ /* No files visible, nothing to do. */+ return false;+ }++ if (has_selection) {+ if (extend && filelist_entry_select_index_get(files, active_old, CHECK_ALL) &&+ filelist_entry_select_index_get(files, active_new, CHECK_ALL))+ {+ /* conditions for deselecting: initial file is selected, new file is+ * selected and either other_side isn't selected/found or we use fill */+ deselect = (fill || other_site == -1 ||+ !filelist_entry_select_index_get(files, other_site, CHECK_ALL));++ /* don't change highlight_file here since we either want to deselect active or we want+ * to walk through a block of selected files without selecting/deselecting anything */+ params->active_file = active_new;+ /* but we want to change active if we use fill+ * (needed to get correct selection bounds) */+ if (deselect && fill) {+ active = active_new;+ }+ }+ else {+ /* regular selection change */+ params->active_file = active = active_new;+ }+ }+ else {+ /* select last file */+ if (ELEM(direction, UI_SELECT_WALK_UP, UI_SELECT_WALK_LEFT)) {+ params->active_file = active = numfiles - 1;+ }+ /* select first file */+ else if (ELEM(direction, UI_SELECT_WALK_DOWN, UI_SELECT_WALK_RIGHT)) {+ params->active_file = active = 0;+ }+ else {+ BLI_assert(0);+ }+ }++ if (active < 0) {+ return false;+ }++ if (extend) {+ /* highlight the active walker file for extended selection for better visual feedback */+ params->highlight_file = params->active_file;++ /* unselect '..' parent entry - it's not supposed to be selected if more+ * than one file is selected */+ filelist_entry_parent_select_set(files, FILE_SEL_REMOVE, FILE_SEL_SELECTED, CHECK_ALL);+ }+ else {+ /* deselect all first */+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);++ /* highlight file under mouse pos */+ params->highlight_file = -1;+ WM_event_add_mousemove(win);+ }++ /* do the actual selection */+ if (fill) {+ FileSelection sel = {std::min(active, last_sel), std::max(active, last_sel)};++ /* fill selection between last and first selected file */+ filelist_entries_select_index_range_set(+ files, &sel, deselect ? FILE_SEL_REMOVE : FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ /* entire sel is cleared here, so select active again */+ if (deselect) {+ filelist_entry_select_index_set(files, active, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ }++ /* unselect '..' parent entry - it's not supposed to be selected if more+ * than one file is selected */+ if ((sel.last - sel.first) > 1) {+ filelist_entry_parent_select_set(files, FILE_SEL_REMOVE, FILE_SEL_SELECTED, CHECK_ALL);+ }+ }+ else {+ filelist_entry_select_index_set(+ files, active, deselect ? FILE_SEL_REMOVE : FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ }++ BLI_assert(IN_RANGE(active, -1, numfiles));+ fileselect_file_set(C, sfile, params->active_file);++ /* ensure newly selected file is inside viewbounds */+ file_ensure_inside_viewbounds(region, sfile, params->active_file);++ /* selection changed */+ return true;+}++/**+ * \returns true if selection has changed+ */+static bool file_walk_select_do(bContext *C,+ SpaceFile *sfile,+ FileSelectParams *params,+ const int direction,+ const bool extend,+ const bool fill)+{+ wmWindow *win = CTX_wm_window(C);+ ARegion *region = CTX_wm_region(C);+ FileList *files = sfile->files;+ const int numfiles = filelist_files_ensure(files);+ const bool has_selection = file_is_any_selected(files);+ const int active_old = params->active_file;+ int active_new = -1;+ int other_site = -1; /* file on the other site of active_old */++ /* *** get all needed files for handling selection *** */++ if (numfiles == 0) {+ /* No files visible, nothing to do. */+ return false;+ }++ if (has_selection) {+ FileLayout *layout = ED_fileselect_get_layout(sfile, region);+ const int idx_shift = (layout->flag & FILE_LAYOUT_HOR) ? layout->rows : layout->flow_columns;++ if ((layout->flag & FILE_LAYOUT_HOR && direction == UI_SELECT_WALK_UP) ||+ (layout->flag & FILE_LAYOUT_VER && direction == UI_SELECT_WALK_LEFT))+ {+ active_new = active_old - 1;+ other_site = active_old + 1;+ }+ else if ((layout->flag & FILE_LAYOUT_HOR && direction == UI_SELECT_WALK_DOWN) ||+ (layout->flag & FILE_LAYOUT_VER && direction == UI_SELECT_WALK_RIGHT))+ {+ active_new = active_old + 1;+ other_site = active_old - 1;+ }+ else if ((layout->flag & FILE_LAYOUT_HOR && direction == UI_SELECT_WALK_LEFT) ||+ (layout->flag & FILE_LAYOUT_VER && direction == UI_SELECT_WALK_UP))+ {+ active_new = active_old - idx_shift;+ other_site = active_old + idx_shift;+ }+ else if ((layout->flag & FILE_LAYOUT_HOR && direction == UI_SELECT_WALK_RIGHT) ||+ (layout->flag & FILE_LAYOUT_VER && direction == UI_SELECT_WALK_DOWN))+ {++ active_new = active_old + idx_shift;+ other_site = active_old - idx_shift;+ }+ else {+ BLI_assert(0);+ }++ if (!IN_RANGE(active_new, -1, numfiles)) {+ if (extend) {+ /* extend to invalid file -> abort */+ return false;+ }+ /* if we don't extend, selecting '..' (index == 0) is allowed so+ * using key selection to go to parent directory is possible */+ if (active_new != 0) {+ /* select initial file */+ active_new = active_old;+ }+ }+ if (!IN_RANGE(other_site, 0, numfiles)) {+ other_site = -1;+ }+ }++ return file_walk_select_selection_set(C,+ win,+ region,+ sfile,+ direction,+ numfiles,+ active_old,+ active_new,+ other_site,+ has_selection,+ extend,+ fill);+}++static wmOperatorStatus file_walk_select_invoke(bContext *C,+ wmOperator *op,+ const wmEvent * /*event*/)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(CTX_wm_space_data(C));+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const int direction = RNA_enum_get(op->ptr, "direction");+ const bool extend = RNA_boolean_get(op->ptr, "extend");+ const bool fill = RNA_boolean_get(op->ptr, "fill");++ if (file_walk_select_do(C, sfile, params, direction, extend, fill)) {+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ return OPERATOR_FINISHED;+ }++ return OPERATOR_CANCELLED;+}++void FILE_OT_select_walk(wmOperatorType *ot)+{+ PropertyRNA *prop;++ /* identifiers */+ ot->name = "Walk Select/Deselect File";+ ot->description = "Select/Deselect files by walking through them";+ ot->idname = "FILE_OT_select_walk";++ /* API callbacks. */+ ot->invoke = file_walk_select_invoke;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;++ /* properties */+ WM_operator_properties_select_walk_direction(ot);+ prop = RNA_def_boolean(ot->srna,+ "extend",+ false,+ "Extend",+ "Extend selection instead of deselecting everything first");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(+ ot->srna, "fill", false, "Fill", "Select everything beginning with the last selection");+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_EDITOR_FILEBROWSER);+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Select All Operator+ * \{ */++static wmOperatorStatus file_select_all_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileSelection sel;++ if (sfile->files == nullptr || params == nullptr) {+ return OPERATOR_CANCELLED;+ }++ const int numfiles = filelist_files_ensure(sfile->files);+ int action = RNA_enum_get(op->ptr, "action");++ if (action == SEL_TOGGLE) {+ action = file_is_any_selected(sfile->files) ? SEL_DESELECT : SEL_SELECT;+ }++ sel.first = 0;+ sel.last = numfiles - 1;++ FileCheckType check_type;+ FileSelType filesel_type;++ switch (action) {+ case SEL_SELECT:+ case SEL_INVERT: {+ check_type = (params->flag & FILE_DIRSEL_ONLY) ? CHECK_DIRS : CHECK_FILES;+ filesel_type = (action == SEL_INVERT) ? FILE_SEL_TOGGLE : FILE_SEL_ADD;+ break;+ }+ case SEL_DESELECT: {+ check_type = CHECK_ALL;+ filesel_type = FILE_SEL_REMOVE;+ break;+ }+ default: {+ BLI_assert(0);+ return OPERATOR_CANCELLED;+ }+ }++ filelist_entries_select_index_range_set(+ sfile->files, &sel, filesel_type, FILE_SEL_SELECTED, check_type);++ params->active_file = -1;+ if (action != SEL_DESELECT) {+ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, check_type)) {+ params->active_file = i;+ break;+ }+ }+ }++ file_draw_check(C);+ WM_event_add_mousemove(CTX_wm_window(C));+ ED_area_tag_redraw(area);++ return OPERATOR_FINISHED;+}++void FILE_OT_select_all(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "(De)select All Files";+ ot->description = "Select or deselect all files";+ ot->idname = "FILE_OT_select_all";++ /* API callbacks. */+ ot->exec = file_select_all_exec;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;++ /* properties */+ WM_operator_properties_select_all(ot);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name View Selected Operator+ * \{ */++static wmOperatorStatus file_view_selected_exec(bContext *C, wmOperator * /*op*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (sfile->files == nullptr || params == nullptr) {+ return OPERATOR_CANCELLED;+ }++ FileSelection sel = file_current_selection_range_get(sfile->files);++ if (sel.first == -1 && sel.last == -1 && params->active_file == -1) {+ /* Nothing was selected. */+ return OPERATOR_CANCELLED;+ }++ /* Extend the selection area with the active file, as it may not be selected but still is+ * important to have in view. NOTE: active_file gets -1 after a search has been cleared/updated.+ */+ if (params->active_file != -1) {+ if (sel.first == -1 || params->active_file < sel.first) {+ sel.first = params->active_file;+ }+ if (sel.last == -1 || params->active_file > sel.last) {+ sel.last = params->active_file;+ }+ }++ ScrArea *area = CTX_wm_area(C);+ ARegion *region = CTX_wm_region(C);+ file_ensure_selection_inside_viewbounds(region, sfile, &sel);++ file_draw_check(C);+ WM_event_add_mousemove(CTX_wm_window(C));+ ED_area_tag_redraw(area);++ return OPERATOR_FINISHED;+}++void FILE_OT_view_selected(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Frame Selected";+ ot->description = "Scroll the selected files into view";+ ot->idname = "FILE_OT_view_selected";++ /* API callbacks. */+ ot->exec = file_view_selected_exec;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Select Bookmark Operator+ * \{ */++/* Note we could get rid of this one, but it's used by some addon so...+ * Does not hurt keeping it around for now. */+static wmOperatorStatus bookmark_select_exec(bContext *C, wmOperator *op)+{+ Main *bmain = CTX_data_main(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ PropertyRNA *prop = RNA_struct_find_property(op->ptr, "dir");+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params == nullptr) [[unlikely]] {+ return OPERATOR_CANCELLED;+ }+ char entry[256];++ RNA_property_string_get(op->ptr, prop, entry);+ STRNCPY(params->dir, entry);+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_dir(params->dir);+ ED_file_change_dir(C);++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++void FILE_OT_select_bookmark(wmOperatorType *ot)+{+ PropertyRNA *prop;++ /* identifiers */+ ot->name = "Select Directory";+ ot->description = "Select a bookmarked directory";+ ot->idname = "FILE_OT_select_bookmark";++ /* API callbacks. */+ ot->exec = bookmark_select_exec;+ /* Bookmarks are for file browsing only (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;++ /* properties */+ prop = RNA_def_string(ot->srna, "dir", nullptr, FILE_MAXDIR, "Directory", "");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Add Bookmark Operator+ * \{ */++static wmOperatorStatus bookmark_add_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FSMenu *fsmenu = ED_fsmenu_get();+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (!params) {+ return OPERATOR_CANCELLED;+ }++ if (params->dir[0] != '\0') {++ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_BOOKMARKS, params->dir, nullptr, ICON_FILE_FOLDER, FS_INSERT_SAVE);+ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);+ }+ return OPERATOR_FINISHED;+}++void FILE_OT_bookmark_add(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Add Bookmark";+ ot->description = "Add a bookmark for the selected/active directory";+ ot->idname = "FILE_OT_bookmark_add";++ /* API callbacks. */+ ot->exec = bookmark_add_exec;+ /* Bookmarks are for file browsing only (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Delete Bookmark Operator+ * \{ */++static wmOperatorStatus bookmark_delete_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FSMenu *fsmenu = ED_fsmenu_get();+ int nentries = ED_fsmenu_get_nentries(fsmenu, FS_CATEGORY_BOOKMARKS);++ PropertyRNA *prop = RNA_struct_find_property(op->ptr, "index");+ const int index = RNA_property_is_set(op->ptr, prop) ? RNA_property_int_get(op->ptr, prop) :+ sfile->bookmarknr;+ if ((index > -1) && (index < nentries)) {+ fsmenu_remove_entry(fsmenu, FS_CATEGORY_BOOKMARKS, index);+ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_bookmark_delete(wmOperatorType *ot)+{+ PropertyRNA *prop;++ /* identifiers */+ ot->name = "Delete Bookmark";+ ot->description = "Delete selected bookmark";+ ot->idname = "FILE_OT_bookmark_delete";++ /* API callbacks. */+ ot->exec = bookmark_delete_exec;+ /* Bookmarks are for file browsing only (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;++ /* properties */+ prop = RNA_def_int(ot->srna, "index", -1, -1, 20000, "Index", "", -1, 20000);+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Cleanup Bookmark Operator+ * \{ */++static wmOperatorStatus bookmark_cleanup_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ FSMenu *fsmenu = ED_fsmenu_get();+ FSMenuEntry *fsme_next, *fsme = ED_fsmenu_get_category(fsmenu, FS_CATEGORY_BOOKMARKS);+ int index;+ bool changed = false;++ for (index = 0; fsme; fsme = fsme_next) {+ fsme_next = fsme->next;++ if (!BLI_is_dir(fsme->path)) {+ fsmenu_remove_entry(fsmenu, FS_CATEGORY_BOOKMARKS, index);+ changed = true;+ }+ else {+ index++;+ }+ }++ if (changed) {+ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_bookmark_cleanup(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Cleanup Bookmarks";+ ot->description = "Delete all invalid bookmarks";+ ot->idname = "FILE_OT_bookmark_cleanup";++ /* API callbacks. */+ ot->exec = bookmark_cleanup_exec;+ /* Bookmarks are for file browsing only (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;++ /* properties */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Reorder Bookmark Operator+ * \{ */++enum {+ FILE_BOOKMARK_MOVE_TOP = -2,+ FILE_BOOKMARK_MOVE_UP = -1,+ FILE_BOOKMARK_MOVE_DOWN = 1,+ FILE_BOOKMARK_MOVE_BOTTOM = 2,+};++static wmOperatorStatus bookmark_move_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FSMenu *fsmenu = ED_fsmenu_get();+ FSMenuEntry *fsmentry = ED_fsmenu_get_category(fsmenu, FS_CATEGORY_BOOKMARKS);+ const FSMenuEntry *fsmentry_org = fsmentry;++ const int direction = RNA_enum_get(op->ptr, "direction");+ const int totitems = ED_fsmenu_get_nentries(fsmenu, FS_CATEGORY_BOOKMARKS);+ const int act_index = sfile->bookmarknr;+ int new_index;++ if (totitems < 2) {+ return OPERATOR_CANCELLED;+ }++ switch (direction) {+ case FILE_BOOKMARK_MOVE_TOP:+ new_index = 0;+ break;+ case FILE_BOOKMARK_MOVE_BOTTOM:+ new_index = totitems - 1;+ break;+ case FILE_BOOKMARK_MOVE_UP:+ case FILE_BOOKMARK_MOVE_DOWN:+ default:+ new_index = (totitems + act_index + direction) % totitems;+ break;+ }++ if (new_index == act_index) {+ return OPERATOR_CANCELLED;+ }++ BLI_linklist_move_item(reinterpret_cast<LinkNode **>(&fsmentry), act_index, new_index);+ if (fsmentry != fsmentry_org) {+ ED_fsmenu_set_category(fsmenu, FS_CATEGORY_BOOKMARKS, fsmentry);+ }++ /* Need to update active bookmark number. */+ sfile->bookmarknr = new_index;++ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);++ return OPERATOR_FINISHED;+}++static bool file_bookmark_move_poll(bContext *C)+{+ SpaceFile *sfile = CTX_wm_space_file(C);++ /* Bookmarks are for file browsing only (not asset browsing). */+ if (!ED_operator_file_browsing_active(C)) {+ return false;+ }++ return sfile->bookmarknr != -1;+}++void FILE_OT_bookmark_move(wmOperatorType *ot)+{+ static const EnumPropertyItem slot_move[] = {+ {FILE_BOOKMARK_MOVE_TOP, "TOP", 0, "Top", "Top of the list"},+ {FILE_BOOKMARK_MOVE_UP, "UP", 0, "Up", ""},+ {FILE_BOOKMARK_MOVE_DOWN, "DOWN", 0, "Down", ""},+ {FILE_BOOKMARK_MOVE_BOTTOM, "BOTTOM", 0, "Bottom", "Bottom of the list"},+ {0, nullptr, 0, nullptr, nullptr}};++ /* identifiers */+ ot->name = "Move Bookmark";+ ot->idname = "FILE_OT_bookmark_move";+ ot->description = "Move the active bookmark up/down in the list";++ /* API callbacks. */+ ot->exec = bookmark_move_exec;+ ot->poll = file_bookmark_move_poll;++ /* flags */+ ot->flag = OPTYPE_REGISTER; /* No undo! */++ RNA_def_enum(ot->srna,+ "direction",+ slot_move,+ 0,+ "Direction",+ "Direction to move the active bookmark towards");+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Reset Recent Blend Files Operator+ * \{ */++static wmOperatorStatus reset_recent_exec(bContext *C, wmOperator *op)+{+ ScrArea *area = CTX_wm_area(C);+ FSMenu *fsmenu = ED_fsmenu_get();++ while (ED_fsmenu_get_entry(fsmenu, FS_CATEGORY_RECENT, 0) != nullptr) {+ fsmenu_remove_entry(fsmenu, FS_CATEGORY_RECENT, 0);+ }++ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);++ return OPERATOR_FINISHED;+}++void FILE_OT_reset_recent(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Reset Recent";+ ot->description = "Reset recent files";+ ot->idname = "FILE_OT_reset_recent";++ /* API callbacks. */+ ot->exec = reset_recent_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Highlight File Operator+ * \{ */++int file_highlight_set(SpaceFile *sfile, ARegion *region, int mx, int my)+{+ View2D *v2d = ®ion->v2d;+ FileSelectParams *params;+ int numfiles, origfile;++ /* In case blender starts where the mouse is over a File browser,+ * this operator can be invoked when the `sfile` or `sfile->layout` isn't initialized yet. */+ if (sfile == nullptr || sfile->files == nullptr || sfile->layout == nullptr) {+ return 0;+ }++ params = ED_fileselect_get_active_params(sfile);+ /* In case #SpaceFile.browse_mode just changed, the area may be pending a refresh still, which is+ * what creates the params for the current browse mode. See #93508. */+ if (!params) {+ return false;+ }+ numfiles = filelist_files_ensure(sfile->files);++ origfile = params->highlight_file;++ mx -= region->winrct.xmin;+ my -= region->winrct.ymin;++ if (ED_fileselect_layout_is_inside_pt(sfile->layout, v2d, mx, my)) {+ float fx, fy;+ int highlight_file;++ ui::view2d_region_to_view(v2d, mx, my, &fx, &fy);++ highlight_file = ED_fileselect_layout_offset(+ sfile->layout, int(v2d->tot.xmin + fx), int(v2d->tot.ymax - fy));++ if ((highlight_file >= 0) && (highlight_file < numfiles)) {+ params->highlight_file = highlight_file;+ }+ else {+ params->highlight_file = -1;+ }+ }+ else {+ params->highlight_file = -1;+ }++ return (params->highlight_file != origfile);+}++static wmOperatorStatus file_highlight_invoke(bContext *C,+ wmOperator * /*op*/,+ const wmEvent *event)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (!file_highlight_set(sfile, region, event->xy[0], event->xy[1])) {+ return OPERATOR_PASS_THROUGH;+ }++ ED_area_tag_redraw(CTX_wm_area(C));++ return OPERATOR_PASS_THROUGH;+}++void FILE_OT_highlight(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Highlight File";+ ot->description = "Highlight selected file(s)";+ ot->idname = "FILE_OT_highlight";++ /* API callbacks. */+ ot->invoke = file_highlight_invoke;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Sort from Column Operator+ * \{ */++static wmOperatorStatus file_column_sort_ui_context_invoke(bContext *C,+ wmOperator * /*op*/,+ const wmEvent *event)+{+ const ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (file_attribute_column_header_is_inside(+ ®ion->v2d, sfile->layout, event->mval[0], event->mval[1]))+ {+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const FileAttributeColumnType column_type = file_attribute_column_type_find_isect(+ ®ion->v2d, params, sfile->layout, event->mval[0]);++ if (column_type != COLUMN_NONE) {+ const FileAttributeColumn *column = &sfile->layout->attribute_columns[column_type];++ BLI_assert(column->sort_type != FILE_SORT_DEFAULT);+ if (params->sort == column->sort_type) {+ /* Already sorting by selected column -> toggle sort invert (three state logic). */+ params->flag ^= FILE_SORT_INVERT;+ }+ else {+ params->sort = column->sort_type;+ params->flag &= ~FILE_SORT_INVERT;+ }++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ }+ }++ return OPERATOR_PASS_THROUGH;+}++void FILE_OT_sort_column_ui_context(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Sort from Column";+ ot->description = "Change sorting to use column under cursor";+ ot->idname = "FILE_OT_sort_column_ui_context";++ /* API callbacks. */+ ot->invoke = file_column_sort_ui_context_invoke;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;++ ot->flag = OPTYPE_INTERNAL;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Cancel File Selector Operator+ * \{ */++static bool file_operator_poll(bContext *C)+{+ bool poll = ED_operator_file_browsing_active(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (!sfile || !sfile->op) {+ poll = false;+ }++ return poll;+}++static wmOperatorStatus file_cancel_exec(bContext *C, wmOperator * /*unused*/)+{+ wmWindowManager *wm = CTX_wm_manager(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ wmOperator *op = sfile->op;++ sfile->op = nullptr;++ WM_event_fileselect_event(wm, op, EVT_FILESELECT_CANCEL);++ return OPERATOR_FINISHED;+}++void FILE_OT_cancel(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Cancel File Operation";+ ot->description = "Cancel file operation";+ ot->idname = "FILE_OT_cancel";++ /* API callbacks. */+ ot->exec = file_cancel_exec;+ ot->poll = file_operator_poll;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Operator Utilities+ * \{ */++void file_sfile_to_operator_ex(+ bContext *C, Main *bmain, wmOperator *op, SpaceFile *sfile, char *filepath)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ PropertyRNA *prop;+ char dir[FILE_MAX];++ STRNCPY(dir, params->dir);+ BLI_path_slash_ensure(dir);++ /* XXX, not real length */+ if (params->file[0]) {+ BLI_path_join(MutableCStr(filepath, FILE_MAX), params->dir, params->file);+ }+ else {+ BLI_strncpy(filepath, dir, FILE_MAX);+ }++ if ((prop = RNA_struct_find_property(op->ptr, "relative_path"))) {+ if (RNA_property_boolean_get(op->ptr, prop)) {+ BLI_path_rel(filepath, BKE_main_blendfile_path(bmain));+ BLI_path_rel(dir, BKE_main_blendfile_path(bmain));+ }+ }++ char value[FILE_MAX];+ if ((prop = RNA_struct_find_property(op->ptr, "filename"))) {+ RNA_property_string_get(op->ptr, prop, value);+ RNA_property_string_set(op->ptr, prop, params->file);+ if (RNA_property_update_check(prop) && !STREQ(params->file, value)) {+ RNA_property_update(C, op->ptr, prop);+ }+ }+ if ((prop = RNA_struct_find_property(op->ptr, "directory"))) {+ RNA_property_string_get(op->ptr, prop, value);+ RNA_property_string_set(op->ptr, prop, dir);+ if (RNA_property_update_check(prop) && !STREQ(dir, value)) {+ RNA_property_update(C, op->ptr, prop);+ }+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filepath"))) {+ RNA_property_string_get(op->ptr, prop, value);+ RNA_property_string_set(op->ptr, prop, filepath);+ if (RNA_property_update_check(prop) && !STREQ(filepath, value)) {+ RNA_property_update(C, op->ptr, prop);+ }+ }++ /* some ops have multiple files to select */+ /* this is called on operators check() so clear collections first since+ * they may be already set. */+ {+ int i, numfiles = filelist_files_ensure(sfile->files);++ if ((prop = RNA_struct_find_property(op->ptr, "files"))) {+ PointerRNA itemptr;+ int num_files = 0;+ RNA_property_collection_clear(op->ptr, prop);+ for (i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_FILES)) {+ FileDirEntry *file = filelist_file(sfile->files, i);+ /* Cannot (currently) mix regular items and alias/shortcuts in multiple selection. */+ if (!file->redirection_path) {+ RNA_property_collection_add(op->ptr, prop, &itemptr);+ RNA_string_set(&itemptr, "name", file->relpath);+ num_files++;+ }+ }+ }+ /* make sure the file specified in the filename button is added even if no+ * files selected */+ if (0 == num_files) {+ RNA_property_collection_add(op->ptr, prop, &itemptr);+ RNA_string_set(&itemptr, "name", params->file);+ }+ }++ if ((prop = RNA_struct_find_property(op->ptr, "dirs"))) {+ PointerRNA itemptr;+ int num_dirs = 0;+ RNA_property_collection_clear(op->ptr, prop);+ for (i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_DIRS)) {+ FileDirEntry *file = filelist_file(sfile->files, i);+ RNA_property_collection_add(op->ptr, prop, &itemptr);+ RNA_string_set(&itemptr, "name", file->relpath);+ num_dirs++;+ }+ }++ /* make sure the directory specified in the button is added even if no+ * directory selected */+ if (0 == num_dirs) {+ RNA_property_collection_add(op->ptr, prop, &itemptr);+ RNA_string_set(&itemptr, "name", params->dir);+ }+ }+ }+}+void file_sfile_to_operator(bContext *C, Main *bmain, wmOperator *op, SpaceFile *sfile)+{+ char filepath_dummy[FILE_MAX];++ file_sfile_to_operator_ex(C, bmain, op, sfile, filepath_dummy);+}++void file_operator_to_sfile(Main *bmain, SpaceFile *sfile, wmOperator *op)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ PropertyRNA *prop;++ /* If neither of the above are set, split the filepath back */+ if ((prop = RNA_struct_find_property(op->ptr, "filepath"))) {+ char filepath[FILE_MAX];+ RNA_property_string_get(op->ptr, prop, filepath);+ BLI_path_split_dir_file(filepath, params->dir, params->file);+ }+ else {+ if ((prop = RNA_struct_find_property(op->ptr, "filename"))) {+ RNA_property_string_get(op->ptr, prop, params->file);+ }+ if ((prop = RNA_struct_find_property(op->ptr, "directory"))) {+ RNA_property_string_get(op->ptr, prop, params->dir);+ }+ }++ /* we could check for relative_path property which is used when converting+ * in the other direction but doesn't hurt to do this every time */+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));++ /* XXX, files and dirs updates missing, not really so important though */+}++void file_sfile_filepath_set(SpaceFile *sfile, const char *filepath)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ BLI_assert(BLI_exists(filepath));++ if (BLI_is_dir(filepath)) {+ STRNCPY(params->dir, filepath);+ }+ else {+ if ((params->flag & FILE_DIRSEL_ONLY) == 0) {+ BLI_path_split_dir_file(filepath, params->dir, params->file);+ }+ else {+ BLI_path_split_dir_part(filepath, params->dir);+ }+ }+}++void file_draw_check_ex(bContext *C, ScrArea *area)+{+ /* May happen when manipulating non-active spaces. */+ if (area->spacetype != SPACE_FILE) [[unlikely]] {+ return;+ }+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ wmOperator *op = sfile->op;+ if (op) { /* fail on reload */+ if (op->type->check) {+ Main *bmain = CTX_data_main(C);+ file_sfile_to_operator(C, bmain, op, sfile);++ /* redraw */+ if (op->type->check(C, op)) {+ file_operator_to_sfile(bmain, sfile, op);++ /* redraw, else the changed settings won't get updated */+ ED_area_tag_redraw(area);+ }+ }+ }+}++void file_draw_check(bContext *C)+{+ ScrArea *area = CTX_wm_area(C);+ file_draw_check_ex(C, area);+}++void file_draw_check_cb(bContext *C, void * /*arg1*/, void * /*arg2*/)+{+ file_draw_check(C);+}++bool file_draw_check_exists(SpaceFile *sfile)+{+ if (sfile->op) { /* fails on reload */+ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params && (params->flag & FILE_CHECK_EXISTING)) {+ char filepath[FILE_MAX];+ BLI_path_join(filepath, params->dir, params->file);+ if (BLI_is_file(filepath)) {+ return true;+ }+ }+ }++ return false;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name External operations that can performed on files.+ * \{ */++static const EnumPropertyItem file_external_operation[] = {+ {FILE_EXTERNAL_OPERATION_OPEN, "OPEN", 0, "Open", "Open the file"},+ {FILE_EXTERNAL_OPERATION_FOLDER_OPEN, "FOLDER_OPEN", 0, "Open Folder", "Open the folder"},+ {FILE_EXTERNAL_OPERATION_EDIT, "EDIT", 0, "Edit", "Edit the file"},+ {FILE_EXTERNAL_OPERATION_NEW, "NEW", 0, "New", "Create a new file of this type"},+ {FILE_EXTERNAL_OPERATION_FIND, "FIND", 0, "Find File", "Search for files of this type"},+ {FILE_EXTERNAL_OPERATION_SHOW, "SHOW", 0, "Show", "Show this file"},+ {FILE_EXTERNAL_OPERATION_PLAY, "PLAY", 0, "Play", "Play this file"},+ {FILE_EXTERNAL_OPERATION_BROWSE, "BROWSE", 0, "Browse", "Browse this file"},+ {FILE_EXTERNAL_OPERATION_PREVIEW, "PREVIEW", 0, "Preview", "Preview this file"},+ {FILE_EXTERNAL_OPERATION_PRINT, "PRINT", 0, "Print", "Print this file"},+ {FILE_EXTERNAL_OPERATION_INSTALL, "INSTALL", 0, "Install", "Install this file"},+ {FILE_EXTERNAL_OPERATION_RUNAS, "RUNAS", 0, "Run As User", "Run as specific user"},+ {FILE_EXTERNAL_OPERATION_PROPERTIES,+ "PROPERTIES",+ 0,+ "Properties",+ "Show OS Properties for this item"},+ {FILE_EXTERNAL_OPERATION_FOLDER_FIND,+ "FOLDER_FIND",+ 0,+ "Find in Folder",+ "Search for items in this folder"},+ {FILE_EXTERNAL_OPERATION_FOLDER_CMD,+ "CMD",+ 0,+ "Command Prompt Here",+ "Open a command prompt here"},+ {0, nullptr, 0, nullptr, nullptr}};++static wmOperatorStatus file_external_operation_exec(bContext *C, wmOperator *op)+{+ if (!ED_operator_file_browsing_active(C)) {+ /* File browsing only operator (not asset browsing). */+ return OPERATOR_CANCELLED;+ }++ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (!sfile || !params) {+ return OPERATOR_CANCELLED;+ }+ char dir[FILE_MAX_LIBEXTRA];+ if (filelist_islibrary(sfile->files, dir, nullptr)) {+ return OPERATOR_CANCELLED;+ }+ int numfiles = filelist_files_ensure(sfile->files);+ FileDirEntry *fileentry = nullptr;+ int num_selected = 0;+ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL)) {+ fileentry = filelist_file(sfile->files, i);+ num_selected++;+ }+ }+ if (!fileentry || num_selected > 1) {+ return OPERATOR_CANCELLED;+ }++ const FileExternalOperation operation = (FileExternalOperation)RNA_enum_get(op->ptr,+ "operation");++ char filepath[FILE_MAX_LIBEXTRA];+ if (!(fileentry->typeflag & FILE_TYPE_DIR) && (operation == FILE_EXTERNAL_OPERATION_FOLDER_OPEN))+ {+ const char *root = filelist_dir(sfile->files);+ STRNCPY(filepath, root);+ }+ else {+ filelist_file_get_full_path(sfile->files, fileentry, filepath);+ }++ WM_cursor_set(CTX_wm_window(C), WM_CURSOR_WAIT);++#ifdef WIN32+ if (!(fileentry->typeflag & FILE_TYPE_DIR) &&+ ELEM(operation, FILE_EXTERNAL_OPERATION_FOLDER_OPEN, FILE_EXTERNAL_OPERATION_FOLDER_CMD))+ {+ /* Not a folder path, so for these operations use the root. */+ const char *root = filelist_dir(sfile->files);+ if (BLI_file_external_operation_execute(root, operation)) {+ WM_cursor_set(CTX_wm_window(C), WM_CURSOR_DEFAULT);+ return OPERATOR_FINISHED;+ }+ }+ if (BLI_file_external_operation_execute(filepath, operation)) {+ WM_cursor_set(CTX_wm_window(C), WM_CURSOR_DEFAULT);+ return OPERATOR_FINISHED;+ }+#else+ wmOperatorType *ot = WM_operatortype_find("WM_OT_path_open", true);+ PointerRNA op_props = WM_operator_properties_create_ptr(ot);+ RNA_string_set(&op_props, "filepath", filepath);+ const wmOperatorStatus retval = WM_operator_name_call_ptr(+ C, ot, wm::OpCallContext::InvokeDefault, &op_props, nullptr);+ WM_operator_properties_free(&op_props);++ if (retval == OPERATOR_FINISHED) {+ WM_cursor_set(CTX_wm_window(C), WM_CURSOR_DEFAULT);+ return OPERATOR_FINISHED;+ }+#endif++ BKE_reportf(+ op->reports, RPT_ERROR, "Failure to perform external file operation on \"%s\"", filepath);+ WM_cursor_set(CTX_wm_window(C), WM_CURSOR_DEFAULT);+ return OPERATOR_CANCELLED;+}++static std::string file_external_operation_get_description(bContext * /*C*/,+ wmOperatorType * /*ot*/,+ PointerRNA *ptr)+{+ const char *description = "";+ RNA_enum_description(file_external_operation, RNA_enum_get(ptr, "operation"), &description);+ return TIP_(description);+}++void FILE_OT_external_operation(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "External File Operation";+ ot->idname = "FILE_OT_external_operation";+ ot->description = "Perform external operation on a file or folder";++ /* API callbacks. */+ ot->exec = file_external_operation_exec;+ ot->get_description = file_external_operation_get_description;++ /* flags */+ ot->flag = OPTYPE_REGISTER; /* No undo! */++ /* properties */+ RNA_def_enum(ot->srna,+ "operation",+ file_external_operation,+ FILE_EXTERNAL_OPERATION_OPEN,+ "Operation",+ "Operation to perform on the selected file or path");+}++static void file_os_operations_menu_item(ui::Layout &layout,+ wmOperatorType *ot,+ const char *path,+ FileExternalOperation operation)+{+#ifdef WIN32+ if (!BLI_file_external_operation_supported(path, operation)) {+ return;+ }+#else+ UNUSED_VARS(path);+ if (!ELEM(operation, FILE_EXTERNAL_OPERATION_OPEN, FILE_EXTERNAL_OPERATION_FOLDER_OPEN)) {+ return;+ }+#endif++ const char *title = "";+ RNA_enum_name(file_external_operation, operation, &title);++ PointerRNA props_ptr = layout.op(+ ot, IFACE_(title), ICON_NONE, wm::OpCallContext::InvokeDefault, UI_ITEM_NONE);+ RNA_enum_set(&props_ptr, "operation", operation);+}++static void file_os_operations_menu_draw(const bContext *C_const, Menu *menu)+{+ bContext *C = const_cast<bContext *>(C_const);++ /* File browsing only operator (not asset browsing). */+ if (!ED_operator_file_browsing_active(C)) {+ return;+ }++ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (!sfile || !params) {+ return;+ }++ char dir[FILE_MAX_LIBEXTRA];+ if (filelist_islibrary(sfile->files, dir, nullptr)) {+ return;+ }++ int numfiles = filelist_files_ensure(sfile->files);+ FileDirEntry *fileentry = nullptr;+ int num_selected = 0;++ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL)) {+ fileentry = filelist_file(sfile->files, i);+ num_selected++;+ }+ }++ if (!fileentry || num_selected > 1) {+ return;+ }++ char path[FILE_MAX_LIBEXTRA];+ filelist_file_get_full_path(sfile->files, fileentry, path);+ const char *root = filelist_dir(sfile->files);++ ui::Layout &layout = *menu->layout;+ layout.operator_context_set(wm::OpCallContext::InvokeDefault);+ wmOperatorType *ot = WM_operatortype_find("FILE_OT_external_operation", true);++ if (fileentry->typeflag & FILE_TYPE_DIR) {+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_FOLDER_OPEN);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_FOLDER_CMD);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_PROPERTIES);+ }+ else {+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_OPEN);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_EDIT);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_NEW);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_FIND);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_SHOW);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_PLAY);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_BROWSE);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_PREVIEW);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_PRINT);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_INSTALL);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_RUNAS);+ file_os_operations_menu_item(layout, ot, root, FILE_EXTERNAL_OPERATION_FOLDER_OPEN);+ file_os_operations_menu_item(layout, ot, root, FILE_EXTERNAL_OPERATION_FOLDER_CMD);+ file_os_operations_menu_item(layout, ot, path, FILE_EXTERNAL_OPERATION_PROPERTIES);+ }+}++static bool file_os_operations_menu_poll(const bContext *C_const, MenuType * /*mt*/)+{+ bContext *C = const_cast<bContext *>(C_const);++ /* File browsing only operator (not asset browsing). */+ if (!ED_operator_file_browsing_active(C)) {+ return false;+ }++ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (sfile && params) {+ char dir[FILE_MAX_LIBEXTRA];+ if (filelist_islibrary(sfile->files, dir, nullptr)) {+ return false;+ }++ int numfiles = filelist_files_ensure(sfile->files);+ int num_selected = 0;+ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL)) {+ num_selected++;+ }+ }++ if (num_selected > 1) {+ CTX_wm_operator_poll_msg_set(C, "More than one item is selected");+ }+ else if (num_selected < 1) {+ CTX_wm_operator_poll_msg_set(C, "No items are selected");+ }+ else {+ return true;+ }+ }++ return false;+}++void file_external_operations_menu_register()+{+ MenuType *mt;++ mt = MEM_new_zeroed<MenuType>("spacetype file menu file operations");+ STRNCPY_UTF8(mt->idname, "FILEBROWSER_MT_operations_menu");+ STRNCPY_UTF8(mt->label, N_("External"));+ STRNCPY_UTF8(mt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA);+ mt->draw = file_os_operations_menu_draw;+ mt->poll = file_os_operations_menu_poll;+ WM_menutype_add(mt);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Execute File Window Operator+ * \{ */++/**+ * Execute the active file, as set in the file select params.+ */+static bool file_execute(bContext *C, SpaceFile *sfile)+{+ Main *bmain = CTX_data_main(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (!params) {+ return false;+ }+ FileDirEntry *file = filelist_file(sfile->files, params->active_file);++ if (file && file->redirection_path) {+ /* redirection_path is an absolute path that takes precedence+ * over using params->dir + params->file. */+ BLI_path_split_dir_file(file->redirection_path, params->dir, params->file);+ /* Update relpath with redirected filename as well so that the alternative+ * combination of params->dir + relpath remains valid as well. */+ MEM_delete(file->relpath);+ file->relpath = BLI_strdup(params->file);+ }++ /* directory change */+ if (file && (file->typeflag & FILE_TYPE_DIR)) {+ if (!file->relpath) {+ return false;+ }++ if (FILENAME_IS_PARENT(file->relpath)) {+ BLI_path_parent_dir(params->dir);+ }+ else {+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_native(params->dir);+ BLI_path_append_dir(params->dir, file->relpath);+ }+ ED_file_change_dir(C);+ }+ /* Opening file, sends events now, so things get handled on window-queue level. */+ else if (sfile->op) {+ ScrArea *area = CTX_wm_area(C);+ FSMenu *fsmenu = ED_fsmenu_get();+ wmOperator *op = sfile->op;+ char filepath[FILE_MAX];++ sfile->op = nullptr;++ file_sfile_to_operator_ex(C, bmain, op, sfile, filepath);++ if (BLI_exists(params->dir)) {+ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_RECENT,+ params->dir,+ nullptr,+ ICON_FILE_FOLDER,+ FSMenuInsert(FS_INSERT_SAVE | FS_INSERT_FIRST));+ }++ fsmenu_write_file_and_refresh_or_report_error(fsmenu, area, op->reports);++ WM_event_fileselect_event(CTX_wm_manager(C), op, EVT_FILESELECT_EXEC);+ }++ return true;+}++static wmOperatorStatus file_exec(bContext *C, wmOperator * /*op*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (!file_execute(C, sfile)) {+ return OPERATOR_CANCELLED;+ }++ return OPERATOR_FINISHED;+}++static std::string file_execute_get_description(bContext *C,+ wmOperatorType * /*ot*/,+ PointerRNA * /*ptr*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ if (sfile->op && sfile->op->type && sfile->op->type->description) {+ /* Return the description of the executed operator. Don't use get_description+ * as that will return file details for #WM_OT_open_mainfile. */+ return TIP_(sfile->op->type->description);+ }+ return {};+}++void FILE_OT_execute(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Execute File Window";+ ot->description = "Execute selected file";+ ot->idname = "FILE_OT_execute";+ ot->get_description = file_execute_get_description;++ /* API callbacks. */+ ot->exec = file_exec;+ /* Important since handler is on window level.+ *+ * Avoid using #file_operator_poll since this is also used for entering directories+ * which is used even when the file manager doesn't have an operator. */+ ot->poll = ED_operator_file_browsing_active;+}++/**+ * \returns false if the mouse doesn't hover a selectable item.+ */+static bool file_ensure_hovered_is_active(bContext *C, const wmEvent *event)+{+ rcti rect = file_select_mval_to_select_rect(event->mval);+ if (file_select(C, &rect, FILE_SEL_ADD, false, false) == FILE_SELECT_NOTHING) {+ return false;+ }++ return true;+}++static wmOperatorStatus file_execute_mouse_invoke(bContext *C,+ wmOperator * /*op*/,+ const wmEvent *event)+{+ ARegion *region = CTX_wm_region(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (!ED_fileselect_layout_is_inside_pt(+ sfile->layout, ®ion->v2d, event->mval[0], event->mval[1]))+ {+ return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;+ }++ /* Note that this isn't needed practically, because the keymap already activates the hovered item+ * on mouse-press. This execute operator is called afterwards on the double-click event then.+ * However relying on this would be fragile and could break with keymap changes, so better to+ * have this mouse-execute operator that makes sure once more that the hovered file is active. */+ if (!file_ensure_hovered_is_active(C, event)) {+ return OPERATOR_CANCELLED;+ }++ if (!file_execute(C, sfile)) {+ return OPERATOR_CANCELLED;+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_mouse_execute(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Execute File";+ ot->description =+ "Perform the current execute action for the file under the cursor (e.g. open the file)";+ ot->idname = "FILE_OT_mouse_execute";++ /* API callbacks. */+ ot->invoke = file_execute_mouse_invoke;+ ot->poll = ED_operator_file_browsing_active;++ ot->flag = OPTYPE_INTERNAL;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Refresh File List Operator+ * \{ */++static wmOperatorStatus file_refresh_exec(bContext *C, wmOperator * /*unused*/)+{+ wmWindowManager *wm = CTX_wm_manager(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FSMenu *fsmenu = ED_fsmenu_get();++ ED_fileselect_clear(wm, sfile);++ /* refresh system directory menu */+ fsmenu_refresh_system_category(fsmenu);++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++void FILE_OT_refresh(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Refresh File List";+ ot->description = "Refresh the file list";+ ot->idname = "FILE_OT_refresh";++ /* API callbacks. */+ ot->exec = file_refresh_exec;+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Navigate Parent Operator+ * \{ */++static wmOperatorStatus file_parent_exec(bContext *C, wmOperator * /*unused*/)+{+ Main *bmain = CTX_data_main(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (params) {+ if (BLI_path_parent_dir(params->dir)) {+ BLI_path_abs(params->dir, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_dir(params->dir);+ ED_file_change_dir(C);+ if (params->recursion_level > 1) {+ /* Disable `dirtree` recursion when going up in tree. */+ params->recursion_level = 0;+ filelist_setrecursion(sfile->files, params->recursion_level);+ }+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+ }+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_parent(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Parent Directory";+ ot->description = "Move to parent directory";+ ot->idname = "FILE_OT_parent";++ /* API callbacks. */+ ot->exec = file_parent_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Navigate Previous Operator+ * \{ */++static wmOperatorStatus file_previous_exec(bContext *C, wmOperator * /*op*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (params) {+ folderlist_pushdir(sfile->folders_next, params->dir);+ folderlist_popdir(sfile->folders_prev, params->dir);+ folderlist_pushdir(sfile->folders_next, params->dir);++ ED_file_change_dir(C);+ }+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++void FILE_OT_previous(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Previous Folder";+ ot->description = "Move to previous folder";+ ot->idname = "FILE_OT_previous";++ /* API callbacks. */+ ot->exec = file_previous_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Navigate Next Operator+ * \{ */++static wmOperatorStatus file_next_exec(bContext *C, wmOperator * /*unused*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params) {+ folderlist_pushdir(sfile->folders_prev, params->dir);+ folderlist_popdir(sfile->folders_next, params->dir);++ /* update folders_prev so we can check for it in #folderlist_clear_next() */+ folderlist_pushdir(sfile->folders_prev, params->dir);++ ED_file_change_dir(C);+ }+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++void FILE_OT_next(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Next Folder";+ ot->description = "Move to next folder";+ ot->idname = "FILE_OT_next";++ /* API callbacks. */+ ot->exec = file_next_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Smooth Scroll Operator+ * \{ */++/* only meant for timer usage */+static wmOperatorStatus file_smoothscroll_invoke(bContext *C,+ wmOperator * /*op*/,+ const wmEvent *event)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ ARegion *region, *region_ctx = CTX_wm_region(C);+ const bool is_horizontal = (sfile->layout->flag & FILE_LAYOUT_HOR) != 0;+ int i;++ /* escape if not our timer */+ if (sfile->smoothscroll_timer == nullptr || sfile->smoothscroll_timer != event->customdata) {+ return OPERATOR_PASS_THROUGH;+ }++ const int numfiles = filelist_files_ensure(sfile->files);++ /* Due to asynchronous nature of file listing, we may execute this code before `file_refresh()`+ * editing entry is available in our listing,+ * so we also have to handle switching to rename mode here. */+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if ((params->rename_flag &+ (FILE_PARAMS_RENAME_PENDING | FILE_PARAMS_RENAME_POSTSCROLL_PENDING)) != 0)+ {+ file_params_renamefile_activate(sfile, params);+ }++ /* check if we are editing a name */+ int edit_idx = -1;+ for (i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL) &+ (FILE_SEL_EDITING | FILE_SEL_HIGHLIGHTED))+ {+ edit_idx = i;+ break;+ }+ }++ wmWindowManager *wm = CTX_wm_manager(C);+ wmWindow *win = CTX_wm_window(C);++ /* if we are not editing, we are done */+ if (edit_idx == -1) {+ /* Do not invalidate timer if file-rename is still pending,+ * we might still be building the filelist and yet have to find edited entry. */+ if (params->rename_flag == 0) {+ file_params_smoothscroll_timer_clear(wm, win, sfile);+ }+ return OPERATOR_PASS_THROUGH;+ }++ /* we need the correct area for scrolling */+ region = BKE_area_find_region_type(area, RGN_TYPE_WINDOW);+ if (!region || region->regiontype != RGN_TYPE_WINDOW) {+ file_params_smoothscroll_timer_clear(wm, win, sfile);+ return OPERATOR_PASS_THROUGH;+ }++ /* Number of items in a block (i.e. lines in a column in horizontal layout, or columns in a line+ * in vertical layout).+ */+ const int items_block_size = is_horizontal ? sfile->layout->rows : sfile->layout->flow_columns;++ /* Scroll offset is the first file in the row/column we are editing in. */+ if (sfile->scroll_offset == 0) {+ sfile->scroll_offset = (edit_idx / items_block_size) * items_block_size;+ }++ const int numfiles_layout = ED_fileselect_layout_numfiles(sfile->layout, region);+ const int first_visible_item = ED_fileselect_layout_offset(+ sfile->layout, int(region->v2d.cur.xmin), int(-region->v2d.cur.ymax));+ const int last_visible_item = first_visible_item + numfiles_layout + 1;++ /* NOTE: the special case for vertical layout is because filename is at the bottom of items then,+ * so we artificially move current row back one step, to ensure we show bottom of+ * active item rather than its top (important in case visible height is low). */+ const int middle_offset = max_ii(+ 0, (first_visible_item + last_visible_item) / 2 - (is_horizontal ? 0 : items_block_size));++ const int min_middle_offset = numfiles_layout / 2;+ const int max_middle_offset = ((numfiles / items_block_size) * items_block_size ++ ((numfiles % items_block_size) != 0 ? items_block_size : 0)) -+ (numfiles_layout / 2);+ /* Actual (physical) scrolling info, in pixels, used to detect whether we are fully at the+ * beginning/end of the view. */+ /* Note that there is a weird glitch, that sometimes tot rctf is smaller than cur rctf...+ * that is why we still need to keep the min/max_middle_offset checks too. :( */+ const float min_tot_scroll = is_horizontal ? region->v2d.tot.xmin : -region->v2d.tot.ymax;+ const float max_tot_scroll = is_horizontal ? region->v2d.tot.xmax : -region->v2d.tot.ymin;+ const float min_curr_scroll = is_horizontal ? region->v2d.cur.xmin : -region->v2d.cur.ymax;+ const float max_curr_scroll = is_horizontal ? region->v2d.cur.xmax : -region->v2d.cur.ymin;++ /* Check if we have reached our final scroll position. */+ /* File-list has to be ready, otherwise it makes no sense to stop scrolling yet. */+ const bool is_ready = filelist_is_ready(sfile->files);+ /* Edited item must be in the 'middle' of shown area (kind of approximated).+ * Note that we have to do the check in 'block space', not in 'item space' here. */+ const bool is_centered = (abs(middle_offset / items_block_size -+ sfile->scroll_offset / items_block_size) == 0);+ /* OR edited item must be towards the beginning, and we are scrolled fully to the start. */+ const bool is_full_start = ((sfile->scroll_offset < min_middle_offset) &&+ (min_curr_scroll - min_tot_scroll < 1.0f) &&+ (middle_offset - min_middle_offset < items_block_size));+ /* OR edited item must be towards the end, and we are scrolled fully to the end.+ * This one is crucial (unlike the one for the beginning), because without it scrolling+ * fully to the end, and last column or row will end up only partially drawn. */+ const bool is_full_end = ((sfile->scroll_offset > max_middle_offset) &&+ (max_tot_scroll - max_curr_scroll < 1.0f) &&+ (max_middle_offset - middle_offset < items_block_size));++ if (is_ready && (is_centered || is_full_start || is_full_end)) {+ file_params_smoothscroll_timer_clear(wm, win, sfile);+ /* Post-scroll (after rename has been validated by user) is done,+ * rename process is totally finished, cleanup. */+ if ((params->rename_flag & FILE_PARAMS_RENAME_POSTSCROLL_ACTIVE) != 0) {+ file_params_renamefile_clear(params);+ }+ return OPERATOR_FINISHED;+ }++ /* Temporarily set context to the main window region,+ * so that the pan operator works. */+ CTX_wm_region_set(C, region);++ /* scroll one step in the desired direction */+ int deltax = 0;+ int deltay = 0;++ /* We adjust speed of scrolling to avoid tens of seconds of it in e.g. directories with tens of+ * thousands of folders... See #65782. */+ /* This will slow down scrolling when approaching final goal, also avoids going too far and+ * having to bounce back... */++ /* Number of blocks (columns in horizontal layout, rows otherwise) between current middle of+ * screen, and final goal position. */+ const int diff_offset = sfile->scroll_offset / items_block_size -+ middle_offset / items_block_size;+ /* convert diff_offset into pixels. */+ const int diff_offset_delta = abs(diff_offset) *+ (is_horizontal ?+ sfile->layout->tile_w + 2 * sfile->layout->tile_border_x :+ sfile->layout->tile_h + 2 * sfile->layout->tile_border_y);+ const int scroll_delta = max_ii(2, diff_offset_delta / 15);++ if (diff_offset < 0) {+ if (is_horizontal) {+ deltax = -scroll_delta;+ }+ else {+ deltay = scroll_delta;+ }+ }+ else {+ if (is_horizontal) {+ deltax = scroll_delta;+ }+ else {+ deltay = -scroll_delta;+ }+ }+ PointerRNA op_ptr = WM_operator_properties_create("VIEW2D_OT_pan");+ RNA_int_set(&op_ptr, "deltax", deltax);+ RNA_int_set(&op_ptr, "deltay", deltay);++ WM_operator_name_call(C, "VIEW2D_OT_pan", wm::OpCallContext::ExecDefault, &op_ptr, event);+ WM_operator_properties_free(&op_ptr);++ ED_region_tag_redraw(region);++ /* and restore context */+ CTX_wm_region_set(C, region_ctx);++ return OPERATOR_FINISHED;+}++void FILE_OT_smoothscroll(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Smooth Scroll";+ ot->idname = "FILE_OT_smoothscroll";+ ot->description = "Smooth scroll to make editable file visible";++ /* API callbacks. */+ ot->invoke = file_smoothscroll_invoke;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name File Selector Drop Operator+ * \{ */++static wmOperatorStatus filepath_drop_exec(bContext *C, wmOperator *op)+{+ Main *bmain = CTX_data_main(C);+ SpaceFile *sfile = CTX_wm_space_file(C);++ if (sfile) {+ char filepath[FILE_MAX];++ RNA_string_get(op->ptr, "filepath", filepath);+ if (!BLI_exists(filepath)) {+ BKE_report(op->reports, RPT_ERROR, "File does not exist");+ return OPERATOR_CANCELLED;+ }++ file_sfile_filepath_set(sfile, filepath);++ if (sfile->op) {+ file_sfile_to_operator(C, bmain, sfile->op, sfile);+ file_draw_check(C);+ }++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ return OPERATOR_FINISHED;+ }++ return OPERATOR_CANCELLED;+}++void FILE_OT_filepath_drop(wmOperatorType *ot)+{+ ot->name = "File Selector Drop";+ ot->idname = "FILE_OT_filepath_drop";++ ot->exec = filepath_drop_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;++ RNA_def_string_file_path(ot->srna, "filepath", "Path", FILE_MAX, "", "");+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name New Directory Operator+ * \{ */++/**+ * Create a new, non-existing folder `dirname`, returns true if successful,+ * false if name couldn't be created.+ * The actual name is returned in `r_dirpath`, `r_dirpath_full` contains the complete path,+ * including the new folder name.+ */+static bool new_folder_path(const char *parent,+ char r_dirpath_full[FILE_MAX],+ char r_dirname[FILE_MAXFILE])+{+ int i = 1;+ int len = 0;++ BLI_strncpy(r_dirname, "New Folder", FILE_MAXFILE);+ BLI_path_join(MutableCStr(r_dirpath_full, FILE_MAX), parent, r_dirname);+ /* check whether r_dirpath_full with the name already exists, in this case+ * add number to the name. Check length of generated name to avoid+ * crazy case of huge number of folders each named 'New Folder (x)' */+ while (BLI_exists(r_dirpath_full) && (len < FILE_MAXFILE)) {+ len = BLI_snprintf_utf8(r_dirname, FILE_MAXFILE, "New Folder(%d)", i);+ BLI_path_join(MutableCStr(r_dirpath_full, FILE_MAX), parent, r_dirname);+ i++;+ }++ return (len < FILE_MAXFILE);+}++static wmOperatorStatus file_directory_new_exec(bContext *C, wmOperator *op)+{+ char dirname[FILE_MAXFILE];+ char dirpath[FILE_MAX];+ bool generate_name = true;++ wmWindowManager *wm = CTX_wm_manager(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const bool do_diropen = RNA_boolean_get(op->ptr, "open");++ if (!params) {+ BKE_report(op->reports, RPT_WARNING, "No parent directory given");+ return OPERATOR_CANCELLED;+ }++ dirpath[0] = '\0';++ {+ PropertyRNA *prop = RNA_struct_find_property(op->ptr, "directory");+ RNA_property_string_get(op->ptr, prop, dirpath);+ if (dirpath[0] != '\0') {+ generate_name = false;+ }+ }++ if (generate_name) {+ /* create a new, non-existing folder name */+ if (!new_folder_path(params->dir, dirpath, dirname)) {+ BKE_report(op->reports, RPT_ERROR, "Could not create new folder name");+ return OPERATOR_CANCELLED;+ }+ }+ else { /* We assume we are able to generate a valid name! */+ char org_path[FILE_MAX];++ STRNCPY(org_path, dirpath);+ if (BLI_path_make_safe(dirpath)) {+ BKE_reportf(op->reports,+ RPT_WARNING,+ "'%s' given path is OS-invalid, creating '%s' path instead",+ org_path,+ dirpath);+ }+ }++ /* create the file */+ errno = 0;+ if (!BLI_dir_create_recursive(dirpath) ||+ /* Should no more be needed,+ * now that BLI_dir_create_recursive returns a success state - but kept just in case. */+ !BLI_exists(dirpath))+ {+ BKE_reportf(op->reports,+ RPT_ERROR,+ "Could not create new folder: %s",+ errno ? strerror(errno) : "unknown error");+ return OPERATOR_CANCELLED;+ }++ eFileSel_Params_RenameFlag rename_flag = eFileSel_Params_RenameFlag(params->rename_flag);++ /* If we don't enter the directory directly, remember file to jump into editing. */+ if (do_diropen == false) {+ BLI_assert_msg(params->rename_id == nullptr,+ "File rename handling should immediately clear rename_id when done, "+ "because otherwise it will keep taking precedence over renamefile.");+ STRNCPY(params->renamefile, dirname);+ rename_flag = FILE_PARAMS_RENAME_PENDING;+ }++ file_params_invoke_rename_postscroll(wm, CTX_wm_window(C), sfile);+ params->rename_flag = rename_flag;++ /* reload dir to make sure we're seeing what's in the directory */+ ED_fileselect_clear(wm, sfile);++ if (do_diropen) {+ STRNCPY(params->dir, dirpath);+ ED_file_change_dir(C);+ }++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++static wmOperatorStatus file_directory_new_invoke(bContext *C,+ wmOperator *op,+ const wmEvent * /*event*/)+{+ /* NOTE: confirm is needed because this operator is invoked+ * when entering a path from the file selector. Without a confirmation,+ * a typo will create the path without any prompt. See #128567. */+ if (RNA_boolean_get(op->ptr, "confirm")) {+ return WM_operator_confirm_ex(C,+ op,+ IFACE_("Create new directory?"),+ nullptr,+ IFACE_("Create"),+ ui::AlertIcon::None,+ false);+ }+ return file_directory_new_exec(C, op);+}++void FILE_OT_directory_new(wmOperatorType *ot)+{+ PropertyRNA *prop;++ /* identifiers */+ ot->name = "Create New Directory";+ ot->description = "Create a new directory";+ ot->idname = "FILE_OT_directory_new";++ /* API callbacks. */+ ot->invoke = file_directory_new_invoke;+ ot->exec = file_directory_new_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */++ prop = RNA_def_string_dir_path(+ ot->srna, "directory", nullptr, FILE_MAX, "Directory", "Name of new directory");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ prop = RNA_def_boolean(ot->srna, "open", false, "Open", "Open new directory");+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);+ WM_operator_properties_confirm_or_exec(ot);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Refresh File List Operator+ * \{ */++static void file_expand_directory(const Main *bmain, FileSelectParams *params)+{+ /* NOTE: Arbitrary conventions are used here which are OK for user facing logic+ * Attempting to resolve the path to *something* valid is OK for user input+ * but not suitable for `BLI_path_utils.hh` which is used for lower level path handling. */++ /* The path was invalid, fall back to the default root. */+ bool do_reset = false;++ if (params->dir[0] == '\0') {+ do_reset = true;+ }+ else if (BLI_path_is_rel(params->dir)) { /* `//` literal. */+ const char *blendfile_path = BKE_main_blendfile_path(bmain);+ if (blendfile_path[0] != '\0') {+ BLI_path_abs(params->dir, blendfile_path);+ }+ else {+ /* Ignore relative paths for unsaved files.+ * It's enough of a corner case that any attempt to resolve the path+ * is more likely to confuse users about the meaning of `//`. */+ do_reset = true;+ }+ }+ else if (params->dir[0] == '~') {+ /* While path handling expansion typically doesn't support home directory expansion+ * in Blender, this is a convenience to be able to type in a single character.+ * Even though this is a UNIX convention, it's harmless to expand on WIN32 as well. */+ if (const char *home_dir = BLI_dir_home()) {+ char tmpstr[sizeof(params->dir) - 1];+ STRNCPY(tmpstr, params->dir + 1);+ BLI_path_join(params->dir, home_dir, tmpstr);+ }+ else {+ do_reset = true;+ }+ }+#ifdef WIN32+ else if (BLI_path_is_win32_drive_only(params->dir)) {+ /* Change `C:` --> `C:\`, see: #28102. */+ params->dir[2] = SEP;+ params->dir[3] = '\0';+ }+ else if (BLI_path_is_unc(params->dir)) {+ BLI_path_normalize_unc(params->dir);+ }+#endif /* WIN32 */++ if (do_reset) {+ STRNCPY(params->dir, BKE_appdir_folder_root());+ }+}++/**+ * \param dir: A normalized path (from user input).+ * \return True when `dir` can be created.+ */+static bool can_create_dir_from_user_input(const char dir[FILE_MAX_LIBEXTRA])+{+ /* NOTE(@ideasman42): This function checks if the user should be prompted+ * to create the path when a non-existent path is entered into the directory field.+ *+ * Typically when the intention is to create a path, it's simply created only showing+ * feedback if the operation failed. In the case of entering a path as text any typo+ * in the would immediately be created (if possible) which isn't good, see: #128567.+ *+ * The reason to treat user input differently here is the user could input anything,+ * e.g. values such as a single space. This resolves to the current-working-directory:+ * `$PWD/ ` which is a valid path name and could be created+ * (this was in fact the behavior until v4.4).+ *+ * As this can be error prone, performs basic sanity checks on `dir`.+ * - Ensure it's an absolute path.+ * - It contains a writable parent path.+ * - For WIN32: The UNC path is a directory and not a "share".+ *+ * While these checks don't need to be comprehensive,+ * they should prevent accidents and confusing situations. */++ /* If the user types in a name with no absolute prefix,+ * creating a directory relative to the CWD doesn't make sense from the UI. */+ if (!BLI_path_is_abs_from_cwd(dir)) {+ return false;+ }++ /* If none of the parents exist, the directory can't be created.+ * This prevents the popup to create a new path showing on WIN32+ * for a drive-letter that doesn't exist (for example). */+ {+ char tdir[FILE_MAX_LIBEXTRA];+ STRNCPY(tdir, dir);+ if (!BLI_path_parent_dir_until_exists(tdir)) {+ return false;+ }+ }++#if defined(WIN32)+ /* For UNC paths we need to check whether the parent of the new+ * directory is a proper directory itself and not a share or the+ * UNC root (server name) itself. Calling #BLI_is_dir does this. */+ if (BLI_path_is_unc(dir)) {+ char tdir[FILE_MAX_LIBEXTRA];+ STRNCPY(tdir, dir);+ BLI_path_parent_dir(tdir);+ if (!BLI_is_dir(tdir)) {+ return false;+ }+ }+#endif /* WIN32 */++ return true;+}++void file_directory_enter_handle(bContext *C, void * /*arg_unused*/, void * /*arg_but*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params == nullptr) [[unlikely]] {+ return;+ }++ const Main *bmain = CTX_data_main(C);+ char old_dir[sizeof(params->dir)] = {0};++ STRNCPY(old_dir, params->dir);++ file_expand_directory(bmain, params);++ /* Special case, user may have pasted a path including a file-name into the directory. */+ if (!filelist_is_dir(sfile->files, params->dir)) {+ char tdir[FILE_MAX_LIBEXTRA];+ char *group, *name;++ if (BLI_is_file(params->dir)) {+ char dirpath[sizeof(params->dir)];+ STRNCPY(dirpath, params->dir);+ BLI_path_split_dir_file(dirpath, params->dir, params->file);+ }+ else if (BKE_blendfile_library_path_explode(params->dir, tdir, &group, &name)) {+ if (group) {+ BLI_path_append(tdir, group);+ }+ STRNCPY(params->dir, tdir);+ if (name) {+ STRNCPY(params->file, name);+ }+ else {+ params->file[0] = '\0';+ }+ }+ }++ /* #file_expand_directory will have made absolute. */+ BLI_assert(!BLI_path_is_rel(params->dir));+ BLI_path_normalize_dir(params->dir);++ if (filelist_is_dir(sfile->files, params->dir)) {+ /* Avoids flickering when nothing's changed. */+ if (!STREQ(params->dir, old_dir)) {+ /* If directory exists, enter it immediately. */+ ED_file_change_dir(C);+ }+ }+ else if (!can_create_dir_from_user_input(params->dir)) {+ const char *lastdir = folderlist_peeklastdir(sfile->folders_prev);+ if (lastdir) {+ STRNCPY(params->dir, lastdir);+ }+ }+ else {+ const char *lastdir = folderlist_peeklastdir(sfile->folders_prev);+ char tdir[FILE_MAX_LIBEXTRA];++ /* If we are "inside" a `.blend` library, we cannot do anything. */+ if (lastdir && BKE_blendfile_library_path_explode(lastdir, tdir, nullptr, nullptr)) {+ STRNCPY(params->dir, lastdir);+ }+ else {+ /* If not, ask to create it and enter if confirmed. */+ wmOperatorType *ot = WM_operatortype_find("FILE_OT_directory_new", false);+ PointerRNA ptr = WM_operator_properties_create_ptr(ot);+ RNA_string_set(&ptr, "directory", params->dir);+ RNA_boolean_set(&ptr, "open", true);+ /* Enable confirmation prompt, else it's too easy to accidentally create new directories. */+ RNA_boolean_set(&ptr, "confirm", true);++ if (lastdir) {+ STRNCPY(params->dir, lastdir);+ }++ WM_operator_name_call_ptr(C, ot, wm::OpCallContext::InvokeDefault, &ptr, nullptr);+ WM_operator_properties_free(&ptr);+ }+ }++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+}++void file_filename_enter_handle(bContext *C, void * /*arg_unused*/, void *arg_but)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params == nullptr) [[unlikely]] {+ return;+ }++ const Main *bmain = CTX_data_main(C);+ ui::Button *but = static_cast<ui::Button *>(arg_but);++ file_expand_directory(bmain, params);++ char matched_file[FILE_MAX] = "";+ int matches = file_select_match(sfile, params->file, matched_file);++ /* It's important this runs *after* #file_select_match,+ * so making "safe" doesn't remove shell-style globing characters. */+ const bool allow_tokens = (params->flag & FILE_PATH_TOKENS_ALLOW) != 0;+ BLI_path_make_safe_filename_ex(params->file, allow_tokens);++ if (matches) {+ /* Replace the pattern (or filename that the user typed in),+ * with the first selected file of the match. */+ STRNCPY(params->file, matched_file);++ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);++ if (matches == 1) {+ char filepath[sizeof(params->dir)];+ BLI_path_join(filepath, params->dir, params->file);++ /* If directory, open it and empty filename field. */+ if (filelist_is_dir(sfile->files, filepath)) {+ BLI_path_abs(filepath, BKE_main_blendfile_path(bmain));+ BLI_path_normalize_dir(filepath);+ STRNCPY(params->dir, filepath);+ params->file[0] = '\0';+ ED_file_change_dir(C);+ textbutton_activate_but(C, but);+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+ }+ }+ else {+ BLI_assert(matches > 1);+ file_draw_check(C);+ }+ }+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Toggle Show Hidden Files Operator+ * \{ */++static wmOperatorStatus file_hidedot_exec(bContext *C, wmOperator * /*unused*/)+{+ wmWindowManager *wm = CTX_wm_manager(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (params) {+ params->flag ^= FILE_HIDE_DOT;+ ED_fileselect_clear(wm, sfile);+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_hidedot(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Toggle Hide Dot Files";+ ot->description = "Toggle hide hidden dot files";+ ot->idname = "FILE_OT_hidedot";++ /* API callbacks. */+ ot->exec = file_hidedot_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Increment Filename Operator+ * \{ */++static bool file_filenum_poll(bContext *C)+{+ SpaceFile *sfile = CTX_wm_space_file(C);++ /* File browsing only operator (not asset browsing). */+ if (!ED_operator_file_browsing_active(C)) {+ return false;+ }++ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ return params && (params->flag & FILE_CHECK_EXISTING);+}++/**+ * Looks for a string of digits within filename (using BLI_path_sequence_decode) and adjusts it by+ * add.+ */+static void filenum_newname(MutableCStr filename, int add)+{+ char head[FILE_MAXFILE], tail[FILE_MAXFILE];+ int pic;+ ushort digits;++ pic = BLI_path_sequence_decode(filename.data(), head, tail, &digits);++ /* are we going from 100 -> 99 or from 10 -> 9 */+ if (add < 0 && digits > 0) {+ int i, exp;+ exp = 1;+ for (i = digits; i > 1; i--) {+ exp *= 10;+ }+ if (pic >= exp && (pic + add) < exp) {+ digits--;+ }+ }++ pic += add;+ pic = std::max(pic, 0);+ BLI_path_sequence_encode(filename, head, tail, digits, pic);+}++static wmOperatorStatus file_filenum_exec(bContext *C, wmOperator *op)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ ScrArea *area = CTX_wm_area(C);++ int inc = RNA_int_get(op->ptr, "increment");+ if (params && (inc != 0)) {+ filenum_newname(params->file, inc);+ ED_area_tag_redraw(area);+ file_draw_check(C);+ // WM_event_add_notifier(C, NC_WINDOW, nullptr);+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_filenum(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Increment Number in Filename";+ ot->description = "Increment number in filename";+ ot->idname = "FILE_OT_filenum";++ /* API callbacks. */+ ot->exec = file_filenum_exec;+ ot->poll = file_filenum_poll;++ /* props */+ RNA_def_int(ot->srna, "increment", 1, -100, 100, "Increment", "", -100, 100);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Rename File/Directory Operator+ * \{ */++static void file_rename_state_activate(SpaceFile *sfile, int file_idx, bool require_selected)+{+ const int numfiles = filelist_files_ensure(sfile->files);++ if ((file_idx >= 0) && (file_idx < numfiles)) {+ FileDirEntry *file = filelist_file(sfile->files, file_idx);++ if ((require_selected == false) ||+ (filelist_entry_select_get(sfile->files, file, CHECK_ALL) & FILE_SEL_SELECTED))+ {+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ filelist_entry_select_index_set(+ sfile->files, file_idx, FILE_SEL_ADD, FILE_SEL_EDITING, CHECK_ALL);+ STRNCPY(params->renamefile, file->relpath);+ /* We can skip the pending state,+ * as we can directly set FILE_SEL_EDITING on the expected entry here. */+ params->rename_flag = FILE_PARAMS_RENAME_ACTIVE;+ }+ }+}++static wmOperatorStatus file_rename_exec(bContext *C, wmOperator * /*op*/)+{+ ScrArea *area = CTX_wm_area(C);+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(CTX_wm_space_data(C));+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (params) {+ file_rename_state_activate(sfile, params->active_file, false);+ ED_area_tag_redraw(area);+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_rename(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Rename File or Directory";+ ot->description = "Rename file or file directory";+ ot->idname = "FILE_OT_rename";++ /* API callbacks. */+ ot->exec = file_rename_exec;+ /* File browsing only operator (not asset browsing). */+ ot->poll = ED_operator_file_browsing_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Delete File Operator+ * \{ */++static bool file_delete_poll(bContext *C)+{+ if (!ED_operator_file_browsing_active(C)) {+ return false;+ }++ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (!sfile || !params) {+ return false;+ }++ char dir[FILE_MAX_LIBEXTRA];+ if (filelist_islibrary(sfile->files, dir, nullptr)) {+ return false;+ }++ int numfiles = filelist_files_ensure(sfile->files);+ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL)) {+ /* Has a selected file -> the operator can run. */+ return true;+ }+ }++ return false;+}++static bool file_delete_single(const FileList *files,+ FileDirEntry *file,+ const char **r_error_message)+{+ char filepath[FILE_MAX_LIBEXTRA];+ filelist_file_get_full_path(files, file, filepath);+ if (BLI_delete_soft(filepath, r_error_message) != 0 || BLI_exists(filepath)) {+ return false;+ }++ return true;+}++static wmOperatorStatus file_delete_exec(bContext *C, wmOperator *op)+{+ wmWindowManager *wm = CTX_wm_manager(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ int numfiles = filelist_files_ensure(sfile->files);++ const char *error_message = nullptr;+ bool report_error = false;+ errno = 0;+ for (int i = 0; i < numfiles; i++) {+ if (filelist_entry_select_index_get(sfile->files, i, CHECK_ALL)) {+ FileDirEntry *file = filelist_file(sfile->files, i);+ if (!file_delete_single(sfile->files, file, &error_message)) {+ report_error = true;+ }+ }+ }++ if (report_error) {+ const char *error_prefix = "Could not delete file or directory: ";+ const char *errno_message = errno ? strerror(errno) : "unknown error";+ if (error_message != nullptr) {+ BKE_reportf(op->reports, RPT_ERROR, "%s%s, %s", error_prefix, error_message, errno_message);+ }+ else {+ BKE_reportf(op->reports, RPT_ERROR, "%s%s", error_prefix, errno_message);+ }+ }++ ED_fileselect_clear(wm, sfile);+ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_FILE_LIST, nullptr);++ return OPERATOR_FINISHED;+}++static wmOperatorStatus file_delete_invoke(bContext *C, wmOperator *op, const wmEvent * /*event*/)+{+ return WM_operator_confirm_ex(C,+ op,+ IFACE_("Delete selected files?"),+ nullptr,+ IFACE_("Delete"),+ ui::AlertIcon::None,+ false);+}++void FILE_OT_delete(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Delete Selected Files";+ ot->description = "Move selected files to the trash or recycle bin";+ ot->idname = "FILE_OT_delete";++ /* API callbacks. */+ ot->invoke = file_delete_invoke;+ ot->exec = file_delete_exec;+ ot->poll = file_delete_poll; /* <- important, handler is on window level */+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Enter Filter Text Operator+ * \{ */++static wmOperatorStatus file_start_filter_exec(bContext *C, wmOperator * /*op*/)+{+ const ScrArea *area = CTX_wm_area(C);+ const SpaceFile *sfile = CTX_wm_space_file(C);+ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (area) {+ int regiontype = sfile->browse_mode == FILE_BROWSE_MODE_FILES ? RGN_TYPE_UI : RGN_TYPE_HEADER;+ ARegion *region = BKE_region_find_in_listbase_by_type(&area->regionbase, regiontype);+ if (region) {+ ED_region_activate_rna_prop(C, region, params, "filter_search");+ }+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_start_filter(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Filter";+ ot->description = "Start entering filter text";+ ot->idname = "FILE_OT_start_filter";++ /* API callbacks. */+ ot->exec = file_start_filter_exec;+ /* Operator works for file or asset browsing */+ ot->poll = ED_operator_file_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Edit Directory Path Operator+ * \{ */++static wmOperatorStatus file_edit_directory_path_exec(bContext *C, wmOperator * /*op*/)+{+ const ScrArea *area = CTX_wm_area(C);+ const SpaceFile *sfile = CTX_wm_space_file(C);+ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ if (area) {+ for (ARegion ®ion : area->regionbase) {+ if (ui::textbutton_activate_rna(C, ®ion, params, "directory")) {+ break;+ }+ }+ }++ return OPERATOR_FINISHED;+}++void FILE_OT_edit_directory_path(wmOperatorType *ot)+{+ /* identifiers */+ ot->name = "Edit Directory Path";+ ot->description = "Start editing directory field";+ ot->idname = "FILE_OT_edit_directory_path";++ /* API callbacks. */+ ot->exec = file_edit_directory_path_exec;+ ot->poll = ED_operator_file_active;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Macro Operators+ * \{ */++void ED_operatormacros_file()+{+ // wmOperatorType *ot;+ // wmOperatorTypeMacro *otmacro;++ /* future macros */+}++/** \} */++} // namespace blenderdiff --git a/ui/space_file/file_panels.cc b/ui/space_file/file_panels.ccnew file mode 100644index 0000000..590d4a4--- /dev/null+++ b/ui/space_file/file_panels.cc@@ -0,0 +1,284 @@+/* SPDX-FileCopyrightText: 2009 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "BLI_listbase.h"+#include "BLI_string_utf8.h"+#include "BLI_utildefines.h"++#include "BKE_context.hh"+#include "BKE_screen.hh"++#include "BLT_translation.hh"++#include "DNA_screen_types.h"+#include "DNA_space_types.h"++#include "MEM_guardedalloc.h"++#include "RNA_access.hh"+#include "RNA_define.hh"+#include "RNA_prototypes.hh"++#include "ED_fileselect.hh"++#include "UI_interface.hh"+#include "UI_interface_c.hh"+#include "UI_interface_icons.hh"+#include "UI_interface_layout.hh"+#include "UI_resources.hh"++#include "WM_api.hh"+#include "WM_types.hh"++#include "file_intern.hh"+#include "filelist.hh"++#include <cstring>++namespace blender {++static bool file_panel_operator_poll(const bContext *C, PanelType * /*pt*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ return (sfile && sfile->op);+}++static bool file_panel_asset_browsing_poll(const bContext *C, PanelType * /*pt*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ return sfile && sfile->files && ED_fileselect_is_asset_browser(sfile);+}++static void file_panel_operator_header(const bContext *C, Panel *panel)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ wmOperator *op = sfile->op;++ const std::string opname = WM_operatortype_name(op->type, op->ptr);+ ui::panel_drawname_set(panel, opname);+}++static void file_panel_operator(const bContext *C, Panel *panel)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ wmOperator *op = sfile->op;++ block_func_set(panel->layout->block(), file_draw_check_cb, nullptr, nullptr);++ /* Hack: temporary hide. */+ const char *hide[] = {"filepath", "files", "directory", "filename"};+ /* Track overridden properties with #PROP_HIDDEN flag. */+ bool hidden_override[ARRAY_SIZE(hide)] = {false};+ for (int i = 0; i < ARRAY_SIZE(hide); i++) {+ PropertyRNA *prop = RNA_struct_find_property(op->ptr, hide[i]);+ if (prop && !(RNA_property_flag(prop) & PROP_HIDDEN)) {+ RNA_def_property_flag(prop, PROP_HIDDEN);+ hidden_override[i] = true;+ }+ }+ /* Operator file selector window is a kind of popup, use persistent layout panel states for the+ * active operator. */+ panel->runtime->layout_panel_states_storage = &ui::popup_persistent_layout_panel_states(+ op->type->idname);+ uiTemplateOperatorPropertyButs(+ C, panel->layout, op, ui::BUT_LABEL_ALIGN_NONE, ui::TEMPLATE_OP_PROPS_SHOW_EMPTY);++ /* Hack: temporary hide. */+ for (int i = 0; i < ARRAY_SIZE(hide); i++) {+ PropertyRNA *prop = RNA_struct_find_property(op->ptr, hide[i]);+ if (prop && hidden_override[i]) {+ RNA_def_property_clear_flag(prop, PROP_HIDDEN);+ }+ }++ block_func_set(panel->layout->block(), nullptr, nullptr, nullptr);+}++void file_tool_props_region_panels_register(ARegionType *art)+{+ PanelType *pt;++ pt = MEM_new_zeroed<PanelType>("spacetype file operator properties");+ STRNCPY_UTF8(pt->idname, "FILE_PT_operator");+ STRNCPY_UTF8(pt->label, N_("Operator"));+ STRNCPY_UTF8(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA);+ pt->flag = PANEL_TYPE_NO_HEADER;+ pt->poll = file_panel_operator_poll;+ pt->draw_header = file_panel_operator_header;+ pt->draw = file_panel_operator;+ BLI_addtail(&art->paneltypes, pt);+}++static void file_panel_execution_cancel_button(ui::Layout &layout)+{+ ui::Layout &row = layout.row(false);+ row.scale_x_set(0.8f);+ row.fixed_size_set(true);+ row.op("FILE_OT_cancel", IFACE_("Cancel"), ICON_NONE);+}++static void file_panel_execution_execute_button(ui::Layout &layout,+ const char *title,+ const bool overwrite)+{+ ui::Layout &row = layout.row(false);+ row.scale_x_set(0.8f);+ row.fixed_size_set(true);+ /* Just a display hint. */+ row.active_default_set(true);+ row.red_alert_set(overwrite);+ row.op("FILE_OT_execute", overwrite ? IFACE_("Overwrite") : title, ICON_NONE);+}++static void file_panel_execution_buttons_draw(const bContext *C, Panel *panel)+{+ bScreen *screen = CTX_wm_screen(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ ui::Block *block = panel->layout->block();++ PointerRNA *but_extra_rna_ptr;++ const bool overwrite_alert = file_draw_check_exists(sfile);+ const bool windows_layout =+#ifdef _WIN32+ true;+#else+ false;+#endif++ PointerRNA params_rna_ptr = RNA_pointer_create_discrete(+ &screen->id, RNA_FileSelectParams, params);++ ui::Layout &row = panel->layout->row(false);+ row.scale_y_set(1.3f);++ /* callbacks for operator check functions */+ block_func_set(block, file_draw_check_cb, nullptr, nullptr);++ ui::Button *but = uiDefButR(block,+ ui::ButtonType::Text,+ "",+ 0,+ 0,+ UI_UNIT_X * 5,+ UI_UNIT_Y,+ ¶ms_rna_ptr,+ "filename",+ 0,+ 0.0f,+ float(FILE_MAXFILE),+ overwrite_alert ? TIP_("File name, overwrite existing") :+ TIP_("File name"));++ BLI_assert(!button_flag_is_set(but, ui::BUT_UNDO));+ BLI_assert(!but_is_utf8(but));++ button_func_complete_set(but, autocomplete_file, nullptr);+ /* silly workaround calling NFunc to ensure this does not get called+ * immediate apply_but_func but only after button deactivates */+ button_funcN_set(but, file_filename_enter_handle, nullptr, but, nullptr, nullptr);++ if (params->flag & FILE_CHECK_EXISTING) {+ but_extra_rna_ptr = button_extra_operator_icon_add(+ but, "FILE_OT_filenum", wm::OpCallContext::ExecRegionWin, ICON_REMOVE);+ RNA_int_set(but_extra_rna_ptr, "increment", -1);+ but_extra_rna_ptr = button_extra_operator_icon_add(+ but, "FILE_OT_filenum", wm::OpCallContext::ExecRegionWin, ICON_ADD);+ RNA_int_set(but_extra_rna_ptr, "increment", 1);+ }++ /* check if this overrides a file and if the operator option is used */+ if (overwrite_alert) {+ button_flag_enable(but, ui::BUT_REDALERT);+ }+ block_func_set(block, nullptr, nullptr, nullptr);++ {+ ui::Layout &sub = row.row(false);+ sub.operator_context_set(wm::OpCallContext::ExecRegionWin);++ if (windows_layout) {+ file_panel_execution_execute_button(sub, params->title, overwrite_alert);+ file_panel_execution_cancel_button(sub);+ }+ else {+ file_panel_execution_cancel_button(sub);+ file_panel_execution_execute_button(sub, params->title, overwrite_alert);+ }+ }+}++void file_execute_region_panels_register(ARegionType *art)+{+ PanelType *pt;++ pt = MEM_new_zeroed<PanelType>("spacetype file execution buttons");+ STRNCPY_UTF8(pt->idname, "FILE_PT_execution_buttons");+ STRNCPY_UTF8(pt->label, N_("Execute Buttons"));+ STRNCPY_UTF8(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA);+ pt->flag = PANEL_TYPE_NO_HEADER;+ pt->poll = file_panel_operator_poll;+ pt->draw = file_panel_execution_buttons_draw;+ BLI_addtail(&art->paneltypes, pt);+}++static void file_panel_asset_catalog_buttons_draw(const bContext *C, Panel *panel)+{+ bScreen *screen = CTX_wm_screen(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ /* May be null if the library wasn't loaded yet. */+ asset_system::AssetLibrary *asset_library = filelist_asset_library(sfile->files);+ FileAssetSelectParams *params = ED_fileselect_get_asset_params(sfile);+ BLI_assert(params != nullptr);++ ui::Layout &col = panel->layout->column(false);+ ui::Layout &row = col.row(true);++ PointerRNA params_ptr = RNA_pointer_create_discrete(+ &screen->id, RNA_FileAssetSelectParams, params);++ row.prop(¶ms_ptr, "asset_library_reference", UI_ITEM_NONE, "", ICON_NONE);+ if (params->asset_library_ref.type == ASSET_LIBRARY_LOCAL) {+ bContext *mutable_ctx = CTX_copy(C);+ if (WM_operator_name_poll(mutable_ctx, "asset.bundle_install")) {+ col.separator();+ col.op_menu_enum(C,+ "asset.bundle_install",+ "asset_library_reference",+ IFACE_("Copy Bundle to Asset Library..."),+ ICON_IMPORT);+ }+ CTX_free(mutable_ctx);+ }+ else {+ PointerRNA ptr = row.op("ASSET_OT_library_refresh", "", ICON_FILE_REFRESH);+ RNA_boolean_set(&ptr, "use_shift_for_remote_listing", true);+ }++ col.separator();++ ed::asset_browser::file_create_asset_catalog_tree_view_in_layout(+ C, asset_library, col, sfile, params);+}++void file_tools_region_panels_register(ARegionType *art)+{+ PanelType *pt;++ pt = MEM_new_zeroed<PanelType>("spacetype file asset catalog buttons");+ STRNCPY_UTF8(pt->idname, "FILE_PT_asset_catalog_buttons");+ STRNCPY_UTF8(pt->label, N_("Asset Catalogs"));+ STRNCPY_UTF8(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA);+ pt->flag = PANEL_TYPE_NO_HEADER;+ pt->poll = file_panel_asset_browsing_poll;+ pt->draw = file_panel_asset_catalog_buttons_draw;+ BLI_addtail(&art->paneltypes, pt);+}++} // namespace blenderdiff --git a/ui/space_file/file_utils.cc b/ui/space_file/file_utils.ccnew file mode 100644index 0000000..86af5ad--- /dev/null+++ b/ui/space_file/file_utils.cc@@ -0,0 +1,44 @@+/* SPDX-FileCopyrightText: 2023 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "BLI_path_utils.hh"+#include "BLI_rect.h"+#include "BLI_string.h"++#include "BKE_blendfile.hh"++#include "DNA_screen_types.h"++#include "ED_fileselect.hh"++#include "file_intern.hh"++namespace blender {++void file_tile_boundbox(const ARegion *region, FileLayout *layout, const int file, rcti *r_bounds)+{+ int xmin, ymax;++ ED_fileselect_layout_tilepos(layout, file, &xmin, &ymax);+ ymax = int(region->v2d.tot.ymax) - ymax; /* real, view space ymax */+ BLI_rcti_init(r_bounds,+ xmin,+ xmin + layout->tile_w + layout->tile_border_x,+ ymax - layout->tile_h - layout->tile_border_y,+ ymax);+}++void file_path_to_ui_path(const char *path, MutableCStr r_path)+{+ char tmp_path[FILE_MAX_LIBEXTRA];+ STRNCPY(tmp_path, path);+ BLI_path_slash_rstrip(tmp_path);+ STRNCPY(r_path, BKE_blendfile_extension_check(tmp_path) ? tmp_path : path);+}++} // namespace blenderdiff --git a/ui/space_file/filelist.hh b/ui/space_file/filelist.hhnew file mode 100644index 0000000..8dc5266--- /dev/null+++ b/ui/space_file/filelist.hh@@ -0,0 +1,260 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#pragma once++#include <cstddef>+#include <cstdint>++#include "DNA_space_types.h"+struct BlendHandle;+namespace blender {++struct AssetLibraryReference;+struct bContext;+struct FileIndexerType;+struct FileList;+struct FileSelection;+struct ID;+struct ImBuf;+struct bUUID;+struct wmWindowManager;+namespace asset_system {+class AssetLibrary;+class AssetRepresentation;+} // namespace asset_system++struct FileDirEntry;++using FileUID = uint32_t;++enum FileSelType {+ FILE_SEL_REMOVE = 0,+ FILE_SEL_ADD = 1,+ FILE_SEL_TOGGLE = 2,+};++enum FileCheckType {+ CHECK_DIRS = 1,+ CHECK_FILES = 2,+ CHECK_ALL = 3,+};++void filelist_setsorting(FileList *filelist, short sort, bool invert_sort);+void filelist_sort(FileList *filelist);++void filelist_setfilter_options(FileList *filelist,+ bool do_filter,+ bool hide_dot,+ bool hide_parent,+ uint64_t filter,+ uint64_t filter_id,+ bool filter_assets_only,+ bool filter_assets_hide_online,+ bool filter_assets_hide_offline,+ const char *filter_search);+/**+ * Set the indexer to be used by the filelist.+ *+ * The given indexer allocation should be handled by the caller or defined statically.+ */+void filelist_setindexer(FileList *filelist, const FileIndexerType *indexer);+void filelist_remote_asset_library_refresh_online_assets_status(+ const FileList *filelist, StringRef remote_url, StringRef absolute_downloaded_file);+void filelist_set_asset_include_online(FileList *filelist, bool show_online_assets);+/**+ * \param catalog_id: The catalog that should be filtered by if \a catalog_visibility is+ * #FILE_SHOW_ASSETS_FROM_CATALOG. May be NULL otherwise.+ */+void filelist_set_asset_catalog_filter_options(+ FileList *filelist,+ eFileSel_Params_AssetCatalogVisibility catalog_visibility,+ const bUUID *catalog_id);+bool filelist_needs_filtering(FileList *filelist);+void filelist_tag_needs_filtering(FileList *filelist);+void filelist_filter(FileList *filelist);+/**+ * \param asset_library_ref: May be NULL to unset the library.+ * \param on_change: Called when a different asset library was set. NOT called when the asset+ * library was unset (i.e. \a asset_library_ref is null).+ */+void filelist_setlibrary(FileList *filelist,+ const AssetLibraryReference *asset_library_ref,+ FunctionRef<void()> on_change = nullptr);++void filelist_init_icons();+void filelist_free_icons();+void filelist_file_get_full_path(const FileList *filelist,+ const FileDirEntry *file,+ char r_filepath[/*FILE_MAX_LIBEXTRA*/ 1282]);+bool filelist_file_is_preview_pending(const FileList *filelist, const FileDirEntry *file);+void filelist_online_asset_preview_request(const bContext *C, FileDirEntry *entry);+ImBuf *filelist_file_get_preview_image(const FileDirEntry *file);+ImBuf *filelist_geticon_special_file_image_ex(const FileDirEntry *file);+/**+ * Get one of the larger document icons as image. E.g. a folder or file icon. A file type icon can+ * be overlaid on top then.+ */+ImBuf *filelist_geticon_special_file_image(FileList *filelist, int index);+int filelist_geticon_file_type(FileList *filelist, int index, bool is_main);++/**+ * \param is_from_global_asset_list: Set to indicate that the file list is owned by the+ * #ED_asset_list.hh API (global storage to load and store assets globally), not by an+ * Asset/File Browser.+ */+FileList *filelist_new(short type, bool is_from_global_asset_list = false);+void filelist_settype(FileList *filelist, short type);+void filelist_clear(FileList *filelist);+void filelist_clear_ex(FileList *filelist,+ bool do_asset_library,+ bool do_cache,+ bool do_selection);+/**+ * A "smarter" version of #filelist_clear() that calls partial clearing based on the filelist+ * force-reset flags.+ */+void filelist_clear_from_reset_tag(FileList *filelist);+void filelist_free(FileList *filelist);++/**+ * Get the root path of the file list. To get the full path for a file, use+ * #filelist_file_get_full_path().+ */+const char *filelist_dir(const FileList *filelist);+bool filelist_is_dir(const FileList *filelist, const char *path);+/**+ * May modify in place given `dirpath`, which is expected to be #FILE_MAX_LIBEXTRA length.+ */+void filelist_setdir(FileList *filelist, char dirpath[/*FILE_MAX_LIBEXTRA*/ 1282]);++/**+ * Limited version of full update done by space_file's file_refresh(),+ * to be used by operators and such.+ * Ensures given filelist is ready to be used (i.e. it is filtered and sorted),+ * unless it is tagged for a full refresh.+ */+int filelist_files_ensure(FileList *filelist);+int filelist_needs_reading(const FileList *filelist);+/**+ * Request a file from the file browser cache, adding it to the cache if necessary.+ *+ * As a rule of thumb, this can be used for operations on individual files (e.g. selection, active,+ * renaming, etc.). But avoid calling this on many files (like when iterating the entire list), to+ * not create a bunch of cache entries for a single operation. While a bit against the point of+ * "intern" entries, in this case it's probably better to have queries like+ * #filelist_entry_get_id(), that take a file index and return data directly from the+ * #FileListInternEntry.+ */+FileDirEntry *filelist_file(FileList *filelist, int index);+FileDirEntry *filelist_file_ex(FileList *filelist, int index, bool use_request);++/**+ * Find a file from a file name, or more precisely, its file-list relative path, inside the+ * filtered items. \return The index of the found file or -1.+ */+int filelist_file_find_path(FileList *filelist, const char *filename);+/**+ * Find a file representing \a id.+ * \return The index of the found file or -1.+ */+int filelist_file_find_id(const FileList *filelist, const ID *id);+/**+ * Get the ID a file represents (if any). For #FILE_MAIN_ASSET.+ */+ID *filelist_file_get_id(const FileDirEntry *file);+/**+ * Same as #filelist_file_get_id(), but gets the file by index (doesn't require the file to be+ * cached, uses #FileListInternEntry only). */+ID *filelist_entry_get_id(const FileList *filelist, int index);+asset_system::AssetRepresentation *filelist_entry_get_asset_representation(+ const FileList *filelist, const int index);+/**+ * Get the #FileDirEntry.relpath value without requiring the #FileDirEntry to be available (doesn't+ * require the file to be cached, uses #FileListInternEntry only).+ */+const char *filelist_entry_get_relpath(const FileList *filelist, int index);+bool filelist_uid_is_set(const FileUID uid);+void filelist_uid_unset(FileUID *r_uid);+void filelist_file_cache_slidingwindow_set(FileList *filelist, size_t window_size);+/**+ * Load in cache all entries "around" given index (as much as block cache may hold).+ */+bool filelist_file_cache_block(FileList *filelist, int index);++bool filelist_needs_force_reset(const FileList *filelist);+void filelist_tag_force_reset(FileList *filelist);+void filelist_tag_force_reset_mainfiles(FileList *filelist);+void filelist_tag_reload_asset_library(FileList *filelist);+bool filelist_pending(const FileList *filelist);+bool filelist_needs_reset_on_main_changes(const FileList *filelist);+bool filelist_is_ready(const FileList *filelist);++unsigned int filelist_entry_select_set(const FileList *filelist,+ const FileDirEntry *entry,+ FileSelType select,+ const eDirEntry_SelectFlag flag,+ FileCheckType check);+void filelist_entry_select_index_set(FileList *filelist,+ int index,+ FileSelType select,+ eDirEntry_SelectFlag flag,+ FileCheckType check);+void filelist_entries_select_index_range_set(FileList *filelist,+ FileSelection *sel,+ FileSelType select,+ eDirEntry_SelectFlag flag,+ FileCheckType check);+eDirEntry_SelectFlag filelist_entry_select_get(FileList *filelist,+ FileDirEntry *entry,+ FileCheckType check);+eDirEntry_SelectFlag filelist_entry_select_index_get(FileList *filelist,+ int index,+ FileCheckType check);+bool filelist_entry_is_selected(FileList *filelist, int index);+/**+ * Set selection of the '..' parent entry, but only if it's actually visible.+ */+void filelist_entry_parent_select_set(FileList *filelist,+ FileSelType select,+ eDirEntry_SelectFlag flag,+ FileCheckType check);++void filelist_setrecursion(FileList *filelist, int recursion_level);+/** Set the extension glob used to tag entries with #FILE_TYPE_OPERATOR. */+void filelist_setglob(FileList *filelist, const char *filter_glob);++asset_system::AssetLibrary *filelist_asset_library(FileList *filelist);++BlendHandle *filelist_lib(FileList *filelist);+/**+ * \param dir: Must be #FILE_MAX_LIBEXTRA long!+ */+bool filelist_islibrary(FileList *filelist, char *dir, char **r_group);+void filelist_freelib(FileList *filelist);++/**+ * Return the total raw number of entries listed in the given `filelist`, whether they are+ * filtered out or not.+ */+int filelist_files_num_entries(FileList *filelist);++/** Forcibly run the job as a blocking task on the main thread. */+void filelist_readjob_blocking_run(FileList *filelist, int space_notifier, const bContext *C);++/** May run the job in either the main thread or asynchronously. */+void filelist_readjob_start(FileList *filelist, int space_notifier, const bContext *C);+void filelist_readjob_stop(FileList *filelist, wmWindowManager *wm);+int filelist_readjob_running(FileList *filelist, wmWindowManager *wm);++bool filelist_cache_previews_update(FileList *filelist);+void filelist_cache_previews_set(FileList *filelist, bool use_previews);+bool filelist_cache_previews_running(FileList *filelist);+bool filelist_cache_previews_done(FileList *filelist);++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist.cc b/ui/space_file/filelist/filelist.ccnew file mode 100644index 0000000..90cabc5--- /dev/null+++ b/ui/space_file/filelist/filelist.cc@@ -0,0 +1,2128 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++/* global includes */++#include <algorithm>+#include <cstdlib>+#include <cstring>+#include <ctime>+#include <memory>+#include <optional>+#include <sys/stat.h>++#include "AS_asset_library.hh"+#include "AS_asset_representation.hh"+#include "AS_remote_library.hh"++#include "DNA_space_enums.h"+#include "MEM_guardedalloc.h"++#include "BLF_api.hh"++#include "BLI_fileops.hh"+#include "BLI_ghash.h"+#include "BLI_listbase.h"+#include "BLI_math_vector.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_task.h"+#include "BLI_threads.h"++#include "BKE_asset.hh"+#include "BKE_blendfile.hh"+#include "BKE_context.hh"+#include "BKE_global.hh"+#include "BKE_icons.hh"+#include "BKE_main.hh"+#include "BKE_preferences.h"+#include "BKE_preview_image.hh"++#include "DNA_asset_types.h"+#include "DNA_space_types.h"+#include "DNA_userdef_types.h"++#include "ED_asset_indexer.hh"+#include "ED_fileselect.hh"++#include "IMB_imbuf.hh"+#include "IMB_imbuf_types.hh"+#include "IMB_thumbs.hh"++#include "MOV_util.hh"++#include "WM_api.hh"+#include "WM_types.hh"++#include "UI_interface_icons.hh"+#include "UI_resources.hh"++#include "atomic_ops.h"++#include "../file_indexer.hh"+#include "../file_intern.hh"+#include "../filelist.hh"+#include "filelist_intern.hh"+#include "filelist_readjob.hh"++namespace blender {++static ImBuf *gSpecialFileImages[int(SpecialFileImages::_Max)];++static void remote_asset_library_refresh_online_assets_status(+ const FileList *filelist, const StringRef downloaded_file_abspath)+{+ for (FileListInternEntry &entry : filelist->filelist_intern.entries) {+ std::shared_ptr<asset_system::AssetRepresentation> asset = entry.asset.lock();+ if (!asset) {+ continue;+ }++ if (entry.typeflag & FILE_TYPE_ASSET_ONLINE) {+ /* #AssetRepresentation.full_library_path() will only return a non-empty string if the+ * asset's path points into some .blend on disk. */+ std::string filepath = asset->full_library_path();+ if (filepath.empty()) {+ continue;+ }+ BLI_assert(BLI_is_file(filepath.c_str()));++ entry.typeflag &= ~FILE_TYPE_ASSET_ONLINE;+ asset->online_asset_mark_downloaded();++ if (FileDirEntry **cached_entry = filelist->filelist_cache->uids.lookup_ptr(entry.uid)) {+ (**cached_entry).typeflag &= ~FILE_TYPE_ASSET_ONLINE;+ }+ }+ else if (asset->remote_file_status() == asset_system::RemoteAssetFileStatus::NO_MATCH) {+ /* For already-downloaded assets that didn't match the remote listing, clear the mismatch+ * status when their specific file has been re-downloaded. */+ std::string filepath = asset->full_library_path();+ if (filepath != downloaded_file_abspath) {+ continue;+ }+ asset->online_asset_mark_downloaded();+ }+ }+}++void filelist_remote_asset_library_refresh_online_assets_status(+ const FileList *filelist,+ const blender::StringRef remote_url,+ const blender::StringRef absolute_downloaded_file)+{+ if (!filelist->asset_library) {+ return;+ }+ if (remote_url.is_empty()) {+ return;+ }++ if (asset_system::contains_assets_from_remote_url(*filelist->asset_library, remote_url)) {+ remote_asset_library_refresh_online_assets_status(filelist, absolute_downloaded_file);+ }+}++void filelist_setindexer(FileList *filelist, const FileIndexerType *indexer)+{+ BLI_assert(filelist);+ BLI_assert(indexer);++ filelist->indexer = indexer;+}++void filelist_set_asset_include_online(FileList *filelist, const bool show_online_assets)+{+ if (!filelist->asset_library_ref ||+ !asset_system::is_or_contains_remote_libraries(*filelist->asset_library_ref))+ {+ /* Online flag has no effect if not displaying online libraries. This function will be called+ * again when switching libraries, so updating the flag here shouldn't be needed. Still do it+ * for predictability. */+ SET_FLAG_FROM_TEST(filelist->flags, show_online_assets, FL_ASSETS_INCLUDE_ONLINE);+ return;+ }++ if (show_online_assets && ((filelist->flags & FL_ASSETS_INCLUDE_ONLINE) == 0)) {+ /* Full refresh when enabling online assets, so online asset loading is triggered. */+ filelist_tag_force_reset(filelist);+ filelist->flags |= FL_ASSETS_INCLUDE_ONLINE;+ }+ else if (!show_online_assets && ((filelist->flags & FL_ASSETS_INCLUDE_ONLINE) != 0)) {+ /* Simply filter out online assets when they were already loaded. */+ filelist_tag_needs_filtering(filelist);+ filelist->flags &= ~FL_ASSETS_INCLUDE_ONLINE;+ }+}++void filelist_set_asset_catalog_filter_options(+ FileList *filelist,+ eFileSel_Params_AssetCatalogVisibility catalog_visibility,+ const bUUID *catalog_id)+{+ if (!filelist->filter_data.asset_catalog_filter) {+ /* There's no filter data yet. */+ filelist->filter_data.asset_catalog_filter =+ ed::asset_browser::file_create_asset_catalog_filter_settings();+ }++ const bool needs_update = file_set_asset_catalog_filter_settings(+ filelist->filter_data.asset_catalog_filter, catalog_visibility, *catalog_id);++ if (needs_update) {+ filelist_tag_needs_filtering(filelist);+ }+}++/**+ * Checks two libraries for equality.+ * \return True if the libraries match.+ */+static bool filelist_compare_asset_libraries(const AssetLibraryReference *library_a,+ const AssetLibraryReference *library_b)+{+ if (library_a->type != library_b->type) {+ return false;+ }+ if (library_a->type == ASSET_LIBRARY_CUSTOM) {+ /* Don't only check the index, also check that it's valid. */+ bUserAssetLibrary *library_ptr_a = BKE_preferences_asset_library_find_index(+ &U, library_a->custom_library_index);+ return (library_ptr_a != nullptr) &&+ (library_a->custom_library_index == library_b->custom_library_index);+ }++ return true;+}++void filelist_setlibrary(FileList *filelist,+ const AssetLibraryReference *asset_library_ref,+ FunctionRef<void()> on_change)+{+ /* Unset if needed. */+ if (!asset_library_ref) {+ if (filelist->asset_library_ref) {+ MEM_SAFE_DELETE(filelist->asset_library_ref);+ filelist->flags |= FL_FORCE_RESET;+ }+ return;+ }++ bool changed = false;+ if (!filelist->asset_library_ref) {+ filelist->asset_library_ref = MEM_new<AssetLibraryReference>("filelist asset library");+ *filelist->asset_library_ref = *asset_library_ref;++ filelist->flags |= FL_FORCE_RESET;+ changed = true;+ }+ else if (!filelist_compare_asset_libraries(filelist->asset_library_ref, asset_library_ref)) {+ *filelist->asset_library_ref = *asset_library_ref;+ filelist->flags |= FL_FORCE_RESET;+ changed = true;+ }++ if (changed && on_change) {+ on_change();+ }+}++/* ********** Icon/image helpers ********** */++void filelist_free_icons()+{+ BLI_assert(G.background == false);++ for (int i = 0; i < int(SpecialFileImages::_Max); i++) {+ IMB_freeImBuf(gSpecialFileImages[i]);+ gSpecialFileImages[i] = nullptr;+ }+}++void filelist_file_get_full_path(const FileList *filelist,+ const FileDirEntry *file,+ char r_filepath[FILE_MAX_LIBEXTRA])+{+ if (file->asset) {+ const std::string asset_path = file->asset->full_path();+ BLI_strncpy(r_filepath, asset_path.c_str(), FILE_MAX_LIBEXTRA);+ return;+ }++ const char *root = filelist_dir(filelist);+ BLI_path_join(MutableCStr(r_filepath, FILE_MAX_LIBEXTRA), root, file->relpath);+}++bool filelist_file_is_preview_pending(const FileList *filelist, const FileDirEntry *file)+{+ /* Actual preview loading is only started after the filelist is loaded, so the file isn't flagged+ * with #FILE_ENTRY_PREVIEW_LOADING yet. */+ const bool filelist_ready = filelist_is_ready(filelist);+ if (!filelist_ready) {+ return true;+ }+ const PreviewImage *asset_preview = file->asset ? file->asset->get_preview() : nullptr;+ if (asset_preview && (asset_preview->flag[ICON_SIZE_PREVIEW] & PRV_RENDERING)) {+ return true;+ }++ return file->flags & FILE_ENTRY_PREVIEW_LOADING;+}++static FileDirEntry *filelist_geticon_get_file(FileList *filelist, const int index)+{+ BLI_assert(G.background == false);++ return filelist_file(filelist, index);+}++ImBuf *filelist_file_get_preview_image(const FileDirEntry *file)+{+ return (file->preview_icon_id && BKE_icon_is_imbuf(file->preview_icon_id)) ?+ BKE_icon_imbuf_get_buffer(file->preview_icon_id) :+ nullptr;+}++static ImBuf *filelist_ensure_special_file_image(SpecialFileImages image, int icon)+{+ ImBuf *ibuf = gSpecialFileImages[int(image)];+ if (ibuf) {+ return ibuf;+ }+ return gSpecialFileImages[int(image)] = ui::svg_icon_bitmap(icon, 256.0f, false);+}++ImBuf *filelist_geticon_special_file_image_ex(const FileDirEntry *file)+{+ ImBuf *ibuf = nullptr;++ if (file->typeflag & FILE_TYPE_DIR) {+ if (FILENAME_IS_PARENT(file->relpath)) {+ ibuf = filelist_ensure_special_file_image(SpecialFileImages::Parent, ICON_FILE_PARENT_LARGE);+ }+ else {+ ibuf = filelist_ensure_special_file_image(SpecialFileImages::Folder, ICON_FILE_FOLDER_LARGE);+ }+ }+ else {+ ibuf = filelist_ensure_special_file_image(SpecialFileImages::Document, ICON_FILE_LARGE);+ }++ return ibuf;+}++ImBuf *filelist_geticon_special_file_image(FileList *filelist, const int index)+{+ FileDirEntry *file = filelist_geticon_get_file(filelist, index);+ return filelist_geticon_special_file_image_ex(file);+}++static int filelist_geticon_file_type_ex(const FileList *filelist,+ const FileDirEntry *file,+ const bool is_main,+ const bool ignore_libdir)+{+ const eFileSel_File_Types typeflag = eFileSel_File_Types(file->typeflag);++ if ((typeflag & FILE_TYPE_DIR) &&+ !(ignore_libdir && (typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER))))+ {+ if (FILENAME_IS_PARENT(file->relpath)) {+ return is_main ? ICON_FILE_PARENT : ICON_NONE;+ }+ if (typeflag & FILE_TYPE_BUNDLE) {+ return ICON_UGLYPACKAGE;+ }+ if (typeflag & FILE_TYPE_BLENDER) {+ return ICON_FILE_BLEND;+ }+ if (is_main) {+ /* Do not return icon for folders if icons are not 'main' draw type+ * (e.g. when used over previews). */+ return (file->attributes & FILE_ATTR_ANY_LINK) ? ICON_FOLDER_REDIRECT : ICON_FILE_FOLDER;+ }++ /* If this path is in System list or path cache then use that icon. */+ FSMenu *fsmenu = ED_fsmenu_get();+ FSMenuCategory categories[] = {+ FS_CATEGORY_SYSTEM,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FS_CATEGORY_OTHER,+ };++ for (int i = 0; i < ARRAY_SIZE(categories); i++) {+ FSMenuEntry *tfsm = ED_fsmenu_get_category(fsmenu, categories[i]);+ char fullpath[FILE_MAX_LIBEXTRA];+ char *target = fullpath;+ if (file->redirection_path) {+ target = file->redirection_path;+ }+ else if (filelist) {+ filelist_file_get_full_path(filelist, file, fullpath);+ BLI_path_slash_ensure(fullpath);+ }+ for (; tfsm; tfsm = tfsm->next) {+ if (STREQ(tfsm->path, target)) {+ /* Never want a little folder inside a large one. */+ return (tfsm->icon == ICON_FILE_FOLDER) ? ICON_NONE : tfsm->icon;+ }+ }+ }++ if (file->attributes & FILE_ATTR_OFFLINE) {+ return ICON_STATUS_ERROR;+ }+ if (file->attributes & FILE_ATTR_TEMPORARY) {+ return ICON_FILE_CACHE;+ }+ if (file->attributes & FILE_ATTR_SYSTEM) {+ return ICON_SYSTEM;+ }+ }++ if (typeflag & FILE_TYPE_BLENDER) {+ return (is_main || file->preview_icon_id) ? ICON_FILE_BLEND : ICON_BLENDER;+ }+ if (typeflag & FILE_TYPE_BLENDER_BACKUP) {+ return ICON_FILE_BACKUP;+ }+ if (typeflag & FILE_TYPE_IMAGE) {+ return ICON_FILE_IMAGE;+ }+ if (typeflag & FILE_TYPE_MOVIE) {+ return ICON_FILE_MOVIE;+ }+ if (typeflag & FILE_TYPE_PYSCRIPT) {+ return ICON_FILE_SCRIPT;+ }+ if (typeflag & FILE_TYPE_SOUND) {+ return ICON_FILE_SOUND;+ }+ if (typeflag & FILE_TYPE_FTFONT) {+ return ICON_FILE_FONT;+ }+ if (typeflag & FILE_TYPE_BTX) {+ return ICON_FILE_BLANK;+ }+ if (typeflag & FILE_TYPE_ALEMBIC) {+ return ICON_FILE_3D;+ }+ if (typeflag & FILE_TYPE_USD) {+ return ICON_FILE_3D;+ }+ if (typeflag & FILE_TYPE_VOLUME) {+ return ICON_FILE_VOLUME;+ }+ if (typeflag & FILE_TYPE_OBJECT_IO) {+ return ICON_FILE_3D;+ }+ if (typeflag & FILE_TYPE_TEXT) {+ return ICON_FILE_TEXT;+ }+ if (typeflag & FILE_TYPE_ARCHIVE) {+ return ICON_FILE_ARCHIVE;+ }+ if (typeflag & FILE_TYPE_BLENDERLIB) {+ const int ret = ui::icon_from_idcode(file->blentype);+ if (ret != ICON_NONE) {+ return ret;+ }+ }+ return is_main ? ICON_FILE_BLANK : ICON_NONE;+}++int filelist_geticon_file_type(FileList *filelist, const int index, const bool is_main)+{+ FileDirEntry *file = filelist_geticon_get_file(filelist, index);++ return filelist_geticon_file_type_ex(filelist, file, is_main, false);+}++int ED_file_icon(const FileDirEntry *file)+{+ return file->preview_icon_id ? file->preview_icon_id :+ filelist_geticon_file_type_ex(nullptr, file, false, false);+}++bool filelist_intern_entry_is_main_file(const FileListInternEntry *intern_entry)+{+ return intern_entry->local_data.id != nullptr;+}++/* ********** Main ********** */++static void filelist_entry_clear(FileDirEntry *entry)+{+ if (entry->name && ((entry->flags & FILE_ENTRY_NAME_FREE) != 0)) {+ MEM_delete(const_cast<char *>(entry->name));+ }+ if (entry->relpath) {+ MEM_delete(entry->relpath);+ }+ if (entry->redirection_path) {+ MEM_delete(entry->redirection_path);+ }+ if (entry->preview_icon_id &&+ /* Online assets previews are managed by the general UI preview system, not the file browser+ * one. Don't mess with them. */+ ((entry->typeflag & FILE_TYPE_ASSET_ONLINE) == 0))+ {+ BKE_icon_delete(entry->preview_icon_id);+ entry->preview_icon_id = 0;+ }+}++static void filelist_entry_free(FileDirEntry *entry)+{+ filelist_entry_clear(entry);+ MEM_delete(entry);+}++static void filelist_direntryarr_free(FileDirEntryArr *array)+{+#if 0+ FileDirEntry *entry, *entry_next;++ for (entry = array->entries.first; entry; entry = entry_next) {+ entry_next = entry->next;+ filelist_entry_free(entry);+ }+ array->entries.clear_no_delete();+#else+ BLI_assert(array->entries.is_empty());+#endif+ array->entries_num = FILEDIR_NBR_ENTRIES_UNSET;+ array->entries_filtered_num = FILEDIR_NBR_ENTRIES_UNSET;+}++static void filelist_intern_entry_free(FileList *filelist, FileListInternEntry *entry)+{+ if (auto asset_ptr = entry->asset.lock()) {+ BLI_assert(filelist->asset_library);+ filelist->asset_library->remove_asset(*asset_ptr);+ }++ if (entry->relpath) {+ MEM_delete(entry->relpath);+ }+ if (entry->redirection_path) {+ MEM_delete(entry->redirection_path);+ }+ if (entry->name && entry->free_name) {+ MEM_delete(const_cast<char *>(entry->name));+ }+ MEM_delete(entry);+}++static void filelist_intern_free(FileList *filelist)+{+ FileListIntern *filelist_intern = &filelist->filelist_intern;+ for (FileListInternEntry &entry : filelist_intern->entries.items_mutable()) {+ filelist_intern_entry_free(filelist, &entry);+ }+ filelist_intern->entries.clear_no_delete();++ MEM_SAFE_DELETE(filelist_intern->filtered);+}++/**+ * \return the number of main files removed.+ */+static int filelist_intern_free_main_files(FileList *filelist)+{+ FileListIntern *filelist_intern = &filelist->filelist_intern;+ int removed_counter = 0;+ for (FileListInternEntry &entry : filelist_intern->entries.items_mutable()) {+ if (!filelist_intern_entry_is_main_file(&entry)) {+ continue;+ }++ BLI_remlink(&filelist_intern->entries, &entry);+ filelist_intern_entry_free(filelist, &entry);+ removed_counter++;+ }++ if (removed_counter > 0) {+ MEM_SAFE_DELETE(filelist_intern->filtered);+ }+ return removed_counter;+}++static void filelist_cache_preview_runf(TaskPool *__restrict pool, void *taskdata)+{+ FileListEntryCache *cache = static_cast<FileListEntryCache *>(BLI_task_pool_user_data(pool));+ if (cache->previews_cancel_token.is_cancelled()) {+ return;+ }++ FileListEntryPreviewTaskData *preview_taskdata = static_cast<FileListEntryPreviewTaskData *>(+ taskdata);+ FileListEntryPreview *preview = preview_taskdata->preview;++ /* XXX #THB_SOURCE_IMAGE for "historic" reasons. The case of an undefined source should be+ * handled better. */+ ThumbSource source = THB_SOURCE_IMAGE;++ // printf("%s: Start (%d)...\n", __func__, threadid);++ // printf("%s: %d - %s - %p\n", __func__, preview->index, preview->path, preview->img);+ BLI_assert(preview->flags &+ (FILE_TYPE_IMAGE | FILE_TYPE_MOVIE | FILE_TYPE_FTFONT | FILE_TYPE_BLENDER |+ FILE_TYPE_OBJECT_IO | FILE_TYPE_BLENDER_BACKUP | FILE_TYPE_BLENDERLIB));+ BLI_assert((preview->flags & FILE_TYPE_ASSET_ONLINE) == 0);++ if (preview->flags & FILE_TYPE_IMAGE) {+ source = THB_SOURCE_IMAGE;+ }+ else if (preview->flags & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP | FILE_TYPE_BLENDERLIB))+ {+ source = THB_SOURCE_BLEND;+ }+ else if (preview->flags & FILE_TYPE_MOVIE) {+ source = THB_SOURCE_MOVIE;+ }+ else if (preview->flags & FILE_TYPE_FTFONT) {+ source = THB_SOURCE_FONT;+ }+ else if (preview->flags & FILE_TYPE_OBJECT_IO) {+ source = THB_SOURCE_OBJECT_IO;+ }++ IMB_thumb_path_lock(preview->filepath);+ /* Always generate biggest preview size for now, it's simpler and avoids having to re-generate+ * in case user switch to a bigger preview size. */+ ImBuf *imbuf = IMB_thumb_manage(+ preview->filepath, THB_LARGE, source, &cache->previews_cancel_token);+ IMB_thumb_path_unlock(preview->filepath);++ if (imbuf) {+ preview->icon_id = BKE_icon_imbuf_create(imbuf);+ }++ /* Move ownership to the done queue. */+ preview_taskdata->preview = nullptr;++ BLI_thread_queue_push(cache->previews_done, preview, BLI_THREAD_QUEUE_WORK_PRIORITY_NORMAL);++ // printf("%s: End (%d)...\n", __func__, threadid);+}++static void filelist_cache_preview_freef(TaskPool *__restrict /*pool*/, void *taskdata)+{+ FileListEntryPreviewTaskData *preview_taskdata = static_cast<FileListEntryPreviewTaskData *>(+ taskdata);++ /* In case the preview wasn't moved to the "done" queue yet. */+ if (preview_taskdata->preview) {+ MEM_delete(preview_taskdata->preview);+ }++ MEM_delete(preview_taskdata);+}++static void filelist_cache_preview_ensure_running(FileListEntryCache *cache)+{+ if (!cache->previews_pool) {+ cache->previews_pool = BLI_task_pool_create_background(cache, TASK_PRIORITY_LOW);+ cache->previews_done = BLI_thread_queue_init();+ cache->previews_todo_count = 0;++ IMB_thumb_locks_acquire();+ }+}++static void filelist_cache_previews_clear(FileListEntryCache *cache)+{+ if (cache->previews_pool) {+ cache->previews_cancel_token.cancel();+ BLI_task_pool_work_and_wait(cache->previews_pool);++ for (FileDirEntry &entry : cache->cached_entries) {+ entry.flags &= ~FILE_ENTRY_PREVIEW_LOADING;+ }++ FileListEntryPreview *preview;+ while ((preview = static_cast<FileListEntryPreview *>(+ BLI_thread_queue_pop_timeout(cache->previews_done, 0))))+ {+ // printf("%s: DONE %d - %s - %p\n", __func__, preview->index, preview->path,+ // preview->img);+ BLI_assert((preview->flags & FILE_TYPE_ASSET_ONLINE) == 0);+ if (preview->icon_id) {+ BKE_icon_delete(preview->icon_id);+ }+ MEM_delete(preview);+ }+ cache->previews_todo_count = 0;+ cache->previews_cancel_token.reset();+ }+}++static void filelist_cache_previews_free(FileListEntryCache *cache)+{+ if (cache->previews_pool) {+ BLI_thread_queue_nowait(cache->previews_done);++ filelist_cache_previews_clear(cache);++ BLI_thread_queue_free(cache->previews_done);+ BLI_task_pool_free(cache->previews_pool);+ cache->previews_pool = nullptr;+ cache->previews_done = nullptr;+ cache->previews_todo_count = 0;++ IMB_thumb_locks_release();+ }++ cache->flags &= ~FLC_PREVIEWS_ACTIVE;+}++/**+ * Check if a preview for \a entry may be requested. Further conditions may apply, this just helps+ * to skip plenty of entries where it's easy to tell that no valid preview will be available or is+ * being loaded already.+ */+static bool filelist_file_preview_load_poll(const FileDirEntry *entry)+{+ if (entry->flags & (FILE_ENTRY_INVALID_PREVIEW | FILE_ENTRY_PREVIEW_LOADING)) {+ return false;+ }++ if (!(entry->typeflag &+ (FILE_TYPE_IMAGE | FILE_TYPE_MOVIE | FILE_TYPE_FTFONT | FILE_TYPE_OBJECT_IO |+ FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP | FILE_TYPE_BLENDERLIB)))+ {+ return false;+ }++ /* If we know this is an external ID without a preview, skip loading the preview. Can save quite+ * some time in heavy files, because otherwise for each missing preview and for each preview+ * reload, we'd reopen the .blend to look for the preview. */+ if ((entry->typeflag & FILE_TYPE_BLENDERLIB) &&+ (entry->flags & FILE_ENTRY_BLENDERLIB_NO_PREVIEW))+ {+ return false;+ }++ /* External ID that is also a directory is never previewed. */+ if ((entry->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_DIR)) ==+ (FILE_TYPE_BLENDERLIB | FILE_TYPE_DIR))+ {+ return false;+ }++ return true;+}++void filelist_online_asset_preview_request(const bContext *C, FileDirEntry *entry)+{+ BLI_assert(entry->asset);+ BLI_assert(entry->asset->is_online_only());++ if (entry->preview_icon_id) {+ return;+ }++ if (!filelist_file_preview_load_poll(entry)) {+ return;+ }++ /* Request online preview if needed. */+ if (entry->asset->is_online_only()) {+ entry->asset->ensure_previewable(*C, CTX_wm_reports(C));++ const PreviewImage *preview = entry->asset->get_preview();++ if (preview) {+ entry->preview_icon_id = preview->runtime->icon_id;+ }+ else {+ entry->flags |= FILE_ENTRY_INVALID_PREVIEW;+ }+ }+}++/**+ * \return True if a new preview request was pushed, false otherwise (e.g. because the preview is+ * already loaded, invalid or not supported).+ */+static bool filelist_cache_previews_push(FileList *filelist, FileDirEntry *entry, const int index)+{+ FileListEntryCache *cache = filelist->filelist_cache;++ BLI_assert(cache->flags & FLC_PREVIEWS_ACTIVE);++ if (entry->preview_icon_id) {+ return false;+ }++ if (entry->typeflag & FILE_TYPE_ASSET_ONLINE) {+ /* Online assets use the UI system for async preview loading (see #PreviewLoadJob)+ * instead of the file browser one. */+ return false;+ }++ if (!filelist_file_preview_load_poll(entry)) {+ return false;+ }++ FileListInternEntry *intern_entry = filelist->filelist_intern.filtered[index];+ const PreviewImage *preview_in_memory = intern_entry->local_data.preview_image;+ if (preview_in_memory && !BKE_previewimg_is_finished(preview_in_memory, ICON_SIZE_PREVIEW)) {+ /* Nothing to set yet. Wait for next call. */+ return false;+ }++ filelist_cache_preview_ensure_running(cache);+ entry->flags |= FILE_ENTRY_PREVIEW_LOADING;++ FileListEntryPreview *preview = MEM_new_zeroed<FileListEntryPreview>(__func__);+ preview->index = index;+ preview->flags = entry->typeflag;+ preview->icon_id = 0;++ if (preview_in_memory) {+ /* TODO(mano-wii): No need to use the thread API here. */+ BLI_assert(!BKE_previewimg_is_rendering(preview_in_memory, ICON_SIZE_PREVIEW));+ preview->filepath[0] = '\0';+ ImBuf *imbuf = BKE_previewimg_to_imbuf(preview_in_memory, ICON_SIZE_PREVIEW);+ if (imbuf) {+ preview->icon_id = BKE_icon_imbuf_create(imbuf);+ }+ BLI_thread_queue_push(cache->previews_done, preview, BLI_THREAD_QUEUE_WORK_PRIORITY_NORMAL);+ }+ else {+ if (entry->redirection_path) {+ BLI_strncpy(preview->filepath, entry->redirection_path, FILE_MAXDIR);+ }+ else {+ filelist_file_get_full_path(filelist, entry, preview->filepath);+ }+ // printf("%s: %d - %s\n", __func__, preview->index, preview->filepath);++ FileListEntryPreviewTaskData *preview_taskdata = MEM_new_zeroed<FileListEntryPreviewTaskData>(+ __func__);+ preview_taskdata->preview = preview;+ BLI_task_pool_push(cache->previews_pool,+ filelist_cache_preview_runf,+ preview_taskdata,+ true,+ filelist_cache_preview_freef);+ }+ cache->previews_todo_count++;++ return true;+}++FileListEntryCache::FileListEntryCache() : size(FILELIST_ENTRYCACHESIZE_DEFAULT)+{+ block_entries = static_cast<FileDirEntry **>(+ MEM_new_uninitialized(sizeof(*this->block_entries) * this->size, __func__));++ this->misc_entries.reserve(this->size);+ this->misc_entries_indices = MEM_new_array_uninitialized<int>(this->size, __func__);+ std::fill_n(this->misc_entries_indices, this->size, -1);++ this->uids.reserve(this->size * 2);+}++FileListEntryCache::~FileListEntryCache()+{+ filelist_cache_previews_free(this);++ MEM_delete(this->block_entries);+ MEM_delete(this->misc_entries_indices);++ for (FileDirEntry &entry : this->cached_entries.items_mutable()) {+ filelist_entry_free(&entry);+ }+}++void filelist_cache_clear(FileListEntryCache *cache, size_t new_size)+{+ filelist_cache_previews_clear(cache);++ cache->block_cursor = cache->block_start_index = cache->block_center_index =+ cache->block_end_index = 0;+ if (new_size != cache->size) {+ cache->block_entries = static_cast<FileDirEntry **>(+ MEM_realloc_uninitialized(cache->block_entries, sizeof(*cache->block_entries) * new_size));+ }++ cache->misc_entries.clear();+ cache->misc_entries.reserve(new_size);+ if (new_size != cache->size) {+ cache->misc_entries_indices = static_cast<int *>(MEM_realloc_uninitialized(+ cache->misc_entries_indices, sizeof(*cache->misc_entries_indices) * new_size));+ }+ std::fill_n(cache->misc_entries_indices, new_size, -1);++ cache->uids.clear();+ cache->uids.reserve(new_size * 2);++ cache->size = new_size;++ for (FileDirEntry &entry : cache->cached_entries.items_mutable()) {+ filelist_entry_free(&entry);+ }+ cache->cached_entries.clear_no_delete();+}++FileList *filelist_new(short type, const bool is_from_global_asset_list)+{+ FileList *p = MEM_new<FileList>(__func__);++ p->filelist_cache = MEM_new<FileListEntryCache>("FileListEntryCache");++ p->selection_state = BLI_ghash_new(BLI_ghashutil_inthash_p, BLI_ghashutil_intcmp, __func__);+ p->filelist.entries_num = FILEDIR_NBR_ENTRIES_UNSET;+ filelist_settype(p, type);+ if (is_from_global_asset_list) {+ p->tags |= FILELIST_TAGS_FROM_GLOBAL_ASSET_LIST;+ }++ return p;+}++void filelist_settype(FileList *filelist, short type)+{+ if (filelist->type == type) {+ return;+ }++ filelist->type = eFileSelectType(type);+ filelist->tags = 0;+ filelist->indexer = &file_indexer_noop;+ filelist->check_dir_fn = nullptr;+ filelist->start_job_fn = nullptr;+ filelist->timer_step_fn = nullptr;+ filelist->read_job_fn = nullptr;+ filelist->prepare_filter_fn = nullptr;+ filelist->filter_fn = nullptr;++ switch (filelist->type) {+ case FILE_LOADLIB:+ filelist_set_readjob_library(filelist);+ break;+ case FILE_ASSET_LIBRARY:+ filelist_set_readjob_on_disk_asset_library(filelist);+ break;+ case FILE_MAIN_ASSET:+ filelist_set_readjob_current_file_asset_library(filelist);+ break;+ case FILE_ASSET_LIBRARY_REMOTE:+ filelist_set_readjob_remote_asset_library(filelist);+ break;+ case FILE_ASSET_LIBRARY_ESSENTIALS:+ filelist_set_readjob_essentials_asset_library(filelist);+ break;+ case FILE_ASSET_LIBRARY_ALL:+ filelist_set_readjob_all_asset_library(filelist);+ break;+ default:+ filelist_set_readjob_directories(filelist);+ break;+ }++ filelist->flags |= FL_FORCE_RESET;+}++static void filelist_clear_asset_library(FileList *filelist)+{+ /* The AssetLibraryService owns the AssetLibrary pointer, so no need for us to free it. */+ filelist->asset_library = nullptr;+ file_delete_asset_catalog_filter_settings(&filelist->filter_data.asset_catalog_filter);+}++void filelist_clear_ex(FileList *filelist,+ const bool do_asset_library,+ const bool do_cache,+ const bool do_selection)+{+ if (!filelist) {+ return;+ }++ filelist_tag_needs_filtering(filelist);++ if (do_cache) {+ filelist_cache_clear(filelist->filelist_cache, filelist->filelist_cache->size);+ }++ filelist_intern_free(filelist);++ filelist_direntryarr_free(&filelist->filelist);++ if (do_selection && filelist->selection_state) {+ BLI_ghash_clear(filelist->selection_state, nullptr, nullptr);+ }++ if (do_asset_library) {+ filelist_clear_asset_library(filelist);+ }+}++static void filelist_clear_main_files(FileList *filelist,+ const bool do_asset_library,+ const bool do_cache,+ const bool do_selection)+{+ if (!filelist || !(filelist->tags & FILELIST_TAGS_USES_MAIN_DATA)) {+ return;+ }+ if (filelist->filelist.entries_num == FILEDIR_NBR_ENTRIES_UNSET) {+ return;+ }+ const int removed_files = filelist_intern_free_main_files(filelist);+ /* File list contains no main files to clear. */+ if (removed_files == 0) {+ return;+ }++ filelist_tag_needs_filtering(filelist);++ if (do_cache) {+ filelist_cache_clear(filelist->filelist_cache, filelist->filelist_cache->size);+ }++ filelist->filelist.entries_num -= removed_files;+ filelist->filelist.entries_filtered_num = FILEDIR_NBR_ENTRIES_UNSET;+ BLI_assert(filelist->filelist.entries_num > FILEDIR_NBR_ENTRIES_UNSET);++ if (do_selection && filelist->selection_state) {+ BLI_ghash_clear(filelist->selection_state, nullptr, nullptr);+ }++ if (do_asset_library) {+ filelist_clear_asset_library(filelist);+ }+}++void filelist_clear(FileList *filelist)+{+ filelist_clear_ex(filelist, true, true, true);+}++void filelist_clear_from_reset_tag(FileList *filelist)+{+ /* Do a full clear if needed. */+ if (filelist->flags & FL_FORCE_RESET) {+ filelist_clear(filelist);+ return;+ }++ if (filelist->flags & FL_FORCE_RESET_MAIN_FILES) {+ filelist_clear_main_files(filelist, false, true, false);+ return;+ }+}++void filelist_free(FileList *filelist)+{+ if (!filelist) {+ printf("Attempting to delete empty filelist.\n");+ return;+ }++ /* No need to clear cache & selection_state, we free them anyway. */+ filelist_clear_ex(filelist, true, false, false);+ MEM_delete(filelist->filelist_cache);++ if (filelist->selection_state) {+ BLI_ghash_free(filelist->selection_state, nullptr, nullptr);+ filelist->selection_state = nullptr;+ }++ MEM_SAFE_DELETE(filelist->asset_library_ref);++ memset(&filelist->filter_data, 0, sizeof(filelist->filter_data));++ filelist->flags &= ~(FL_NEED_SORTING | FL_NEED_FILTERING);++ MEM_delete(filelist);+}++asset_system::AssetLibrary *filelist_asset_library(FileList *filelist)+{+ return filelist->asset_library;+}++void filelist_freelib(FileList *filelist)+{+ if (filelist->libfiledata) {+ BLO_blendhandle_close(filelist->libfiledata);+ }+ filelist->libfiledata = nullptr;+}++BlendHandle *filelist_lib(FileList *filelist)+{+ return filelist->libfiledata;+}++int filelist_files_num_entries(FileList *filelist)+{+ return filelist->filelist.entries_num;+}++const char *fileentry_uiname(const char *root, FileListInternEntry *entry, char *buff)+{+ if (asset_system::AssetRepresentation *asset = entry->get_asset()) {+ const StringRefNull asset_name = asset->get_name();+ return BLI_strdupn(asset_name.c_str(), asset_name.size());+ }++ const char *relpath = entry->relpath;+ const eFileSel_File_Types typeflag = entry->typeflag;+ char *name = nullptr;++ if (typeflag & FILE_TYPE_FTFONT && !(typeflag & FILE_TYPE_BLENDERLIB)) {+ if (entry->redirection_path) {+ name = BLF_display_name_from_file(entry->redirection_path);+ }+ else {+ char abspath[FILE_MAX_LIBEXTRA];+ BLI_path_join(abspath, root, relpath);+ name = BLF_display_name_from_file(abspath);+ }+ if (name) {+ /* Allocated string, so no need to #BLI_strdup. */+ return name;+ }+ }++ if (typeflag & FILE_TYPE_BLENDERLIB) {+ char abspath[FILE_MAX_LIBEXTRA];+ char *group;++ BLI_path_join(abspath, root, relpath);+ BKE_blendfile_library_path_explode(abspath, buff, &group, &name);+ if (!name) {+ name = group;+ }+ }+ /* Depending on platforms, 'my_file.blend/..' might be viewed as dir or not... */+ if (!name) {+ if (typeflag & FILE_TYPE_DIR) {+ name = const_cast<char *>(relpath);+ }+ else {+ name = const_cast<char *>(BLI_path_basename(relpath));+ }+ }+ BLI_assert(name);++ return BLI_strdup(name);+}++const char *filelist_dir(const FileList *filelist)+{+ return filelist->filelist.root;+}++bool filelist_is_dir(const FileList *filelist, const char *path)+{+ return filelist->check_dir_fn(filelist, const_cast<char *>(path), false);+}++void filelist_setdir(FileList *filelist, char dirpath[FILE_MAX_LIBEXTRA])+{+ const bool allow_invalid = filelist->asset_library_ref != nullptr;+ BLI_assert(strlen(dirpath) < FILE_MAX_LIBEXTRA);++ BLI_path_abs(dirpath, BKE_main_blendfile_path_from_global());+ BLI_path_normalize_dir(MutableCStr(dirpath, FILE_MAX_LIBEXTRA));+ const bool is_valid_path = filelist->check_dir_fn(filelist, dirpath, !allow_invalid);+ BLI_assert(is_valid_path || allow_invalid);+ UNUSED_VARS_NDEBUG(is_valid_path);++ if (!STREQ(filelist->filelist.root, dirpath)) {+ STRNCPY(filelist->filelist.root, dirpath);+ filelist->flags |= FL_FORCE_RESET;+ }+}++void filelist_setrecursion(FileList *filelist, const int recursion_level)+{+ if (filelist->max_recursion != recursion_level) {+ filelist->max_recursion = recursion_level;+ filelist->flags |= FL_FORCE_RESET;+ }+}++void filelist_entry_glob_tag(FileListInternEntry *entry, const char *filter_glob)+{+ entry->typeflag &= ~FILE_TYPE_OPERATOR;++ if (entry->typeflag & (FILE_TYPE_DIR | FILE_TYPE_BLENDERLIB)) {+ return;+ }+ if (filter_glob[0] == '\0') {+ return;+ }++ /* Aliases & shortcuts match their target, its extension may differ from the link. */+ const char *path = entry->redirection_path ? entry->redirection_path : entry->relpath;+ if (BLI_path_extension_check_glob(path, filter_glob)) {+ entry->typeflag |= FILE_TYPE_OPERATOR;+ }+}++void filelist_reset_glob(FileList *filelist)+{+ for (FileListInternEntry &entry : filelist->filelist_intern.entries) {+ filelist_entry_glob_tag(&entry, filelist->filter_glob);+ }++ filelist->flags &= ~FL_NEED_RESET_GLOB;+}++void filelist_setglob(FileList *filelist, const char *filter_glob)+{+ /* The glob is stored in #FileListInternEntry.typeflag, so filtering again isn't enough.+ * Re-tag the entries, reading the directory again would be needlessly heavy. */++ if (!STREQ(filelist->filter_glob, filter_glob)) {+ STRNCPY(filelist->filter_glob, filter_glob);+ filelist->flags |= FL_NEED_RESET_GLOB;+ filelist_tag_needs_filtering(filelist);+ }+}++bool filelist_needs_force_reset(const FileList *filelist)+{+ return (filelist->flags & (FL_FORCE_RESET | FL_FORCE_RESET_MAIN_FILES)) != 0;+}++void filelist_tag_force_reset(FileList *filelist)+{+ filelist->flags |= FL_FORCE_RESET;+}++void filelist_tag_force_reset_mainfiles(FileList *filelist)+{+ if (!(filelist->tags & FILELIST_TAGS_USES_MAIN_DATA)) {+ return;+ }+ filelist->flags |= FL_FORCE_RESET_MAIN_FILES;+}++void filelist_tag_reload_asset_library(FileList *filelist)+{+ filelist->flags |= FL_RELOAD_ASSET_LIBRARY;+}++bool filelist_is_ready(const FileList *filelist)+{+ return (filelist->flags & FL_IS_READY) != 0;+}++bool filelist_pending(const FileList *filelist)+{+ return (filelist->flags & FL_IS_PENDING) != 0;+}++bool filelist_needs_reset_on_main_changes(const FileList *filelist)+{+ return (filelist->tags & FILELIST_TAGS_USES_MAIN_DATA) != 0;+}++int filelist_files_ensure(FileList *filelist)+{+ if (!filelist_needs_force_reset(filelist) || !filelist_needs_reading(filelist)) {+ filelist_sort(filelist);+ filelist_filter(filelist);+ }++ return filelist->filelist.entries_filtered_num;+}++static FileDirEntry *filelist_file_create_entry(FileList *filelist, const int index)+{+ FileListInternEntry *entry = filelist->filelist_intern.filtered[index];+ FileListEntryCache *cache = filelist->filelist_cache;+ FileDirEntry *ret;++ ret = MEM_new<FileDirEntry>(__func__);++ ret->size = uint64_t(entry->st.st_size);+ ret->time = int64_t(entry->st.st_mtime);++ ret->relpath = BLI_strdup(entry->relpath);+ if (entry->free_name) {+ ret->name = BLI_strdup(entry->name);+ ret->flags |= FILE_ENTRY_NAME_FREE;+ }+ else {+ ret->name = entry->name;+ }+ ret->uid = entry->uid;+ ret->blentype = entry->blentype;+ ret->typeflag = entry->typeflag;+ ret->attributes = entry->attributes;+ if (entry->redirection_path) {+ ret->redirection_path = BLI_strdup(entry->redirection_path);+ }+ ret->id = entry->local_data.id;+ ret->asset = entry->get_asset();+ /* For some file types the preview is already available. */+ if (entry->local_data.preview_image &&+ BKE_previewimg_is_finished(entry->local_data.preview_image, ICON_SIZE_PREVIEW))+ {+ ImBuf *ibuf = BKE_previewimg_to_imbuf(entry->local_data.preview_image, ICON_SIZE_PREVIEW);+ if (ibuf) {+ ret->preview_icon_id = BKE_icon_imbuf_create(ibuf);+ }+ }+ if (entry->blenderlib_has_no_preview) {+ ret->flags |= FILE_ENTRY_BLENDERLIB_NO_PREVIEW;+ }+ BLI_addtail(&cache->cached_entries, ret);+ return ret;+}++static void filelist_file_release_entry(FileList *filelist, FileDirEntry *entry)+{+ BLI_remlink(&filelist->filelist_cache->cached_entries, entry);+ filelist_entry_free(entry);+}++static FileDirEntry *filelist_cache_file_lookup(FileListEntryCache *cache, const int index)+{+ /* If the file is cached, we can get it from either the block or the misc entry storage. */++ if (index >= cache->block_start_index && index < cache->block_end_index) {+ const int idx = (index - cache->block_start_index + cache->block_cursor) % cache->size;+ return cache->block_entries[idx];+ }++ return cache->misc_entries.lookup_default(index, nullptr);+}++FileDirEntry *filelist_file_ex(FileList *filelist, const int index, const bool use_request)+{+ FileDirEntry *ret = nullptr;+ FileListEntryCache *cache = filelist->filelist_cache;+ int old_index;++ if ((index < 0) || (index >= filelist->filelist.entries_filtered_num)) {+ return ret;+ }++ if ((ret = filelist_cache_file_lookup(cache, index))) {+ return ret;+ }++ if (!use_request) {+ return nullptr;+ }++ // printf("requesting file %d (not yet cached)\n", index);++ /* Else, we have to add new entry to 'misc' cache - and possibly make room for it first! */+ ret = filelist_file_create_entry(filelist, index);+ old_index = cache->misc_entries_indices[cache->misc_cursor];+ if (FileDirEntry *old = cache->misc_entries.pop_default(old_index, nullptr)) {+ cache->uids.remove(old->uid);+ filelist_file_release_entry(filelist, old);+ }+ cache->misc_entries.add(index, ret);+ cache->uids.add(ret->uid, ret);++ cache->misc_entries_indices[cache->misc_cursor] = index;+ cache->misc_cursor = (cache->misc_cursor + 1) % cache->size;++#if 0 /* Actually no, only block cached entries should have preview IMHO. */+ if (cache->previews_pool) {+ filelist_cache_previews_push(filelist, ret, index);+ }+#endif++ return ret;+}++FileDirEntry *filelist_file(FileList *filelist, int index)+{+ return filelist_file_ex(filelist, index, true);+}++int filelist_file_find_path(FileList *filelist, const char *filename)+{+ if (filelist->filelist.entries_filtered_num == FILEDIR_NBR_ENTRIES_UNSET) {+ return -1;+ }++ /* XXX TODO: Cache could probably use a ghash on paths too? Not really urgent though.+ * This is only used to find again renamed entry,+ * annoying but looks hairy to get rid of it currently. */++ for (int fidx = 0; fidx < filelist->filelist.entries_filtered_num; fidx++) {+ FileListInternEntry *entry = filelist->filelist_intern.filtered[fidx];+ if (STREQ(entry->relpath, filename)) {+ return fidx;+ }+ }++ return -1;+}++int filelist_file_find_id(const FileList *filelist, const ID *id)+{+ if (filelist->filelist.entries_filtered_num == FILEDIR_NBR_ENTRIES_UNSET) {+ return -1;+ }++ for (int fidx = 0; fidx < filelist->filelist.entries_filtered_num; fidx++) {+ FileListInternEntry *entry = filelist->filelist_intern.filtered[fidx];+ if (entry->local_data.id == id) {+ return fidx;+ }+ }++ return -1;+}++static FileListInternEntry *filelist_entry_intern_get(const FileList *filelist, const int index)+{+ BLI_assert(index >= 0 && index < filelist->filelist.entries_filtered_num);+ return filelist->filelist_intern.filtered[index];+}++ID *filelist_entry_get_id(const FileList *filelist, const int index)+{+ const FileListInternEntry *intern_entry = filelist_entry_intern_get(filelist, index);+ return intern_entry->local_data.id;+}++asset_system::AssetRepresentation *filelist_entry_get_asset_representation(+ const FileList *filelist, const int index)+{+ const FileListInternEntry *intern_entry = filelist_entry_intern_get(filelist, index);+ return intern_entry->get_asset();+}++ID *filelist_file_get_id(const FileDirEntry *file)+{+ return file->id;+}++const char *filelist_entry_get_relpath(const FileList *filelist, int index)+{+ const FileListInternEntry *intern_entry = filelist_entry_intern_get(filelist, index);+ return intern_entry->relpath;+}++#define FILE_UID_UNSET 0++FileUID filelist_uid_generate(FileList *filelist)+{+ /* Using an atomic operation to avoid having to lock thread...+ * Note that we do not really need this here currently, since there is a single listing thread,+ * but better remain consistent about threading! */+ return atomic_add_and_fetch_uint32(&filelist->filelist_intern.curr_uid, 1);+}++bool filelist_uid_is_set(const FileUID uid)+{+ FileUID unset_uid;+ filelist_uid_unset(&unset_uid);+ return unset_uid != uid;+}++void filelist_uid_unset(FileUID *r_uid)+{+ *r_uid = FILE_UID_UNSET;+}++void filelist_file_cache_slidingwindow_set(FileList *filelist, size_t window_size)+{+ /* Always keep it power of 2, in [256, 8192] range for now,+ * cache being app. twice bigger than requested window. */+ size_t size = 256;+ window_size *= 2;++ while (size < window_size && size < 8192) {+ size *= 2;+ }++ if (size != filelist->filelist_cache->size) {+ filelist_cache_clear(filelist->filelist_cache, size);+ }+}++/* Helpers, low-level, they assume cursor + size <= cache_size */+static bool filelist_file_cache_block_create(FileList *filelist,+ const int start_index,+ const int size,+ int cursor)+{+ FileListEntryCache *cache = filelist->filelist_cache;++ int i, idx;++ for (i = 0, idx = start_index; i < size; i++, idx++, cursor++) {+ FileDirEntry *entry;++ /* That entry might have already been requested and stored in misc cache... */+ if ((entry = cache->misc_entries.pop_default(idx, nullptr)) == nullptr) {+ entry = filelist_file_create_entry(filelist, idx);+ cache->uids.add(entry->uid, entry);+ }+ cache->block_entries[cursor] = entry;+ }+ return true;+}++static void filelist_file_cache_block_release(FileList *filelist, const int size, int cursor)+{+ FileListEntryCache *cache = filelist->filelist_cache;++ int i;++ for (i = 0; i < size; i++, cursor++) {+ FileDirEntry *entry = cache->block_entries[cursor];+#if 0+ printf("%s: release cacheidx %d (%%p %%s)\n",+ __func__,+ cursor /*, cache->block_entries[cursor], cache->block_entries[cursor]->relpath*/);+#endif+ cache->uids.remove(entry->uid);+ filelist_file_release_entry(filelist, entry);+#ifndef NDEBUG+ cache->block_entries[cursor] = nullptr;+#endif+ }+}++bool filelist_file_cache_block(FileList *filelist, const int index)+{+ FileListEntryCache *cache = filelist->filelist_cache;+ const size_t cache_size = cache->size;++ const int entries_num = filelist->filelist.entries_filtered_num;+ int start_index = max_ii(0, index - (cache_size / 2));+ int end_index = min_ii(entries_num, index + (cache_size / 2));+ int i;+ const bool full_refresh = (filelist->flags & FL_IS_READY) == 0;++ if ((index < 0) || (index >= entries_num)) {+ // printf("Wrong index %d ([%d:%d])", index, 0, entries_num);+ return false;+ }++ /* Maximize cached range! */+ if ((end_index - start_index) < cache_size) {+ if (start_index == 0) {+ end_index = min_ii(entries_num, start_index + cache_size);+ }+ else if (end_index == entries_num) {+ start_index = max_ii(0, end_index - cache_size);+ }+ }++ BLI_assert((end_index - start_index) <= cache_size);++ // printf("%s: [%d:%d] around index %d (current cache: [%d:%d])\n", __func__,+ // start_index, end_index, index, cache->block_start_index, cache->block_end_index);++ /* If we have something to (re)cache... */+ if (full_refresh || (start_index != cache->block_start_index) ||+ (end_index != cache->block_end_index))+ {+ if (full_refresh || (start_index >= cache->block_end_index) ||+ (end_index <= cache->block_start_index))+ {+ int size1 = cache->block_end_index - cache->block_start_index;+ int size2 = 0;+ int idx1 = cache->block_cursor, idx2 = 0;++ // printf("Full Recaching!\n");++ if (cache->flags & FLC_PREVIEWS_ACTIVE) {+ filelist_cache_previews_clear(cache);+ }++ if (idx1 + size1 > cache_size) {+ size2 = idx1 + size1 - cache_size;+ size1 -= size2;+ filelist_file_cache_block_release(filelist, size2, idx2);+ }+ filelist_file_cache_block_release(filelist, size1, idx1);++ cache->block_start_index = cache->block_end_index = cache->block_cursor = 0;++ /* New cached block does not overlap existing one, simple. */+ if (!filelist_file_cache_block_create(filelist, start_index, end_index - start_index, 0)) {+ return false;+ }++ cache->block_start_index = start_index;+ cache->block_end_index = end_index;+ }+ else {+ // printf("Partial Recaching!\n");++ /* At this point, we know we keep part of currently cached entries, so update previews+ * if needed, and remove everything from working queue - we'll add all newly needed+ * entries at the end. */+ if (cache->flags & FLC_PREVIEWS_ACTIVE) {+ filelist_cache_previews_update(filelist);+ filelist_cache_previews_clear(cache);+ }++ // printf("\tpreview cleaned up...\n");++ if (start_index > cache->block_start_index) {+ int size1 = start_index - cache->block_start_index;+ int size2 = 0;+ int idx1 = cache->block_cursor, idx2 = 0;++ // printf("\tcache releasing: [%d:%d] (%d, %d)\n",+ // cache->block_start_index, cache->block_start_index + size1,+ // cache->block_cursor, size1);++ if (idx1 + size1 > cache_size) {+ size2 = idx1 + size1 - cache_size;+ size1 -= size2;+ filelist_file_cache_block_release(filelist, size2, idx2);+ }+ filelist_file_cache_block_release(filelist, size1, idx1);++ cache->block_cursor = (idx1 + size1 + size2) % cache_size;+ cache->block_start_index = start_index;+ }+ if (end_index < cache->block_end_index) {+ int size1 = cache->block_end_index - end_index;+ int size2 = 0;+ int idx1, idx2 = 0;++#if 0+ printf("\tcache releasing: [%d:%d] (%d)\n",+ cache->block_end_index - size1,+ cache->block_end_index,+ cache->block_cursor);+#endif++ idx1 = (cache->block_cursor + end_index - cache->block_start_index) % cache_size;+ if (idx1 + size1 > cache_size) {+ size2 = idx1 + size1 - cache_size;+ size1 -= size2;+ filelist_file_cache_block_release(filelist, size2, idx2);+ }+ filelist_file_cache_block_release(filelist, size1, idx1);++ cache->block_end_index = end_index;+ }++ // printf("\tcache cleaned up...\n");++ if (start_index < cache->block_start_index) {+ /* Add (request) needed entries before already cached ones. */+ /* NOTE: We need some index black magic to wrap around (cycle)+ * inside our cache_size array... */+ int size1 = cache->block_start_index - start_index;+ int size2 = 0;+ int idx1, idx2;++ if (size1 > cache->block_cursor) {+ size2 = size1;+ size1 -= cache->block_cursor;+ size2 -= size1;+ idx2 = 0;+ idx1 = cache_size - size1;+ }+ else {+ idx1 = cache->block_cursor - size1;+ }++ if (size2) {+ if (!filelist_file_cache_block_create(filelist, start_index + size1, size2, idx2)) {+ return false;+ }+ }+ if (!filelist_file_cache_block_create(filelist, start_index, size1, idx1)) {+ return false;+ }++ cache->block_cursor = idx1;+ cache->block_start_index = start_index;+ }+ // printf("\tstart-extended...\n");+ if (end_index > cache->block_end_index) {+ /* Add (request) needed entries after already cached ones. */+ /* NOTE: We need some index black magic to wrap around (cycle)+ * inside our cache_size array... */+ int size1 = end_index - cache->block_end_index;+ int size2 = 0;+ int idx1, idx2;++ idx1 = (cache->block_cursor + end_index - cache->block_start_index - size1) % cache_size;+ if ((idx1 + size1) > cache_size) {+ size2 = size1;+ size1 = cache_size - idx1;+ size2 -= size1;+ idx2 = 0;+ }++ if (size2) {+ if (!filelist_file_cache_block_create(filelist, end_index - size2, size2, idx2)) {+ return false;+ }+ }+ if (!filelist_file_cache_block_create(filelist, end_index - size1 - size2, size1, idx1)) {+ return false;+ }++ cache->block_end_index = end_index;+ }++ // printf("\tend-extended...\n");+ }+ }+ else if ((cache->block_center_index != index) && (cache->flags & FLC_PREVIEWS_ACTIVE)) {+ /* We try to always preview visible entries first, so 'restart' preview background task. */+ filelist_cache_previews_update(filelist);+ filelist_cache_previews_clear(cache);+ }++ // printf("Re-queueing previews...\n");++ if (cache->flags & FLC_PREVIEWS_ACTIVE) {+ /* Note we try to preview first images around given index - i.e. assumed visible ones. */+ int block_index = cache->block_cursor + (index - start_index);+ int offs_max = max_ii(end_index - index, index - start_index);+ for (i = 0; i <= offs_max; i++) {+ int offs = i;+ do {+ int offs_idx = index + offs;+ if (start_index <= offs_idx && offs_idx < end_index) {+ int offs_block_idx = (block_index + offs) % int(cache_size);+ filelist_cache_previews_push(filelist, cache->block_entries[offs_block_idx], offs_idx);+ }+ } while ((offs = -offs) < 0); /* Switch between negative and positive offset. */+ }+ }++ cache->block_center_index = index;++ // printf("%s Finished!\n", __func__);++ return true;+}++void filelist_cache_previews_set(FileList *filelist, const bool use_previews)+{+ FileListEntryCache *cache = filelist->filelist_cache;++ if (use_previews == ((cache->flags & FLC_PREVIEWS_ACTIVE) != 0)) {+ return;+ }+ /* Do not start preview work while listing, gives nasty flickering! */+ if (use_previews && (filelist->flags & FL_IS_READY)) {+ cache->flags |= FLC_PREVIEWS_ACTIVE;++ BLI_assert((cache->previews_pool == nullptr) && (cache->previews_done == nullptr) &&+ (cache->previews_todo_count == 0));++ // printf("%s: Init Previews...\n", __func__);++ /* No need to populate preview queue here, filelist_file_cache_block() handles this. */+ }+ else {+ // printf("%s: Clear Previews...\n", __func__);++ filelist_cache_previews_free(cache);+ }+}++bool filelist_cache_previews_update(FileList *filelist)+{+ FileListEntryCache *cache = filelist->filelist_cache;+ TaskPool *pool = cache->previews_pool;+ bool changed = false;++ if (!pool) {+ return changed;+ }++ // printf("%s: Update Previews...\n", __func__);++ while (!BLI_thread_queue_is_empty(cache->previews_done)) {+ FileListEntryPreview *preview = static_cast<FileListEntryPreview *>(+ BLI_thread_queue_pop(cache->previews_done));+ FileDirEntry *entry;++ /* Paranoid (should never happen currently+ * since we consume this queue from a single thread), but... */+ if (!preview) {+ BLI_assert_unreachable();+ continue;+ }+ /* entry might have been removed from cache in the mean time,+ * we do not want to cache it again here. */+ entry = filelist_file_ex(filelist, preview->index, false);++ BLI_assert_msg((entry->typeflag & FILE_TYPE_ASSET_ONLINE) == 0,+ "Online assets shouldn't use the file preview loading system");++ // printf("%s: %d - %s - %p\n", __func__, preview->index, preview->filepath, preview->img);++ if (entry) {+ if (preview->icon_id) {+ /* The FILE_ENTRY_PREVIEW_LOADING flag should have prevented any other asynchronous+ * process from trying to generate the same preview icon. */+ BLI_assert_msg(!entry->preview_icon_id, "Preview icon should not have been generated yet");++ /* Move ownership over icon. */+ entry->preview_icon_id = preview->icon_id;+ preview->icon_id = 0;+ }+ else {+ /* We want to avoid re-processing this entry continuously!+ * Note that, since entries only live in cache,+ * preview will be retried quite often anyway. */+ entry->flags |= FILE_ENTRY_INVALID_PREVIEW;+ }+ entry->flags &= ~FILE_ENTRY_PREVIEW_LOADING;+ changed = true;+ }+ else {+ BKE_icon_delete(preview->icon_id);+ }++ MEM_delete(preview);+ cache->previews_todo_count--;+ }++ return changed;+}++bool filelist_cache_previews_running(FileList *filelist)+{+ FileListEntryCache *cache = filelist->filelist_cache;++ return (cache->previews_pool != nullptr);+}++bool filelist_cache_previews_done(FileList *filelist)+{+ FileListEntryCache *cache = filelist->filelist_cache;+ if ((cache->flags & FLC_PREVIEWS_ACTIVE) == 0) {+ /* There are no previews. */+ return false;+ }++ return (cache->previews_pool == nullptr) || (cache->previews_done == nullptr) ||+ (cache->previews_todo_count == 0);+}++/* would recognize .blend as well */+static bool file_is_blend_backup(const char *str)+{+ const size_t a = strlen(str);+ size_t b = 7;+ bool retval = false;++ if (a == 0 || b >= a) {+ /* pass */+ }+ else {+ const char *loc;++ if (a > b + 1) {+ b++;+ }++ /* allow .blend1 .blend2 .blend32 */+ loc = BLI_strcasestr(str + a - b, ".blend");++ if (loc) {+ retval = true;+ }+ }++ return retval;+}++int ED_path_extension_type(const char *path)+{+ /* ATTENTION: Never return OR'ed bit-flags here, always return a single enum value! Some code+ * using this may do `ELEM()`-like checks. */++ if (BKE_blendfile_extension_check(path)) {+ return FILE_TYPE_BLENDER;+ }+ if (file_is_blend_backup(path)) {+ return FILE_TYPE_BLENDER_BACKUP;+ }+#ifdef __APPLE__+ if (BLI_path_extension_check_n(path,+ /* Application bundle */+ ".app",+ /* Safari in-progress/paused download */+ ".download",+ nullptr))+ {+ return FILE_TYPE_BUNDLE;+ }+#endif+ if (BLI_path_extension_check(path, ".py")) {+ return FILE_TYPE_PYSCRIPT;+ }+ if (BLI_path_extension_check_n(path,+ ".txt",+ ".glsl",+ ".osl",+ ".data",+ ".pov",+ ".ini",+ ".mcr",+ ".inc",+ ".fountain",+ ".toml",+ nullptr))+ {+ return FILE_TYPE_TEXT;+ }++ /* NOTE: While `.ttc` & `.otc` files can be loaded, only a single "face" is supported,+ * users will have to extract bold/italic etc manually for Blender to use them, see #44254. */+ if (BLI_path_extension_check_n(path, ".ttf", ".pfb", ".otf", ".woff", ".woff2", nullptr)) {+ return FILE_TYPE_FTFONT;+ }+ if (BLI_path_extension_check(path, ".btx")) {+ return FILE_TYPE_BTX;+ }+ if (BLI_path_extension_check(path, ".abc")) {+ return FILE_TYPE_ALEMBIC;+ }+ if (BLI_path_extension_check_n(path, ".usd", ".usda", ".usdc", ".usdz", nullptr)) {+ return FILE_TYPE_USD;+ }+ if (BLI_path_extension_check(path, ".vdb")) {+ return FILE_TYPE_VOLUME;+ }+ if (BLI_path_extension_check(path, ".zip")) {+ return FILE_TYPE_ARCHIVE;+ }+ if (BLI_path_extension_check_n(path,+ ".obj",+ ".mtl",+ ".3ds",+ ".fbx",+ ".glb",+ ".gltf",+ ".svg",+ ".pdf",+ ".ply",+ ".stl",+ nullptr))+ {+ return FILE_TYPE_OBJECT_IO;+ }+ if (BLI_path_extension_check_array(path, imb_ext_image)) {+ return FILE_TYPE_IMAGE;+ }+ if (BLI_path_extension_check(path, ".ogg")) {+ if (MOV_is_movie_file(path)) {+ return FILE_TYPE_MOVIE;+ }+ return FILE_TYPE_SOUND;+ }+ if (BLI_path_extension_check_array(path, imb_ext_movie)) {+ return FILE_TYPE_MOVIE;+ }+ if (BLI_path_extension_check_array(path, imb_ext_audio)) {+ return FILE_TYPE_SOUND;+ }+ return 0;+}++int ED_file_extension_icon(const char *path)+{+ const int type = ED_path_extension_type(path);++ switch (type) {+ case FILE_TYPE_BLENDER:+ return ICON_FILE_BLEND;+ case FILE_TYPE_BLENDER_BACKUP:+ return ICON_FILE_BACKUP;+ case FILE_TYPE_IMAGE:+ return ICON_FILE_IMAGE;+ case FILE_TYPE_MOVIE:+ return ICON_FILE_MOVIE;+ case FILE_TYPE_PYSCRIPT:+ return ICON_FILE_SCRIPT;+ case FILE_TYPE_SOUND:+ return ICON_FILE_SOUND;+ case FILE_TYPE_FTFONT:+ return ICON_FILE_FONT;+ case FILE_TYPE_BTX:+ return ICON_FILE_BLANK;+ case FILE_TYPE_ALEMBIC:+ case FILE_TYPE_OBJECT_IO:+ return ICON_FILE_3D;+ case FILE_TYPE_TEXT:+ return ICON_FILE_TEXT;+ case FILE_TYPE_ARCHIVE:+ return ICON_FILE_ARCHIVE;+ case FILE_TYPE_VOLUME:+ return ICON_FILE_VOLUME;+ default:+ return ICON_FILE_BLANK;+ }+}++int filelist_needs_reading(const FileList *filelist)+{+ return (filelist->filelist.entries_num == FILEDIR_NBR_ENTRIES_UNSET) ||+ filelist_needs_force_reset(filelist);+}++uint filelist_entry_select_set(const FileList *filelist,+ const FileDirEntry *entry,+ FileSelType select,+ const eDirEntry_SelectFlag flag,+ FileCheckType check)+{+ /* Default nullptr pointer if not found is fine here! */+ void **es_p = BLI_ghash_lookup_p(filelist->selection_state, POINTER_FROM_UINT(entry->uid));+ eDirEntry_SelectFlag entry_flag = eDirEntry_SelectFlag(es_p ? POINTER_AS_UINT(*es_p) : 0);+ const eDirEntry_SelectFlag org_entry_flag = entry_flag;++ BLI_assert(entry);+ BLI_assert(ELEM(check, CHECK_DIRS, CHECK_FILES, CHECK_ALL));++ if ((check == CHECK_ALL) || ((check == CHECK_DIRS) && (entry->typeflag & FILE_TYPE_DIR)) ||+ ((check == CHECK_FILES) && !(entry->typeflag & FILE_TYPE_DIR)))+ {+ switch (select) {+ case FILE_SEL_REMOVE:+ entry_flag &= ~flag;+ break;+ case FILE_SEL_ADD:+ entry_flag |= flag;+ break;+ case FILE_SEL_TOGGLE:+ entry_flag ^= flag;+ break;+ }+ }++ if (entry_flag != org_entry_flag) {+ if (es_p) {+ if (entry_flag) {+ *es_p = POINTER_FROM_UINT(entry_flag);+ }+ else {+ BLI_ghash_remove(+ filelist->selection_state, POINTER_FROM_UINT(entry->uid), nullptr, nullptr);+ }+ }+ else if (entry_flag) {+ BLI_ghash_insert(+ filelist->selection_state, POINTER_FROM_UINT(entry->uid), POINTER_FROM_UINT(entry_flag));+ }+ }++ return entry_flag;+}++void filelist_entry_select_index_set(FileList *filelist,+ const int index,+ FileSelType select,+ const eDirEntry_SelectFlag flag,+ FileCheckType check)+{+ FileDirEntry *entry = filelist_file(filelist, index);++ if (entry) {+ filelist_entry_select_set(filelist, entry, select, flag, check);+ }+}++void filelist_entries_select_index_range_set(FileList *filelist,+ FileSelection *sel,+ FileSelType select,+ const eDirEntry_SelectFlag flag,+ FileCheckType check)+{+ /* select all valid files between first and last indicated */+ if ((sel->first >= 0) && (sel->first < filelist->filelist.entries_filtered_num) &&+ (sel->last >= 0) && (sel->last < filelist->filelist.entries_filtered_num))+ {+ int current_file;+ for (current_file = sel->first; current_file <= sel->last; current_file++) {+ filelist_entry_select_index_set(filelist, current_file, select, flag, check);+ }+ }+}++eDirEntry_SelectFlag filelist_entry_select_get(FileList *filelist,+ FileDirEntry *entry,+ FileCheckType check)+{+ BLI_assert(entry);+ BLI_assert(ELEM(check, CHECK_DIRS, CHECK_FILES, CHECK_ALL));++ if ((check == CHECK_ALL) || ((check == CHECK_DIRS) && (entry->typeflag & FILE_TYPE_DIR)) ||+ ((check == CHECK_FILES) && !(entry->typeflag & FILE_TYPE_DIR)))+ {+ /* Default nullptr pointer if not found is fine here! */+ return eDirEntry_SelectFlag(POINTER_AS_UINT(+ BLI_ghash_lookup(filelist->selection_state, POINTER_FROM_UINT(entry->uid))));+ }++ return eDirEntry_SelectFlag(0);+}++eDirEntry_SelectFlag filelist_entry_select_index_get(FileList *filelist,+ const int index,+ FileCheckType check)+{+ FileDirEntry *entry = filelist_file(filelist, index);++ if (entry) {+ return filelist_entry_select_get(filelist, entry, check);+ }++ return eDirEntry_SelectFlag(0);+}++bool filelist_entry_is_selected(FileList *filelist, const int index)+{+ BLI_assert(index >= 0 && index < filelist->filelist.entries_filtered_num);+ FileListInternEntry *intern_entry = filelist->filelist_intern.filtered[index];++ /* BLI_ghash_lookup returns nullptr if not found, which gets mapped to 0, which gets mapped to+ * "not selected". */+ const eDirEntry_SelectFlag selection_state = eDirEntry_SelectFlag(POINTER_AS_UINT(+ BLI_ghash_lookup(filelist->selection_state, POINTER_FROM_UINT(intern_entry->uid))));++ return selection_state != 0;+}++void filelist_entry_parent_select_set(FileList *filelist,+ FileSelType select,+ const eDirEntry_SelectFlag flag,+ FileCheckType check)+{+ if ((filelist->filter_data.flags & FLF_HIDE_PARENT) == 0) {+ filelist_entry_select_index_set(filelist, 0, select, flag, check);+ }+}++bool filelist_islibrary(FileList *filelist, char *dir, char **r_group)+{+ if (filelist->asset_library) {+ return true;+ }+ return BKE_blendfile_library_path_explode(filelist->filelist.root, dir, r_group, nullptr);+}++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_filter.cc b/ui/space_file/filelist/filelist_filter.ccnew file mode 100644index 0000000..2b5e34a--- /dev/null+++ b/ui/space_file/filelist/filelist_filter.cc@@ -0,0 +1,438 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "AS_asset_representation.hh"+#include "AS_essentials_library.hh"++#include "BLI_fnmatch.h"+#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_string_search.hh"+#include "BLI_string_utf8.h"+#include "BLI_uuid.h"+#include "BLI_vector.hh"++#include "BKE_idtype.hh"++#include "../file_intern.hh"+#include "../filelist.hh"+#include "filelist_intern.hh"++namespace blender {++/* True if should be hidden, based on current filtering. */+static bool is_filtered_hidden(const char *filename,+ const FileListFilter *filter,+ const FileListInternEntry *file)+{+ if ((filename[0] == '.') && (filename[1] == '\0')) {+ return true; /* Ignore. */+ }++ if (filter->flags & FLF_HIDE_PARENT) {+ if (filename[0] == '.' && filename[1] == '.' && filename[2] == '\0') {+ return true; /* Ignore. */+ }+ }++ /* Check for _OUR_ "hidden" attribute. This not only mirrors OS-level hidden file+ * attribute but is also set for Linux/Mac "dot" files. See `filelist_readjob_list_dir`.+ */+ if ((filter->flags & FLF_HIDE_DOT) && (file->attributes & FILE_ATTR_HIDDEN)) {+ return true;+ }++ /* For data-blocks (but not the group directories), check the asset-only filter. */+ if (!(file->typeflag & FILE_TYPE_DIR) && (file->typeflag & FILE_TYPE_BLENDERLIB) &&+ (filter->flags & FLF_ASSETS_ONLY) && !(file->typeflag & FILE_TYPE_ASSET))+ {+ return true;+ }++ return false;+}++/**+ * Apply the filter string as file path matching pattern.+ * \return true when the file should be in the result set, false if it should be filtered out.+ */+static bool is_filtered_file_relpath(const FileListInternEntry *file, const FileListFilter *filter)+{+ if (filter->filter_search[0] == '\0') {+ return true;+ }++ /* If there's a filter string, apply it as filter even if FLF_DO_FILTER is not set. */+ return fnmatch(filter->filter_search, file->relpath, FNM_CASEFOLD) == 0;+}++/**+ * Apply the filter string as matching pattern on file name.+ * \return true when the file should be in the result set, false if it should be filtered out.+ */+static bool is_filtered_file_name(const FileListInternEntry *file, const FileListFilter *filter)+{+ if (filter->filter_search[0] == '\0') {+ return true;+ }++ /* If there's a filter string, apply it as filter even if FLF_DO_FILTER is not set. */+ return fnmatch(filter->filter_search, file->name, FNM_CASEFOLD) == 0;+}++/** \return true when the file should be in the result set, false if it should be filtered out. */+static bool is_filtered_file_type(const FileListInternEntry *file, const FileListFilter *filter)+{+ if (is_filtered_hidden(file->relpath, filter, file)) {+ return false;+ }++ if (FILENAME_IS_CURRPAR(file->relpath)) {+ return false;+ }++ /* We only check for types if some type are enabled in filtering. */+ if (filter->filter && (filter->flags & FLF_DO_FILTER)) {+ if (file->typeflag & FILE_TYPE_DIR) {+ if (file->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {+ if (!(filter->filter & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {+ return false;+ }+ }+ else {+ if (!(filter->filter & FILE_TYPE_FOLDER)) {+ return false;+ }+ }+ }+ else {+ if (!(file->typeflag & filter->filter)) {+ return false;+ }+ }+ }+ return true;+}++bool is_filtered_file(FileListInternEntry *file, const char * /*root*/, FileListFilter *filter)+{+ return is_filtered_file_type(file, filter) &&+ (is_filtered_file_relpath(file, filter) || is_filtered_file_name(file, filter));+}++static bool is_filtered_id_file_type(const FileListInternEntry *file,+ const short id_code,+ const char *name,+ const FileListFilter *filter)+{+ if (!is_filtered_file_type(file, filter)) {+ return false;+ }++ /* We only check for types if some type are enabled in filtering. */+ if ((filter->filter || filter->filter_id) && (filter->flags & FLF_DO_FILTER)) {+ if (id_code) {+ if (!name && (filter->flags & FLF_HIDE_LIB_DIR)) {+ return false;+ }++ const uint64_t filter_id = BKE_idtype_idcode_to_idfilter(id_code);+ if (!(filter_id & filter->filter_id)) {+ return false;+ }+ }+ }++ return true;+}++/**+ * Get the asset metadata of a file, if it represents an asset. This may either be of a local ID+ * (ID in the current #Main) or read from an external asset library.+ */+static AssetMetaData *filelist_file_internal_get_asset_data(const FileListInternEntry *file)+{+ if (asset_system::AssetRepresentation *asset = file->get_asset()) {+ return &asset->get_metadata();+ }+ return nullptr;+}++void prepare_filter_asset_library(const FileList *filelist, FileListFilter *filter)+{+ /* Not used yet for the asset view template. */+ if (!filter->asset_catalog_filter) {+ return;+ }+ BLI_assert_msg(filelist->asset_library,+ "prepare_filter_asset_library() should only be called when the file browser is "+ "in asset browser mode");++ file_ensure_updated_catalog_filter_data(filter->asset_catalog_filter, filelist->asset_library);+}++bool is_filtered_asset(FileListInternEntry *file, FileListFilter *filter)+{+ asset_system::AssetRepresentation *asset = file->get_asset();+ const AssetMetaData &asset_data = asset->get_metadata();++ /* Not used yet for the asset view template. */+ if (filter->asset_catalog_filter &&+ !file_is_asset_visible_in_catalog_filter_settings(filter->asset_catalog_filter, &asset_data))+ {+ return false;+ }++ const bool is_online = asset->is_online_only();+ if (((filter->flags & FLF_ASSETS_HIDE_ONLINE) != 0) && is_online) {+ return false;+ }+ if (((filter->flags & FLF_ASSETS_HIDE_OFFLINE) != 0) && !is_online) {+ return false;+ }+ if (asset_system::skip_experimental_asset_catalog(asset_data.catalog_id)) {+ return false;+ }++ /* The actual string search is handled for the whole list at once, to allow sorting of the+ * results. */+ return true;+}++static bool is_filtered_lib_type(FileListInternEntry *file,+ const char * /*root*/,+ FileListFilter *filter)+{+ if (file->typeflag & FILE_TYPE_BLENDERLIB) {+ return is_filtered_id_file_type(file, file->blentype, file->name, filter);+ }+ return is_filtered_file_type(file, filter);+}++bool is_filtered_lib(FileListInternEntry *file, const char *root, FileListFilter *filter)+{+ return is_filtered_lib_type(file, root, filter) && is_filtered_file_relpath(file, filter);+}++bool is_filtered_main_assets(FileListInternEntry *file,+ const char * /*dir*/,+ FileListFilter *filter)+{+ /* "Filtered" means *not* being filtered out... So return true if the file should be visible. */+ return is_filtered_id_file_type(file, file->blentype, file->name, filter) &&+ is_filtered_asset(file, filter);+}++bool is_filtered_asset_library(FileListInternEntry *file, const char *root, FileListFilter *filter)+{+ if (filelist_intern_entry_is_main_file(file)) {+ return is_filtered_main_assets(file, root, filter);+ }++ return is_filtered_lib_type(file, root, filter) && is_filtered_asset(file, filter);+}++void filelist_tag_needs_filtering(FileList *filelist)+{+ filelist->flags |= FL_NEED_FILTERING;+}++bool filelist_needs_filtering(FileList *filelist)+{+ return (filelist->flags & FL_NEED_FILTERING);+}++static void filelist_filter_and_sort_assets(FileList *filelist,+ FileListInternEntry **entries_to_filter,+ int entries_num)+{+ const FileListFilter &filter = filelist->filter_data;+ if (filter.filter_search[0] == '\0') {+ /* No search text, just copy over the pre-filtered list. */+ if (filelist->filelist_intern.filtered) {+ MEM_delete(filelist->filelist_intern.filtered);+ }+ filelist->filelist_intern.filtered = static_cast<FileListInternEntry **>(MEM_new_uninitialized(+ sizeof(*filelist->filelist_intern.filtered) * size_t(entries_num), __func__));+ memcpy(filelist->filelist_intern.filtered,+ entries_to_filter,+ sizeof(*filelist->filelist_intern.filtered) * size_t(entries_num));+ filelist->filelist.entries_filtered_num = entries_num;+ return;+ }++ /* `filter->filter_search` contains "*the search text*". */+ char filter_search_buf[sizeof(FileListFilter::filter_search)];+ const size_t string_length = STRNCPY_RLEN(filter_search_buf, filter.filter_search);++ /* When doing a name comparison, get rid of the leading/trailing asterisks. */+ filter_search_buf[string_length - 1] = '\0';+ const char *search_str = filter_search_buf + 1;++ string_search::StringSearch<FileListInternEntry> search(nullptr,+ string_search::MainWordsHeuristic::All);++ for (int i = 0; i < entries_num; i++) {+ FileListInternEntry *file = entries_to_filter[i];+ const AssetMetaData *asset_data = filelist_file_internal_get_asset_data(file);+ if (asset_data) {+ std::string searchable_string = file->name;+ for (const AssetTag &asset_tag : asset_data->tags) {+ searchable_string += " ";+ searchable_string += asset_tag.name;+ }+ search.add(searchable_string, file);+ }+ else {+ search.add(file->name, file);+ }+ }++ const Vector<FileListInternEntry *> results = search.query(search_str);++ if (filelist->filelist_intern.filtered) {+ MEM_delete(filelist->filelist_intern.filtered);+ }++ const int num_filtered = results.size();+ filelist->filelist_intern.filtered = static_cast<FileListInternEntry **>(MEM_new_uninitialized(+ sizeof(*filelist->filelist_intern.filtered) * size_t(num_filtered), __func__));+ for (int i = 0; i < num_filtered; i++) {+ filelist->filelist_intern.filtered[i] = results[i];+ }+ filelist->filelist.entries_filtered_num = num_filtered;+}++void filelist_filter(FileList *filelist)+{+ int num_filtered = 0;+ const int num_files = filelist->filelist.entries_num;+ FileListInternEntry **filtered_tmp;++ if (ELEM(filelist->filelist.entries_num, FILEDIR_NBR_ENTRIES_UNSET, 0)) {+ return;+ }++ if (!(filelist->flags & FL_NEED_FILTERING)) {+ /* Assume it has already been filtered, nothing else to do! */+ return;+ }++ if (filelist->flags & FL_NEED_RESET_GLOB) {+ filelist_reset_glob(filelist);+ }++ filelist->filter_data.flags &= ~FLF_HIDE_LIB_DIR;+ if (filelist->max_recursion) {+ /* Never show lib ID 'categories' directories when we are in 'flat' mode, unless+ * root path is a blend file. */+ char dir[FILE_MAX_LIBEXTRA];+ if (!filelist_islibrary(filelist, dir, nullptr)) {+ filelist->filter_data.flags |= FLF_HIDE_LIB_DIR;+ }+ }++ if (filelist->prepare_filter_fn) {+ filelist->prepare_filter_fn(filelist, &filelist->filter_data);+ }++ filtered_tmp = MEM_new_array_uninitialized<FileListInternEntry *>(num_files, __func__);++ /* Filter remap & count how many files are left after filter in a single loop. */+ for (FileListInternEntry &file : filelist->filelist_intern.entries) {+ if (filelist->filter_fn(&file, filelist->filelist.root, &filelist->filter_data)) {+ filtered_tmp[num_filtered++] = &file;+ }+ }++ if (filelist->tags & FILELIST_TAGS_APPLY_FUZZY_SEARCH) {+ filelist_filter_and_sort_assets(filelist, filtered_tmp, num_filtered);+ }+ else {+ if (filelist->filelist_intern.filtered) {+ MEM_delete(filelist->filelist_intern.filtered);+ }+ filelist->filelist_intern.filtered = MEM_new_array_uninitialized<FileListInternEntry *>(+ num_filtered, __func__);+ memcpy(filelist->filelist_intern.filtered,+ filtered_tmp,+ sizeof(*filelist->filelist_intern.filtered) * size_t(num_filtered));+ filelist->filelist.entries_filtered_num = num_filtered;+ }++ // printf("Filtered: %d over %d entries\n", num_filtered, filelist->filelist.entries_num);++ filelist_cache_clear(filelist->filelist_cache, filelist->filelist_cache->size);+ filelist->flags &= ~FL_NEED_FILTERING;++ MEM_delete(filtered_tmp);+}++void filelist_setfilter_options(FileList *filelist,+ const bool do_filter,+ const bool hide_dot,+ const bool hide_parent,+ const uint64_t filter,+ const uint64_t filter_id,+ const bool filter_assets_only,+ const bool filter_assets_hide_online,+ const bool filter_assets_hide_offline,+ const char *filter_search)+{+ bool update = false;++ if (((filelist->filter_data.flags & FLF_DO_FILTER) != 0) != (do_filter != 0)) {+ filelist->filter_data.flags ^= FLF_DO_FILTER;+ update = true;+ }+ if (((filelist->filter_data.flags & FLF_HIDE_DOT) != 0) != (hide_dot != 0)) {+ filelist->filter_data.flags ^= FLF_HIDE_DOT;+ update = true;+ }+ if (((filelist->filter_data.flags & FLF_HIDE_PARENT) != 0) != (hide_parent != 0)) {+ filelist->filter_data.flags ^= FLF_HIDE_PARENT;+ update = true;+ }+ if (((filelist->filter_data.flags & FLF_ASSETS_ONLY) != 0) != (filter_assets_only != 0)) {+ filelist->filter_data.flags ^= FLF_ASSETS_ONLY;+ update = true;+ }+ if (((filelist->filter_data.flags & FLF_ASSETS_HIDE_ONLINE) != 0) !=+ (filter_assets_hide_online != 0))+ {+ filelist->filter_data.flags ^= FLF_ASSETS_HIDE_ONLINE;+ update = true;+ }+ if (((filelist->filter_data.flags & FLF_ASSETS_HIDE_OFFLINE) != 0) !=+ (filter_assets_hide_offline != 0))+ {+ filelist->filter_data.flags ^= FLF_ASSETS_HIDE_OFFLINE;+ update = true;+ }+ if (filelist->filter_data.filter != filter) {+ filelist->filter_data.filter = filter;+ update = true;+ }+ const uint64_t new_filter_id = (filter & FILE_TYPE_BLENDERLIB) ? filter_id : FILTER_ID_ALL;+ if (filelist->filter_data.filter_id != new_filter_id) {+ filelist->filter_data.filter_id = new_filter_id;+ update = true;+ }+ if (BLI_strcmp_ignore_pad(filelist->filter_data.filter_search, filter_search, '*') != 0) {+ BLI_strncpy_ensure_pad(filelist->filter_data.filter_search, filter_search, '*');+ update = true;+ }++ if (update) {+ /* And now, free filtered data so that we know we have to filter again. */+ filelist_tag_needs_filtering(filelist);+ }+}++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_intern.hh b/ui/space_file/filelist/filelist_intern.hhnew file mode 100644index 0000000..5e5e5bc--- /dev/null+++ b/ui/space_file/filelist/filelist_intern.hh@@ -0,0 +1,351 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#pragma once++#include <cstdint>+#include <memory>++#include "BLI_fileops.hh"+#include "BLI_map.hh"++#include "DNA_listBase.h"+#include "DNA_space_enums.h"+#include "DNA_space_types.h"++#include "IMB_thumbs.hh"++struct BlendHandle;+namespace blender {++#define FILEDIR_NBR_ENTRIES_UNSET -1++using FileUID = uint32_t;++struct AssetLibraryReference;+struct FileDirEntry;+struct FileIndexerType;+struct ID;+struct PreviewImage;+struct ThreadQueue;+struct TaskPool;++namespace asset_system {+class AssetLibrary;+class AssetRepresentation;+} // namespace asset_system+namespace ed::asset_browser {+class AssetCatalogFilterSettings;+}++/* ------------------FILELIST------------------------ */++struct FileListInternEntry {+ FileListInternEntry *next = nullptr, *prev = nullptr;++ FileUID uid = 0;++ eFileSel_File_Types typeflag = eFileSel_File_Types(0);+ /** ID type, in case typeflag has FILE_TYPE_BLENDERLIB set. */+ int blentype = 0;++ char *relpath = nullptr;+ /** Optional argument for shortcuts, aliases etc. */+ char *redirection_path = nullptr;+ /** not strictly needed, but used during sorting, avoids to have to recompute it there... */+ const char *name = nullptr;+ bool free_name = false;++ /**+ * This is data from the current main, represented by this file. It's crucial that this is+ * updated correctly on undo, redo and file reading (without UI). The space is responsible to+ * take care of that.+ */+ struct {+ /** When showing local IDs (#FILE_MAIN_ASSET), the ID this file entry represents. */+ ID *id = nullptr;++ /* For the few file types that have the preview already in memory. For others, there's delayed+ * preview reading from disk. Non-owning pointer. */+ PreviewImage *preview_image = nullptr;+ } local_data;++ /**+ * References an asset in the asset library storage.+ * The file list inserts this asset representation into the library, and removes it again when+ * the file list is destructed. In that sense it manages the asset but doesn't own it.+ *+ * Weak pointer so access is protected in case the asset library gets destructed externally.+ */+ std::weak_ptr<asset_system::AssetRepresentation> asset;++ /* See #FILE_ENTRY_BLENDERLIB_NO_PREVIEW. */+ bool blenderlib_has_no_preview = false;++ /** Defined in BLI_fileops.hh */+ eFileAttributes attributes = eFileAttributes(0);+ BLI_stat_t st = {0};++ /**+ * Be careful not to use the returned asset pointer in a context where it might be dangling, e.g.+ * because the file list or the asset library were destroyed.+ */+ asset_system::AssetRepresentation *get_asset() const+ {+ if (std::shared_ptr<asset_system::AssetRepresentation> asset_ptr = asset.lock()) {+ /* Returning a raw pointer from a shared pointer and destructing the shared pointer+ * immediately afterwards isn't entirely clean. But it's just a way to get the raw pointer+ * from the weak pointer. Nothing should free the asset in the asset library meanwhile, so+ * this should be fine really. */+ BLI_assert(asset_ptr.use_count() > 1);+ return asset_ptr.get();+ }+ return nullptr;+ }+};++struct FileListIntern {+ /** FileListInternEntry items. */+ ListBaseT<FileListInternEntry> entries;+ FileListInternEntry **filtered;++ FileUID curr_uid; /* Used to generate UID during internal listing. */+};++#define FILELIST_ENTRYCACHESIZE_DEFAULT 1024 /* Keep it a power of two! */+struct FileListEntryCache {+ size_t size = 0; /* The size of the cache... */++ int flags = 0;++ /* This one gathers all entries from both block and misc caches. Used for easy bulk-freeing. */+ ListBaseT<FileDirEntry> cached_entries = {};++ /* Block cache: all entries between start and end index.+ * used for part of the list on display. */+ FileDirEntry **block_entries = nullptr;+ int block_start_index = 0;+ int block_end_index = 0;+ int block_center_index = 0;+ int block_cursor = 0;++ /* Misc cache: random indices, FIFO behavior.+ * NOTE: Not 100% sure we actually need that, time will say. */+ int misc_cursor = 0;+ int *misc_entries_indices = nullptr;+ Map<int, FileDirEntry *> misc_entries;++ /* Allows to quickly get a cached entry from its UID. */+ Map<int, FileDirEntry *> uids;++ /* Previews handling. */+ TaskPool *previews_pool = nullptr;+ ThreadQueue *previews_done = nullptr;+ ThumbCancellationToken previews_cancel_token;+ /** Counter for previews that are not fully loaded and ready to display yet. So includes all+ * previews either in `previews_pool` or `previews_done`. #filelist_cache_previews_update() makes+ * previews in `preview_done` ready for display, so the counter is decremented there. */+ int previews_todo_count = 0;++ FileListEntryCache();+ ~FileListEntryCache();+};++/** #FileListCache.flags */+enum {+ FLC_PREVIEWS_ACTIVE = 1 << 0,+};++struct FileListEntryPreview {+ /** Use #FILE_MAX_LIBEXTRA as this is the size written into by #filelist_file_get_full_path. */+ char filepath[FILE_MAX_LIBEXTRA];+ uint flags;+ int index;+ int icon_id;+};++/* Dummy wrapper around FileListEntryPreview to ensure we do not access freed memory when freeing+ * tasks' data (see #74609). */+struct FileListEntryPreviewTaskData {+ FileListEntryPreview *preview;+};++struct FileListFilter {+ uint64_t filter;+ uint64_t filter_id;+ char filter_search[66]; /* + 2 for heading/trailing implicit '*' wildcards. */+ short flags;++ ed::asset_browser::AssetCatalogFilterSettings *asset_catalog_filter;+};++/** #FileListFilter.flags */+enum {+ FLF_DO_FILTER = 1 << 0,+ FLF_HIDE_DOT = 1 << 1,+ FLF_HIDE_PARENT = 1 << 2,+ FLF_HIDE_LIB_DIR = 1 << 3,+ FLF_ASSETS_ONLY = 1 << 4,+ FLF_ASSETS_HIDE_ONLINE = 1 << 5,+ FLF_ASSETS_HIDE_OFFLINE = 1 << 6,+};++struct FileListReadJob;+struct FileList {+ FileDirEntryArr filelist;++ eFileSelectType type;+ /* The library this list was created for. Stored here so we know when to re-read. */+ AssetLibraryReference *asset_library_ref;+ asset_system::AssetLibrary *asset_library; /* Non-owning. */++ short flags;++ short sort;++ FileListFilter filter_data;++ /**+ * File indexer to use. Attribute is always set.+ */+ const FileIndexerType *indexer;++ FileListIntern filelist_intern;++ FileListEntryCache *filelist_cache;++ /**+ * We need to keep those info outside of actual file-list items,+ * because those are no more persistent+ * (only generated on demand, and freed as soon as possible).+ * Persistent part (mere list of paths + stat info)+ * is kept as small as possible, and file-browser agnostic.+ *+ * - The key is a #FileDirEntry::uid+ * - The value is an #eDirEntry_SelectFlag.+ */+ GHash *selection_state;++ /** Extension glob, see #filelist_setglob. */+ char filter_glob[FILE_MAXFILE];++ short max_recursion;+ short recursion_level;++ BlendHandle *libfiledata;++ /**+ * Set given path as root directory.+ *+ * \param do_change: When true, the callback may change given string in place to a valid value.+ * \return True when `dirpath` is valid.+ */+ bool (*check_dir_fn)(const FileList *filelist,+ char dirpath[FILE_MAX_LIBEXTRA],+ const bool do_change);++ /** Called from the main thread when starting the job. */+ void (*start_job_fn)(FileListReadJob *job_params);+ /** Called from the main thread in regular intervals. */+ void (*timer_step_fn)(FileListReadJob *job_params);+ /** Fill `filelist` (to be called by read job). */+ void (*read_job_fn)(FileListReadJob *job_params, bool *stop, bool *do_update, float *progress);++ /** Filter an entry of current `filelist`. */+ bool (*filter_fn)(FileListInternEntry *file, const char *root, FileListFilter *filter);+ /** Executed before filtering individual items, to set up additional filter data. */+ void (*prepare_filter_fn)(const FileList *filelist, FileListFilter *filter);++ /** #FileListTags. */+ short tags;+};++/** #FileList.flags */+enum {+ FL_FORCE_RESET = 1 << 0,+ /* Don't do a full reset (unless #FL_FORCE_RESET is also set), only reset files representing main+ * data (assets from the current file/#Main). */+ FL_FORCE_RESET_MAIN_FILES = 1 << 1,+ FL_IS_READY = 1 << 2,+ FL_IS_PENDING = 1 << 3,+ FL_NEED_SORTING = 1 << 4,+ FL_NEED_FILTERING = 1 << 5,+ FL_SORT_INVERT = 1 << 6,+ /** Trigger a call to #AS_asset_library_load() to update asset catalogs (won't reload the actual+ * assets) */+ FL_RELOAD_ASSET_LIBRARY = 1 << 7,+ FL_ASSETS_INCLUDE_ONLINE = 1 << 8,+ /** #FileList.filter_glob changed, re-tag entries instead of reading the directory again. */+ FL_NEED_RESET_GLOB = 1 << 9,+};++/** #FileList.tags */+enum FileListTags {+ /** The file list has references to main data (IDs) and needs special care. */+ FILELIST_TAGS_USES_MAIN_DATA = (1 << 0),+ /**+ * Apply fuzzy search on results left after applying #FileList.filter_fn.+ */+ FILELIST_TAGS_APPLY_FUZZY_SEARCH = (1 << 1),+ /** The file list type is not thread-safe. */+ FILELIST_TAGS_NO_THREADS = (1 << 2),+ /** The file list is owned by the #ED_asset_list.hh API (global storage to load and store assets+ * globally), not the Asset Browser. */+ FILELIST_TAGS_FROM_GLOBAL_ASSET_LIST = 1 << 3,+};++enum class SpecialFileImages {+ Document,+ Folder,+ Parent,+ /* Keep this last. */+ _Max,+};++void filelist_cache_clear(FileListEntryCache *cache, size_t new_size);++FileUID filelist_uid_generate(FileList *filelist);++const char *fileentry_uiname(const char *root, FileListInternEntry *entry, char *buff);++bool filelist_intern_entry_is_main_file(const FileListInternEntry *intern_entry);++void prepare_filter_asset_library(const FileList *filelist, FileListFilter *filter);++/** \return true when the file should be in the result set, false if it should be filtered out. */+bool is_filtered_file(FileListInternEntry *file, const char * /*root*/, FileListFilter *filter);+bool is_filtered_asset(FileListInternEntry *file, FileListFilter *filter);+bool is_filtered_lib(FileListInternEntry *file, const char *root, FileListFilter *filter);+bool is_filtered_main_assets(FileListInternEntry *file,+ const char * /*dir*/,+ FileListFilter *filter);+bool is_filtered_asset_library(FileListInternEntry *file,+ const char *root,+ FileListFilter *filter);++bool filelist_checkdir_dir(const FileList * /*filelist*/,+ char dirpath[FILE_MAX_LIBEXTRA],+ const bool do_change);+bool filelist_checkdir_lib(const FileList * /*filelist*/,+ char dirpath[FILE_MAX_LIBEXTRA],+ const bool do_change);++/** Set or clear #FILE_TYPE_OPERATOR on `entry`, from `filter_glob` matching it. */+void filelist_entry_glob_tag(FileListInternEntry *entry, const char *filter_glob);+/** Apply #FileList.filter_glob to the entries already read. */+void filelist_reset_glob(FileList *filelist);++void filelist_set_readjob_directories(FileList *filelist);+void filelist_set_readjob_library(FileList *filelist);+void filelist_set_readjob_on_disk_asset_library(FileList *filelist);+void filelist_set_readjob_remote_asset_library(FileList *filelist);+void filelist_set_readjob_current_file_asset_library(FileList *filelist);+void filelist_set_readjob_essentials_asset_library(FileList *filelist);+void filelist_set_readjob_all_asset_library(FileList *filelist);++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_readjob.cc b/ui/space_file/filelist/filelist_readjob.ccnew file mode 100644index 0000000..0a90280--- /dev/null+++ b/ui/space_file/filelist/filelist_readjob.cc@@ -0,0 +1,285 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "BKE_context.hh"+#include "BKE_main.hh"++#include "BLI_listbase.h"+#include "BLI_string.h"++#include "WM_api.hh"+#include "WM_types.hh"++#include "../filelist.hh"+#include "filelist_intern.hh"+#include "filelist_readjob.hh"++namespace blender {++static void filelist_readjob_initjob(void *flrjv)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);+ if (flrj->filelist->start_job_fn) {+ flrj->filelist->start_job_fn(flrj);+ }+}++/**+ * Check if the read-job is requesting a partial reread of the file list only.+ */+static bool filelist_readjob_is_partial_read(const FileListReadJob *read_job)+{+ return read_job->only_main_data;+}++/**+ * \note This may trigger partial filelist reading. If the #FL_FORCE_RESET_MAIN_FILES flag is set,+ * some current entries are kept and we just call the readjob to update the main files (see+ * #FileListReadJob.only_main_data).+ */+static void filelist_readjob_startjob(void *flrjv, wmJobWorkerStatus *worker_status)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);++ // printf("START filelist reading (%d files, main thread: %d)\n",+ // flrj->filelist->filelist.entries_num, BLI_thread_is_main());++ {+ std::scoped_lock lock(flrj->lock);+ BLI_assert((flrj->tmp_filelist == nullptr) && flrj->filelist);++ flrj->tmp_filelist = MEM_dupalloc(flrj->filelist);++ flrj->tmp_filelist->filelist.entries.clear_no_delete();+ flrj->tmp_filelist->filelist.entries_num = FILEDIR_NBR_ENTRIES_UNSET;++ flrj->tmp_filelist->filelist_intern.filtered = nullptr;+ flrj->tmp_filelist->filelist_intern.entries.clear_no_delete();+ if (filelist_readjob_is_partial_read(flrj)) {+ /* Don't unset the current UID on partial read, would give duplicates otherwise. */+ }+ else {+ filelist_uid_unset(&flrj->tmp_filelist->filelist_intern.curr_uid);+ }++ flrj->tmp_filelist->libfiledata = nullptr;+ flrj->tmp_filelist->filelist_cache = nullptr;+ flrj->tmp_filelist->selection_state = nullptr;+ flrj->tmp_filelist->asset_library_ref = nullptr;+ flrj->tmp_filelist->filter_data.asset_catalog_filter = nullptr;+ }++ flrj->tmp_filelist->read_job_fn(+ flrj, &worker_status->stop, &worker_status->do_update, &worker_status->progress);+}++/**+ * \note This may update for a partial filelist reading job. If the #FL_FORCE_RESET_MAIN_FILES flag+ * is set, some current entries are kept and we just call the readjob to update the main+ * files (see #FileListReadJob.only_main_data).+ */+static void filelist_readjob_update(void *flrjv)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);+ FileListIntern *fl_intern = &flrj->filelist->filelist_intern;+ ListBaseT<FileListInternEntry> new_entries = {nullptr};+ int entries_num, new_entries_num = 0;++ BLI_movelisttolist(&new_entries, &fl_intern->entries);+ entries_num = flrj->filelist->filelist.entries_num;++ {+ std::scoped_lock lock(flrj->lock);+ if (flrj->tmp_filelist->filelist.entries_num > 0) {+ /* We just move everything out of 'thread context' into final list. */+ new_entries_num = flrj->tmp_filelist->filelist.entries_num;+ BLI_movelisttolist(&new_entries, &flrj->tmp_filelist->filelist.entries);+ flrj->tmp_filelist->filelist.entries_num = 0;+ }++ if (flrj->tmp_filelist->asset_library) {+ flrj->filelist->asset_library = flrj->tmp_filelist->asset_library;+ }++ /* Important for partial reads: Copy increased UID counter back to the real list. */+ fl_intern->curr_uid = std::max(flrj->tmp_filelist->filelist_intern.curr_uid,+ fl_intern->curr_uid);+ }++ if (new_entries_num) {+ /* Do not clear selection cache, we can assume already 'selected' UIDs are still valid! Keep+ * the asset library data we just read. */+ filelist_clear_ex(flrj->filelist, false, true, false);++ flrj->filelist->flags |= (FL_NEED_SORTING | FL_NEED_FILTERING);++ /* The job tagged these entries with the glob it started with. */+ if (!STREQ(flrj->tmp_filelist->filter_glob, flrj->filelist->filter_glob)) {+ flrj->filelist->flags |= FL_NEED_RESET_GLOB;+ }+ }++ /* if no new_entries_num, this is NOP */+ BLI_movelisttolist(&fl_intern->entries, &new_entries);+ flrj->filelist->filelist.entries_num = std::max(entries_num, 0) + new_entries_num;+}++static void filelist_readjob_timer_step(void *flrjv)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);++ if (flrj->filelist->timer_step_fn) {+ flrj->filelist->timer_step_fn(flrj);+ }+}++static void filelist_readjob_endjob(void *flrjv)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);++ /* In case there would be some dangling update... */+ filelist_readjob_update(flrjv);++ flrj->filelist->flags &= ~FL_IS_PENDING;+ flrj->filelist->flags |= FL_IS_READY;++ WM_reports_from_reports_move(flrj->wm, &flrj->reports);+ BKE_reports_free(&flrj->reports);+}++static void filelist_readjob_free(void *flrjv)+{+ FileListReadJob *flrj = static_cast<FileListReadJob *>(flrjv);++ // printf("END filelist reading (%d files)\n", flrj->filelist->filelist.entries_num);++ if (flrj->tmp_filelist) {+ /* tmp_filelist shall never ever be filtered! */+ BLI_assert(flrj->tmp_filelist->filelist.entries_num == 0);+ BLI_assert(flrj->tmp_filelist->filelist.entries.is_empty());++ filelist_freelib(flrj->tmp_filelist);+ filelist_free(flrj->tmp_filelist);+ }++ MEM_delete(flrj);+}++static eWM_JobType filelist_jobtype_get(const FileList *filelist)+{+ if (filelist->tags & FILELIST_TAGS_FROM_GLOBAL_ASSET_LIST) {+ BLI_assert(filelist->asset_library_ref != nullptr);+ return WM_JOB_TYPE_ASSET_LIBRARY_GLOBAL_LISTING_LOAD;+ }+ if (filelist->asset_library_ref) {+ return WM_JOB_TYPE_ASSET_LIBRARY_LOAD;+ }+ return WM_JOB_TYPE_FILESEL_READDIR;+}++/* TODO(Julian): This is temporary, because currently the job system identifies jobs to suspend by+ * the startjob callback, rather than the type. See PR #123033. */+static void assetlibrary_readjob_startjob(void *flrjv, wmJobWorkerStatus *worker_status)+{+ filelist_readjob_startjob(flrjv, worker_status);+}++static void filelist_readjob_start_ex(FileList *filelist,+ const int space_notifier,+ const bContext *C,+ const bool force_blocking_read)+{+ Main *bmain = CTX_data_main(C);+ wmJob *wm_job;+ FileListReadJob *flrj;++ if (!filelist_is_dir(filelist, filelist->filelist.root)) {+ return;+ }++ /* prepare job data */+ flrj = MEM_new<FileListReadJob>(__func__);+ flrj->filelist = filelist;+ flrj->current_main = bmain;+ flrj->wm = CTX_wm_manager(C);+ STRNCPY(flrj->main_filepath, BKE_main_blendfile_path(bmain));+ if ((filelist->flags & FL_FORCE_RESET_MAIN_FILES) && !(filelist->flags & FL_FORCE_RESET) &&+ (filelist->filelist.entries_num != FILEDIR_NBR_ENTRIES_UNSET))+ {+ flrj->only_main_data = true;+ }+ if (filelist->flags & FL_RELOAD_ASSET_LIBRARY) {+ flrj->reload_asset_library = true;+ }+ BKE_reports_init(&flrj->reports, RPT_STORE | RPT_PRINT);+ BKE_report_print_level_set(&flrj->reports, RPT_WARNING);++ filelist->flags &= ~(FL_FORCE_RESET | FL_FORCE_RESET_MAIN_FILES | FL_NEED_RESET_GLOB |+ FL_RELOAD_ASSET_LIBRARY | FL_IS_READY);+ filelist->flags |= FL_IS_PENDING;++ /* The file list type may not support threading so execute immediately. Same when only rereading+ * #Main data (which we do quite often on changes to #Main, since it's the easiest and safest way+ * to ensure the displayed data is up to date), because some operations executing right after+ * main data changed may need access to the ID files (see #93691). */+ const bool no_threads = (filelist->tags & FILELIST_TAGS_NO_THREADS) || flrj->only_main_data;++ if (force_blocking_read || no_threads) {+ /* Single threaded execution. Just directly call the callbacks. */+ wmJobWorkerStatus worker_status = {};+ filelist_readjob_startjob(flrj, &worker_status);+ filelist_readjob_endjob(flrj);+ filelist_readjob_free(flrj);++ WM_event_add_notifier(C, space_notifier | NA_JOB_FINISHED, nullptr);+ return;+ }++ /* setup job */+ wm_job = WM_jobs_get(CTX_wm_manager(C),+ CTX_wm_window(C),+ filelist,+ filelist->asset_library_ref ? "Loading Asset Library..." :+ "Listing directories...",+ WM_JOB_PROGRESS,+ filelist_jobtype_get(filelist));+ WM_jobs_customdata_set(wm_job, flrj, filelist_readjob_free);+ WM_jobs_timer(+ wm_job, 0.01, space_notifier, space_notifier | NA_JOB_FINISHED, filelist_readjob_timer_step);+ WM_jobs_callbacks(wm_job,+ filelist->asset_library_ref ? assetlibrary_readjob_startjob :+ filelist_readjob_startjob,+ filelist_readjob_initjob,+ filelist_readjob_update,+ filelist_readjob_endjob);++ /* start the job */+ WM_jobs_start(CTX_wm_manager(C), wm_job);+}++void filelist_readjob_start(FileList *filelist, const int space_notifier, const bContext *C)+{+ filelist_readjob_start_ex(filelist, space_notifier, C, false);+}++void filelist_readjob_blocking_run(FileList *filelist, int space_notifier, const bContext *C)+{+ filelist_readjob_start_ex(filelist, space_notifier, C, true);+}++void filelist_readjob_stop(FileList *filelist, wmWindowManager *wm)+{+ WM_jobs_kill_all_from_owner(wm, filelist);+}++int filelist_readjob_running(FileList *filelist, wmWindowManager *wm)+{+ return WM_jobs_has_running(wm, filelist, filelist_jobtype_get(filelist));+}++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_readjob.hh b/ui/space_file/filelist/filelist_readjob.hhnew file mode 100644index 0000000..9e89ad2--- /dev/null+++ b/ui/space_file/filelist/filelist_readjob.hh@@ -0,0 +1,164 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ *+ * Functions used by multiple read-job types.+ */++#pragma once++#include <atomic>+#include <functional>+#include <optional>+#include <string>++#include "AS_remote_library.hh"++#include "BLI_compiler_attrs.h"+#include "BLI_map.hh"+#include "BLI_mutex.hh"++#include "BKE_report.hh"++namespace blender {++struct BLODataBlockInfo;+struct FileList;+struct FileListInternEntry;+struct Main;+struct wmWindowManager;+namespace asset_system {+class AssetLibrary;+}++struct RemoteLibraryRequest {+ /** Directory the asset library files should be stored in (#bUserAssetLibrary.dirpath). */+ std::string dirpath;++ /** Code requested to cancel the read job. */+ std::atomic<bool> cancel = false;++ /** Is this asset library tagged as loading externally? Used for remote asset libraries to keep+ * the filelist loading running while the library is being downloaded by other code. */+ std::atomic<bool> is_downloading = false;++ /** When downloading remote library pages, ignore pages older than this. They are from a previous+ * download still. Uses the file system clock since others are not fit for file time-stamp+ * comparisons. */+ std::optional<asset_system::RemoteLibraryLoadingStatus::FileSystemTimePoint> request_time =+ std::nullopt;++ std::atomic<bool> metafiles_in_place = false;+ asset_system::RemoteLibraryLoadingStatus::TimePoint last_new_pages_time;+ std::atomic<bool> new_pages_available = false;+};++struct FileListReadJob {+ Mutex lock;+ char main_filepath[1024 /*FILE_MAX*/] = "";+ Main *current_main = nullptr;+ wmWindowManager *wm = nullptr;+ FileList *filelist = nullptr;++ ReportList reports;++ /**+ * The path currently being read, relative to the filelist root directory.+ * Needed for recursive reading. The full file path is then composed like:+ * `<filelist root>/<cur_relbase>/<file name>`.+ * (whereby the file name may also be a library path within a .blend, e.g.+ * `Materials/Material.001`).+ */+ char cur_relbase[1024 + 258 /*FILE_MAX_LIBEXTRA*/] = "";++ /** The current asset library to load. Usually the same as #FileList.asset_library, however+ * sometimes the #FileList one is a combination of multiple other ones ("All" asset library),+ * which need to be loaded individually. Then this can be set to override the #FileList library.+ * Use this in all loading code. */+ asset_system::AssetLibrary *load_asset_library = nullptr;+ /** Set to request a partial read that only adds files representing #Main data (IDs). Used when+ * #Main may have received changes of interest (e.g. asset removed or renamed). */+ bool only_main_data = false;++ /** Trigger a call to #AS_asset_library_load() to update asset catalogs (won't reload the actual+ * assets) */+ std::atomic<bool> reload_asset_library = false;++ Map<std::string, std::unique_ptr<RemoteLibraryRequest>> remote_library_requests;++ std::optional<std::function<void(asset_system::AssetRepresentation &)>> on_asset_added =+ std::nullopt;++ /** Shallow copy of #filelist for thread-safe access.+ *+ * The job system calls #filelist_readjob_update which moves any read file from #tmp_filelist+ * into #filelist in a thread-safe way.+ *+ * #tmp_filelist also keeps an `AssetLibrary *` so that it can be loaded in the same thread,+ * and moved to #filelist once all categories are loaded.+ *+ * NOTE: #tmp_filelist is freed in #filelist_readjob_free, so any copied pointers need to be+ * set to nullptr to avoid double-freeing them. */+ FileList *tmp_filelist = nullptr;+};++[[nodiscard]] char *current_relpath_append(const FileListReadJob *job_params,+ const char *filename) ATTR_MALLOC;++bool filelist_checkdir_return_always_valid(const FileList * /*filelist*/,+ char /*dirpath*/[1024 + 258 /*FILE_MAX_LIBEXTRA*/],+ const bool /*do_change*/);++bool filelist_readjob_append_entries(FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *from_entries,+ int from_entries_num);++/**+ * \warning: This "steals" the asset metadata from \a datablock_info. Not great design but fixing+ * this requires redesigning things on the caller side for proper ownership management.+ */+void filelist_readjob_list_lib_add_datablock(+ FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *entries,+ BLODataBlockInfo *datablock_info,+ const bool prefix_relpath_with_group_name,+ const int idcode,+ const char *group_name,+ const std::optional<asset_system::OnlineAssetInfo> online_asset_info = std::nullopt);++void filelist_readjob_recursive_dir_add_items(const bool do_lib,+ FileListReadJob *job_params,+ const bool *stop,+ bool *do_update,+ float *progress);+void filelist_readjob_directories_and_libraries(const bool do_lib,+ FileListReadJob *job_params,+ const bool *stop,+ bool *do_update,+ float *progress);++void filelist_readjob_dir(FileListReadJob *job_params,+ bool *stop,+ bool *do_update,+ float *progress);++void filelist_readjob_main_assets_add_items(FileListReadJob *job_params,+ bool * /*stop*/,+ bool *do_update,+ float * /*progress*/);++void filelist_readjob_load_asset_library_data(FileListReadJob *job_params, bool *do_update);++void remote_asset_library_request(FileListReadJob *job_params,+ const asset_system::RemoteLibraryDefinitionRef &library);+void remote_asset_library_load(FileListReadJob *job_params,+ RemoteLibraryRequest &request,+ bool *stop,+ bool *do_update,+ float *progress);+void filelist_timer_step_remote_asset_library(FileListReadJob *job_params);++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_readjob_common.cc b/ui/space_file/filelist/filelist_readjob_common.ccnew file mode 100644index 0000000..b8d315f--- /dev/null+++ b/ui/space_file/filelist/filelist_readjob_common.cc@@ -0,0 +1,883 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "AS_asset_library.hh"++#include "BLI_linklist.h"+#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_stack.h"+#include "BLI_string.h"+#include "BLI_string_utils.hh"++#include "BKE_asset.hh"+#include "BKE_blendfile.hh"+#include "BKE_idtype.hh"++#ifdef WIN32+# include "BKE_appdir.hh"+# include "BLF_api.hh"+# include "BLI_winstuff.hh"+#endif++#include "DNA_space_enums.h"++#include "ED_file_indexer.hh"+#include "ED_fileselect.hh"++#include "filelist_intern.hh"++#include "filelist_readjob.hh"++namespace blender {++/* helper, could probably go in BKE actually? */+static int groupname_to_code(const char *group)+{+ char buf[BLO_GROUP_MAX];+ char *lslash;++ BLI_assert(group);++ STRNCPY(buf, group);+ lslash = const_cast<char *>(BLI_path_slash_rfind(buf));+ if (lslash) {+ lslash[0] = '\0';+ }++ return buf[0] ? BKE_idtype_idcode_from_name(buf) : 0;+}++/**+ * Append \a filename (or even a path inside of a .blend, like `Material/Material.001`), to the+ * current relative path being read within the filelist root. The returned string needs freeing+ * with #MEM_delete().+ */+char *current_relpath_append(const FileListReadJob *job_params, const char *filename)+{+ char relbase[sizeof(job_params->cur_relbase)];+ STRNCPY(relbase, job_params->cur_relbase);++ /* Early exit, nothing to join. */+ if (!relbase[0]) {+ return BLI_strdup(filename);+ }++ BLI_path_slash_ensure(relbase);++ char relpath[FILE_MAX_LIBEXTRA];+ /* Using #BLI_path_join works but isn't needed as `rel_subdir` has a trailing slash. */+ BLI_string_join(relpath,+ /* + 2 to remove "//" relative path prefix. */+ BLI_path_is_rel(relbase) ? relbase + 2 : relbase,+ filename);++ return BLI_strdup(relpath);+}++/* -------------------------------------------------------------------- */+/** \name Common callbacks.+ * \{ */++bool filelist_checkdir_return_always_valid(const FileList * /*filelist*/,+ char /*dirpath*/[FILE_MAX_LIBEXTRA],+ const bool /*do_change*/)+{+ return true;+}++static void parent_dir_until_exists_or_default_root(char *dir)+{+ /* Only allow absolute paths as CWD relative doesn't make sense from the UI. */+ if (BLI_path_is_abs_from_cwd(dir) && BLI_path_parent_dir_until_exists(dir)) {+ return;+ }++#ifdef WIN32+ BLI_windows_get_default_root_dir(dir);+#else+ ARRAY_SET_ITEMS(dir, '/', '\0');+#endif+}++bool filelist_checkdir_dir(const FileList * /*filelist*/,+ char dirpath[FILE_MAX_LIBEXTRA],+ const bool do_change)+{+ bool is_valid;+ if (do_change) {+ parent_dir_until_exists_or_default_root(dirpath);+ is_valid = true;+ }+ else {+ is_valid = BLI_path_is_abs_from_cwd(dirpath) && BLI_is_dir(dirpath);+ }+ return is_valid;+}++bool filelist_checkdir_lib(const FileList * /*filelist*/,+ char dirpath[FILE_MAX_LIBEXTRA],+ const bool do_change)+{+ char tdir[FILE_MAX_LIBEXTRA];+ char *name;++ const bool is_valid = (BLI_is_dir(dirpath) ||+ (BKE_blendfile_library_path_explode(dirpath, tdir, nullptr, &name) &&+ BLI_is_file(tdir) && !name));++ if (do_change && !is_valid) {+ /* if not a valid library, we need it to be a valid directory! */+ parent_dir_until_exists_or_default_root(dirpath);+ return true;+ }+ return is_valid;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name File-list Directory/Library Reading+ * \{ */++/**+ * \return True if new entries were added to the file list.+ */+bool filelist_readjob_append_entries(FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *from_entries,+ int from_entries_num)+{+ BLI_assert(from_entries->count() == from_entries_num);+ if (from_entries_num <= 0) {+ return false;+ }++ FileList *filelist = job_params->tmp_filelist; /* Use the thread-safe filelist queue. */+ std::scoped_lock lock(job_params->lock);+ BLI_movelisttolist(&filelist->filelist.entries, from_entries);+ filelist->filelist.entries_num += from_entries_num;++ return true;+}++#ifdef WIN32+static int filelist_add_userfonts_regpath(HKEY hKeyParent,+ LPCSTR subkeyName,+ ListBaseT<FileListInternEntry> *entries)+{+ int font_num = 0;+ HKEY key = 0;+ /* Try to open the requested key. */+ if (RegOpenKeyExA(hKeyParent, subkeyName, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) {+ return 0;+ }++ DWORD index = 0;+ /* Value name and data buffers (ANSI). */+ TCHAR KeyName[255];+ DWORD KeyNameLen = sizeof(KeyName);+ TCHAR KeyValue[FILE_MAX];+ DWORD KeyValueLen = sizeof(KeyValue);+ DWORD valueType;++ /* Enumerate values. */+ while (RegEnumValueA(key,+ index,+ (LPSTR)&KeyName,+ &KeyNameLen,+ NULL,+ &valueType,+ (LPBYTE)&KeyValue,+ &KeyValueLen) == ERROR_SUCCESS)+ {+ /* Only consider string values (paths). */+ if (valueType == REG_SZ || valueType == REG_EXPAND_SZ) {+ FileListInternEntry *entry = MEM_new<FileListInternEntry>(__func__);+ /* Find last slash to determine basename/relpath portion. */+ const char *val_str = (const char *)KeyValue;+ const char *lslash_str = BLI_path_slash_rfind(val_str);+ const size_t lslash = lslash_str ? size_t(lslash_str - val_str) + 1 : 0;++ BLI_stat(val_str, &entry->st);+ entry->relpath = BLI_strdup(val_str + lslash);+ entry->name = BLF_display_name_from_file(val_str);+ entry->free_name = true;+ entry->attributes = FILE_ATTR_READONLY & FILE_ATTR_ALIAS;+ entry->typeflag = FILE_TYPE_FTFONT;+ entry->redirection_path = BLI_strdup(val_str);+ BLI_addtail(entries, entry);+ font_num++;+ }++ KeyNameLen = sizeof(KeyName);+ KeyValueLen = sizeof(KeyValue);+ index++;+ }++ /* Enumerate sub-keys and recurse into them. */+ index = 0;+ while (RegEnumKeyExA(key, index, (LPSTR)&KeyName, &KeyNameLen, NULL, NULL, NULL, NULL) ==+ ERROR_SUCCESS)+ {+ font_num += filelist_add_userfonts_regpath(key, KeyName, entries);+ KeyNameLen = sizeof(KeyName);+ index++;+ }++ RegCloseKey(key);+ return font_num;+}++static int filelist_add_userfonts(ListBaseT<FileListInternEntry> *entries)+{+ return filelist_add_userfonts_regpath(+ HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", entries);+}++#endif++static int filelist_readjob_list_dir(FileListReadJob *job_params,+ const char *root,+ ListBaseT<FileListInternEntry> *entries,+ const char *filter_glob,+ const bool do_lib,+ const char *main_filepath,+ const bool skip_currpar)+{+ direntry *files;+ int entries_num = 0;+ /* Full path of the item. */+ char full_path[FILE_MAX];++#ifdef WIN32+ char fonts_path[FILE_MAXDIR] = {0};+ BKE_appdir_font_folder_default(fonts_path);+ BLI_path_slash_ensure(fonts_path);+ if (STREQ(root, fonts_path)) {+ entries_num += filelist_add_userfonts(entries);+ }+#endif++ const int files_num = BLI_filelist_dir_contents(root, &files);+ if (files) {+ int i = files_num;+ while (i--) {+ FileListInternEntry *entry;++ if (skip_currpar && FILENAME_IS_CURRPAR(files[i].relname)) {+ continue;+ }++ entry = MEM_new<FileListInternEntry>(__func__);+ entry->relpath = current_relpath_append(job_params, files[i].relname);+ entry->st = files[i].s;++ BLI_path_join(full_path, root, files[i].relname);+ char *target = full_path;++ /* Set initial file type and attributes. */+ entry->attributes = BLI_file_attributes(full_path);+ if (S_ISDIR(files[i].s.st_mode)+#ifdef __APPLE__+ && !(ED_path_extension_type(full_path) & FILE_TYPE_BUNDLE)+#endif+ )+ {+ entry->typeflag = FILE_TYPE_DIR;+ }++ /* Is this a file that points to another file? */+ if (entry->attributes & FILE_ATTR_ALIAS) {+ entry->redirection_path = MEM_new_array_zeroed<char>(FILE_MAXDIR, __func__);+ if (BLI_file_alias_target(full_path, entry->redirection_path)) {+ if (BLI_is_dir(entry->redirection_path)) {+ entry->typeflag = FILE_TYPE_DIR;+ BLI_path_slash_ensure(MutableCStr(entry->redirection_path, FILE_MAXDIR));+ }+ else {+ entry->typeflag = eFileSel_File_Types(ED_path_extension_type(entry->redirection_path));+ }+ target = entry->redirection_path;+#ifdef WIN32+ /* On Windows don't show `.lnk` extension for valid shortcuts. */+ BLI_path_extension_strip(entry->relpath);+#endif+ }+ else {+ MEM_delete(entry->redirection_path);+ entry->redirection_path = nullptr;+ entry->attributes |= FILE_ATTR_HIDDEN;+ }+ }++ if (!(entry->typeflag & FILE_TYPE_DIR)) {+ if (do_lib && BKE_blendfile_extension_check(target)) {+ /* If we are considering .blend files as libraries, promote them to directory status. */+ entry->typeflag = FILE_TYPE_BLENDER;+ /* prevent current file being used as acceptable dir */+ if (BLI_path_cmp(main_filepath, target) != 0) {+ entry->typeflag |= FILE_TYPE_DIR;+ }+ }+ else {+ entry->typeflag = eFileSel_File_Types(ED_path_extension_type(target));+ }+ }++ filelist_entry_glob_tag(entry, filter_glob);++#ifndef WIN32+ /* Set linux-style dot files hidden too. */+ if (BLI_path_has_hidden_component(entry->relpath)) {+ entry->attributes |= FILE_ATTR_HIDDEN;+ }+#endif++ BLI_addtail(entries, entry);+ entries_num++;+ }+ BLI_filelist_free(files, files_num);+ }+ return entries_num;+}++/**+ * From here, we are in 'Job Context',+ * i.e. have to be careful about sharing stuff between background working thread.+ * and main one (used by UI among other things).+ */+struct TodoDir {+ int level;+ char *dir;+};++/**+ * Structure to keep the file indexer and its user data together.+ */+struct FileIndexer {+ const FileIndexerType *callbacks;++ /**+ * User data. Contains the result of `callbacks.init_user_data`.+ */+ void *user_data;+};++enum ListLibOptions {+ LIST_LIB_OPTION_NONE = 0,++ /* Will read both the groups + actual ids from the library. Reduces the amount of times that+ * a library needs to be opened. */+ LIST_LIB_RECURSIVE = (1 << 0),++ /* Will only list assets. */+ LIST_LIB_ASSETS_ONLY = (1 << 1),++ /* Add given root as result. */+ LIST_LIB_ADD_PARENT = (1 << 2),+};+ENUM_OPERATORS(ListLibOptions);++static FileListInternEntry *filelist_readjob_list_lib_group_create(+ const FileListReadJob *job_params, const int idcode, const char *group_name)+{+ FileListInternEntry *entry = MEM_new<FileListInternEntry>(__func__);+ entry->relpath = current_relpath_append(job_params, group_name);+ entry->typeflag |= FILE_TYPE_BLENDERLIB | FILE_TYPE_DIR;+ entry->blentype = idcode;+ return entry;+}++void filelist_readjob_list_lib_add_datablock(+ FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *entries,+ BLODataBlockInfo *datablock_info,+ const bool prefix_relpath_with_group_name,+ const int idcode,+ const char *group_name,+ const std::optional<asset_system::OnlineAssetInfo> online_asset_info)+{+ FileListInternEntry *entry = MEM_new<FileListInternEntry>(__func__);+ if (prefix_relpath_with_group_name) {+ std::string datablock_path = StringRef(group_name) + SEP_STR + datablock_info->name;+ entry->relpath = current_relpath_append(job_params, datablock_path.c_str());+ }+ else {+ entry->relpath = current_relpath_append(job_params, datablock_info->name);+ }+ entry->typeflag |= FILE_TYPE_BLENDERLIB;+ if (datablock_info) {+ entry->blenderlib_has_no_preview = datablock_info->no_preview_found;++ if (datablock_info->name[0] == '.') {+ entry->attributes |= FILE_ATTR_HIDDEN;+ }++ if (datablock_info->asset_data) {++ entry->typeflag |= FILE_TYPE_ASSET;+ if (online_asset_info) {+ entry->typeflag |= FILE_TYPE_ASSET_ONLINE;+ }++ if (job_params->load_asset_library) {+ /* We never want to add assets directly to the "All" library, always add to the actually+ * containing one. */+ BLI_assert((job_params->load_asset_library->library_type() != ASSET_LIBRARY_ALL));++ /* Take ownership over the asset data (shallow copies into unique_ptr managed memory) to+ * pass it on to the asset system. */+ std::unique_ptr metadata = std::make_unique<AssetMetaData>(+ std::move(*datablock_info->asset_data));+ MEM_delete(datablock_info->asset_data);+ /* Give back a non-owning pointer, because the data-block info is still needed (e.g. to+ * update the asset index). */+ datablock_info->asset_data = metadata.get();+ datablock_info->free_asset_data = false;++ entry->asset = online_asset_info ?+ job_params->load_asset_library->add_external_online_asset(+ entry->relpath,+ datablock_info->name,+ idcode,+ std::move(metadata),+ *online_asset_info) :+ job_params->load_asset_library->add_external_on_disk_asset(+ entry->relpath, datablock_info->name, idcode, std::move(metadata));+ if (job_params->on_asset_added) {+ (*job_params->on_asset_added)(*entry->get_asset());+ }+ }+ }+ }+ entry->blentype = idcode;+ BLI_addtail(entries, entry);+}++static void filelist_readjob_list_lib_add_datablocks(FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *entries,+ LinkNode *datablock_infos,+ const bool prefix_relpath_with_group_name,+ const int idcode,+ const char *group_name)+{+ for (LinkNode *ln = datablock_infos; ln; ln = ln->next) {+ BLODataBlockInfo *datablock_info = static_cast<BLODataBlockInfo *>(ln->link);+ filelist_readjob_list_lib_add_datablock(+ job_params, entries, datablock_info, prefix_relpath_with_group_name, idcode, group_name);+ }+}++static FileListInternEntry *filelist_readjob_list_lib_navigate_to_parent_entry_create(+ const FileListReadJob *job_params)+{+ FileListInternEntry *entry = MEM_new<FileListInternEntry>(__func__);+ entry->relpath = current_relpath_append(job_params, FILENAME_PARENT);+ entry->typeflag |= (FILE_TYPE_BLENDERLIB | FILE_TYPE_DIR);+ return entry;+}++static void filelist_readjob_list_lib_add_from_indexer_entries(+ FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *entries,+ const FileIndexerEntries *indexer_entries,+ const bool prefix_relpath_with_group_name)+{+ for (const LinkNode *ln = indexer_entries->entries; ln; ln = ln->next) {+ FileIndexerEntry *indexer_entry = static_cast<FileIndexerEntry *>(ln->link);+ const char *group_name = BKE_idtype_idcode_to_name(indexer_entry->idcode);+ filelist_readjob_list_lib_add_datablock(job_params,+ entries,+ &indexer_entry->datablock_info,+ prefix_relpath_with_group_name,+ indexer_entry->idcode,+ group_name);+ }+}++static int filelist_readjob_list_lib_populate_from_index(FileListReadJob *job_params,+ ListBaseT<FileListInternEntry> *entries,+ const ListLibOptions options,+ const int read_from_index,+ const FileIndexerEntries *indexer_entries)+{+ int navigate_to_parent_len = 0;+ if (options & LIST_LIB_ADD_PARENT) {+ FileListInternEntry *entry = filelist_readjob_list_lib_navigate_to_parent_entry_create(+ job_params);+ BLI_addtail(entries, entry);+ navigate_to_parent_len = 1;+ }++ filelist_readjob_list_lib_add_from_indexer_entries(job_params, entries, indexer_entries, true);+ return read_from_index + navigate_to_parent_len;+}++/**+ * \return The number of entries found if the \a root path points to a valid library file.+ * Otherwise returns no value (#std::nullopt).+ */+static std::optional<int> filelist_readjob_list_lib(FileListReadJob *job_params,+ const char *root,+ ListBaseT<FileListInternEntry> *entries,+ const ListLibOptions options,+ FileIndexer *indexer_runtime)+{+ BLI_assert(indexer_runtime);++ char dir[FILE_MAX_LIBEXTRA], *group;++ BlendHandle *libfiledata = nullptr;++ /* Check if the given root is actually a library. All folders are passed to+ * `filelist_readjob_list_lib` and based on the number of found entries `filelist_readjob_do`+ * will do a dir listing only when this function does not return any entries. */+ /* TODO(jbakker): We should consider introducing its own function to detect if it is a lib and+ * call it directly from `filelist_readjob_do` to increase readability. */+ const bool is_lib = BKE_blendfile_library_path_explode(root, dir, &group, nullptr);+ if (!is_lib) {+ return std::nullopt;+ }++ /* The root path contains an ID group (e.g. "Materials" or "Objects"). */+ const bool has_group = group != nullptr;++ /* Try read from indexer_runtime. */+ /* Indexing returns all entries in a blend file. We should ignore the index when listing a group+ * inside a blend file, so the `entries` isn't filled with undesired entries.+ * This happens when linking or appending data-blocks, where you can navigate into a group (ie+ * Materials/Objects) where you only want to work with partial indexes.+ *+ * Adding support for partial reading/updating indexes would increase the complexity.+ */+ const bool use_indexer = !has_group;+ FileIndexerEntries indexer_entries = {nullptr};+ if (use_indexer) {+ int read_from_index = 0;+ eFileIndexerResult indexer_result = indexer_runtime->callbacks->read_index(+ dir, &indexer_entries, &read_from_index, indexer_runtime->user_data);+ if (indexer_result == FILE_INDEXER_ENTRIES_LOADED) {+ int entries_read = filelist_readjob_list_lib_populate_from_index(+ job_params, entries, options, read_from_index, &indexer_entries);+ ED_file_indexer_entries_clear(&indexer_entries);+ return entries_read;+ }+ }++ /* Open the library file. */+ BlendFileReadReport bf_reports{};+ libfiledata = BLO_blendhandle_from_file(dir, &bf_reports);+ if (libfiledata == nullptr) {+ return std::nullopt;+ }++ /* Add current parent when requested. */+ /* Is the navigate to previous level added to the list of entries. When added the return value+ * should be increased to match the actual number of entries added. It is introduced to keep+ * the code clean and readable and not counting in a single variable. */+ int navigate_to_parent_len = 0;+ if (options & LIST_LIB_ADD_PARENT) {+ FileListInternEntry *entry = filelist_readjob_list_lib_navigate_to_parent_entry_create(+ job_params);+ BLI_addtail(entries, entry);+ navigate_to_parent_len = 1;+ }++ int group_len = 0;+ int datablock_len = 0;+ /* Read only the datablocks from this group. */+ if (has_group) {+ const int idcode = groupname_to_code(group);+ LinkNode *datablock_infos = BLO_blendhandle_get_datablock_info(+ libfiledata, idcode, options & LIST_LIB_ASSETS_ONLY, &datablock_len);+ filelist_readjob_list_lib_add_datablocks(+ job_params, entries, datablock_infos, false, idcode, group);+ BLO_datablock_info_linklist_free(datablock_infos);+ }+ /* Read all datablocks from all groups. */+ else {+ LinkNode *groups = BLO_blendhandle_get_linkable_groups(libfiledata);+ group_len = BLI_linklist_count(groups);++ for (LinkNode *ln = groups; ln; ln = ln->next) {+ const char *group_name = static_cast<char *>(ln->link);+ const int idcode = groupname_to_code(group_name);+ FileListInternEntry *group_entry = filelist_readjob_list_lib_group_create(+ job_params, idcode, group_name);+ BLI_addtail(entries, group_entry);++ if (options & LIST_LIB_RECURSIVE) {+ int group_datablock_len;+ LinkNode *group_datablock_infos = BLO_blendhandle_get_datablock_info(+ libfiledata, idcode, options & LIST_LIB_ASSETS_ONLY, &group_datablock_len);+ filelist_readjob_list_lib_add_datablocks(+ job_params, entries, group_datablock_infos, true, idcode, group_name);+ if (use_indexer) {+ ED_file_indexer_entries_extend_from_datablock_infos(+ &indexer_entries, group_datablock_infos, idcode);+ }+ BLO_datablock_info_linklist_free(group_datablock_infos);+ datablock_len += group_datablock_len;+ }+ }++ BLI_linklist_freeN(groups);+ }++ BLO_blendhandle_close(libfiledata);++ /* Update the index. */+ if (use_indexer) {+ indexer_runtime->callbacks->update_index(dir, &indexer_entries, indexer_runtime->user_data);+ ED_file_indexer_entries_clear(&indexer_entries);+ }++ /* Return the number of items added to entries. */+ int added_entries_len = group_len + datablock_len + navigate_to_parent_len;+ return added_entries_len;+}++static bool filelist_readjob_should_recurse_into_entry(const int max_recursion,+ const bool is_lib,+ const int current_recursion_level,+ FileListInternEntry *entry)+{+ if (max_recursion == 0) {+ /* Recursive loading is disabled. */+ return false;+ }+ if (!is_lib && current_recursion_level > max_recursion) {+ /* No more levels of recursion left. */+ return false;+ }+ /* Show entries when recursion is set to `Blend file` even when `current_recursion_level`+ * exceeds `max_recursion`. */+ if (!is_lib && (current_recursion_level >= max_recursion) &&+ ((entry->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) == 0))+ {+ return false;+ }+ if (entry->typeflag & FILE_TYPE_BLENDERLIB) {+ /* Libraries are already loaded recursively when recursive loaded is used. No need to add+ * them another time. This loading is done with the `LIST_LIB_RECURSIVE` option. */+ return false;+ }+ if (!(entry->typeflag & FILE_TYPE_DIR)) {+ /* Cannot recurse into regular file entries. */+ return false;+ }+ if (FILENAME_IS_CURRPAR(entry->relpath)) {+ /* Don't schedule go to parent entry, (`..`) */+ return false;+ }++ return true;+}++void filelist_readjob_recursive_dir_add_items(const bool do_lib,+ FileListReadJob *job_params,+ const bool *stop,+ bool *do_update,+ float *progress)+{+ FileList *filelist = job_params->tmp_filelist; /* Use the thread-safe filelist queue. */+ ListBaseT<FileListInternEntry> entries = {nullptr};+ BLI_Stack *todo_dirs;+ TodoDir *td_dir;+ char dir[FILE_MAX_LIBEXTRA];+ char filter_glob[FILE_MAXFILE];+ const char *root = filelist->filelist.root;+ const int max_recursion = filelist->max_recursion;+ int dirs_done_count = 0, dirs_todo_count = 1;++ /* The code below assumes the root ends in a slash. It's also not just the code below; weird+ * things happen when it doesn't end in a slash. Better to just enforce it. */+ BLI_assert_msg(StringRef(filelist->filelist.root).endswith(SEP_STR), filelist->filelist.root);++ todo_dirs = BLI_stack_new(sizeof(*td_dir), __func__);+ td_dir = static_cast<TodoDir *>(BLI_stack_push_r(todo_dirs));+ td_dir->level = 1;++ STRNCPY(dir, filelist->filelist.root);+ STRNCPY(filter_glob, filelist->filter_glob);++ BLI_path_abs(dir, job_params->main_filepath);+ BLI_path_normalize_dir(dir);+ td_dir->dir = BLI_strdup(dir);++ /* Init the file indexer. */+ FileIndexer indexer_runtime{};+ indexer_runtime.callbacks = filelist->indexer;+ if (indexer_runtime.callbacks->init_user_data) {+ indexer_runtime.user_data = indexer_runtime.callbacks->init_user_data(dir, sizeof(dir));+ }++ while (!BLI_stack_is_empty(todo_dirs) && !(*stop)) {+ int entries_num = 0;++ char *subdir;+ char rel_subdir[FILE_MAX_LIBEXTRA];+ int recursion_level;+ bool skip_currpar;++ td_dir = static_cast<TodoDir *>(BLI_stack_peek(todo_dirs));+ subdir = td_dir->dir;+ recursion_level = td_dir->level;+ skip_currpar = (recursion_level > 1);++ BLI_stack_discard(todo_dirs);++ /* ARRRG! We have to be very careful *not to use* common `BLI_path_utils.hh` helpers over+ * entry->relpath itself (nor any path containing it), since it may actually be a datablock+ * name inside .blend file, which can have slashes and backslashes! See #46827.+ * Note that in the end, this means we 'cache' valid relative subdir once here,+ * this is actually better. */+ STRNCPY(rel_subdir, subdir);+ BLI_path_abs(rel_subdir, root);+ BLI_path_normalize_dir(rel_subdir);+ BLI_path_rel(rel_subdir, root);++ /* Update the current relative base path within the filelist root. */+ STRNCPY(job_params->cur_relbase, rel_subdir);++ bool is_lib = false;+ if (do_lib) {+ ListLibOptions list_lib_options = LIST_LIB_OPTION_NONE;+ if (!skip_currpar) {+ list_lib_options |= LIST_LIB_ADD_PARENT;+ }++ /* Libraries are loaded recursively when max_recursion is set. It doesn't check if there is+ * still a recursion level over. */+ if (max_recursion > 0) {+ list_lib_options |= LIST_LIB_RECURSIVE;+ }+ /* Only load assets when browsing an asset library. For normal file browsing we return all+ * entries. `FLF_ASSETS_ONLY` filter can be enabled/disabled by the user. */+ if (job_params->load_asset_library) {+ list_lib_options |= LIST_LIB_ASSETS_ONLY;+ }+ std::optional<int> lib_entries_num = filelist_readjob_list_lib(+ job_params, subdir, &entries, list_lib_options, &indexer_runtime);+ if (lib_entries_num) {+ is_lib = true;+ entries_num += *lib_entries_num;+ }+ }++ if (!is_lib && BLI_is_dir(subdir)) {+ entries_num = filelist_readjob_list_dir(job_params,+ subdir,+ &entries,+ filter_glob,+ do_lib,+ job_params->main_filepath,+ skip_currpar);+ }++ for (FileListInternEntry &entry : entries) {+ entry.uid = filelist_uid_generate(filelist);+ if (!entry.name) {+ entry.name = fileentry_uiname(root, &entry, dir);+ }+ entry.free_name = true;++ if (filelist_readjob_should_recurse_into_entry(+ max_recursion, is_lib, recursion_level, &entry))+ {+ /* We have a directory we want to list, add it to todo list!+ * Using #BLI_path_join works but isn't needed as `root` has a trailing slash. */+ BLI_string_join(dir, root, entry.relpath);+ BLI_path_abs(dir, job_params->main_filepath);+ BLI_path_normalize_dir(dir);+ td_dir = static_cast<TodoDir *>(BLI_stack_push_r(todo_dirs));+ td_dir->level = recursion_level + 1;+ td_dir->dir = BLI_strdup(dir);+ dirs_todo_count++;+ }+ }++ if (filelist_readjob_append_entries(job_params, &entries, entries_num)) {+ *do_update = true;+ }++ dirs_done_count++;+ *progress = float(dirs_done_count) / float(dirs_todo_count);+ MEM_delete(subdir);+ }++ /* Finalize and free indexer. */+ if (indexer_runtime.callbacks->filelist_finished && BLI_stack_is_empty(todo_dirs)) {+ indexer_runtime.callbacks->filelist_finished(indexer_runtime.user_data);+ }+ if (indexer_runtime.callbacks->free_user_data && indexer_runtime.user_data) {+ indexer_runtime.callbacks->free_user_data(indexer_runtime.user_data);+ indexer_runtime.user_data = nullptr;+ }++ /* If we were interrupted by stop, stack may not be empty and we need to free+ * pending dir paths. */+ while (!BLI_stack_is_empty(todo_dirs)) {+ td_dir = static_cast<TodoDir *>(BLI_stack_peek(todo_dirs));+ MEM_delete(td_dir->dir);+ BLI_stack_discard(todo_dirs);+ }+ BLI_stack_free(todo_dirs);+}++void filelist_readjob_directories_and_libraries(const bool do_lib,+ FileListReadJob *job_params,+ const bool *stop,+ bool *do_update,+ float *progress)+{+ FileList *filelist = job_params->tmp_filelist; /* Use the thread-safe filelist queue. */++ // BLI_assert(filelist->filtered == nullptr);+ BLI_assert(filelist->filelist.entries.is_empty() &&+ (filelist->filelist.entries_num == FILEDIR_NBR_ENTRIES_UNSET));++ /* A valid, but empty directory from now. */+ filelist->filelist.entries_num = 0;++ filelist_readjob_recursive_dir_add_items(do_lib, job_params, stop, do_update, progress);+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Asset library reading+ * \{ */++/**+ * Load asset library data, which currently means loading the asset catalogs for the library.+ */+void filelist_readjob_load_asset_library_data(FileListReadJob *job_params, bool *do_update)+{+ BLI_assert(job_params->filelist->asset_library_ref);++ FileList *filelist = job_params->tmp_filelist; /* Use the thread-safe filelist queue. */+ *do_update = false;++ /* See if loading is necessary (and then load). */+ const bool is_force_reload = job_params->reload_asset_library;+ if (!filelist->asset_library || is_force_reload) {+ filelist->asset_library = AS_asset_library_load(job_params->current_main,+ *job_params->filelist->asset_library_ref);+ job_params->reload_asset_library = false;+ *do_update = true;+ }++ /* Not really necessary for this function to do, but otherwise it's up to the caller, and can be+ * forgotten. */+ job_params->load_asset_library = filelist->asset_library;+}++/** \} */++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_readjob_directories.cc b/ui/space_file/filelist/filelist_readjob_directories.ccnew file mode 100644index 0000000..04e7e93--- /dev/null+++ b/ui/space_file/filelist/filelist_readjob_directories.cc@@ -0,0 +1,32 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ *+ * Normal directory browsing.+ */++#include "filelist_intern.hh"+#include "filelist_readjob.hh"++namespace blender {++void filelist_readjob_dir(FileListReadJob *job_params,+ bool *stop,+ bool *do_update,+ float *progress)+{+ filelist_readjob_directories_and_libraries(+ /*do_lib=*/false, job_params, stop, do_update, progress);+}++void filelist_set_readjob_directories(FileList *filelist)+{+ filelist->check_dir_fn = filelist_checkdir_dir;+ filelist->read_job_fn = filelist_readjob_dir;+ filelist->filter_fn = is_filtered_file;+}++} // namespace blenderdiff --git a/ui/space_file/filelist/filelist_sort.cc b/ui/space_file/filelist/filelist_sort.ccnew file mode 100644index 0000000..6b9a1ee--- /dev/null+++ b/ui/space_file/filelist/filelist_sort.cc@@ -0,0 +1,354 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include "AS_asset_catalog.hh"+#include "AS_asset_library.hh"+#include "AS_asset_representation.hh"++#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"++#include "../filelist.hh"+#include "filelist_intern.hh"++namespace blender {++struct FileSortData {+ bool inverted;+};++static int compare_apply_inverted(int val, const FileSortData *sort_data)+{+ return sort_data->inverted ? -val : val;+}++/**+ * If all relevant characteristics match (e.g. the file type when sorting by file types), this+ * should be used as tiebreaker. It makes sure there's a well defined sorting even in such cases.+ *+ * Multiple files with the same name can appear with recursive file loading and/or when displaying+ * IDs of different types, so these cases need to be handled.+ *+ * 1) Sort files by name using natural sorting.+ * 2) If not possible (file names match) and both represent local IDs, sort by ID-type.+ * 3) If not possible and only one is a local ID, place files representing local IDs first.+ *+ * TODO: (not actually implemented, but should be):+ * 4) If no file represents a local ID, sort by file path, so that files higher up the file system+ * hierarchy are placed first.+ */+static int compare_tiebreaker(const FileListInternEntry *entry1, const FileListInternEntry *entry2)+{+ /* Case 1. */+ {+ const int order = BLI_strcasecmp_natural(entry1->name, entry2->name);+ if (order) {+ return order;+ }+ }++ /* Case 2. */+ if (entry1->local_data.id && entry2->local_data.id) {+ if (entry1->blentype < entry2->blentype) {+ return -1;+ }+ if (entry1->blentype > entry2->blentype) {+ return 1;+ }+ }+ /* Case 3. */+ {+ if (entry1->local_data.id && !entry2->local_data.id) {+ return -1;+ }+ if (!entry1->local_data.id && entry2->local_data.id) {+ return 1;+ }+ }++ return 0;+}++/**+ * Handles inverted sorting itself (currently there's nothing to invert), so if this returns non-0,+ * it should be used as-is and not inverted.+ */+static int compare_direntry_generic(const FileListInternEntry *entry1,+ const FileListInternEntry *entry2)+{+ /* type is equal to stat.st_mode */++ if (entry1->typeflag & FILE_TYPE_DIR) {+ if (entry2->typeflag & FILE_TYPE_DIR) {+ /* If both entries are tagged as dirs, we make a 'sub filter' that shows first the real dirs,+ * then libraries (.blend files), then categories in libraries. */+ if (entry1->typeflag & FILE_TYPE_BLENDERLIB) {+ if (!(entry2->typeflag & FILE_TYPE_BLENDERLIB)) {+ return 1;+ }+ }+ else if (entry2->typeflag & FILE_TYPE_BLENDERLIB) {+ return -1;+ }+ else if (entry1->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {+ if (!(entry2->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {+ return 1;+ }+ }+ else if (entry2->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {+ return -1;+ }+ }+ else {+ return -1;+ }+ }+ else if (entry2->typeflag & FILE_TYPE_DIR) {+ return 1;+ }++ /* make sure "." and ".." are always first */+ if (FILENAME_IS_CURRENT(entry1->relpath)) {+ return -1;+ }+ if (FILENAME_IS_CURRENT(entry2->relpath)) {+ return 1;+ }+ if (FILENAME_IS_PARENT(entry1->relpath)) {+ return -1;+ }+ if (FILENAME_IS_PARENT(entry2->relpath)) {+ return 1;+ }++ return 0;+}++static int compare_name(void *user_data, const void *a1, const void *a2)+{+ const FileListInternEntry *entry1 = static_cast<const FileListInternEntry *>(a1);+ const FileListInternEntry *entry2 = static_cast<const FileListInternEntry *>(a2);+ const FileSortData *sort_data = static_cast<const FileSortData *>(user_data);++ int ret;+ if ((ret = compare_direntry_generic(entry1, entry2))) {+ return ret;+ }++ return compare_apply_inverted(compare_tiebreaker(entry1, entry2), sort_data);+}++static int compare_date(void *user_data, const void *a1, const void *a2)+{+ const FileListInternEntry *entry1 = static_cast<const FileListInternEntry *>(a1);+ const FileListInternEntry *entry2 = static_cast<const FileListInternEntry *>(a2);+ const FileSortData *sort_data = static_cast<const FileSortData *>(user_data);+ int64_t time1, time2;++ int ret;+ if ((ret = compare_direntry_generic(entry1, entry2))) {+ return ret;+ }++ time1 = int64_t(entry1->st.st_mtime);+ time2 = int64_t(entry2->st.st_mtime);+ if (time1 < time2) {+ return compare_apply_inverted(1, sort_data);+ }+ if (time1 > time2) {+ return compare_apply_inverted(-1, sort_data);+ }++ return compare_apply_inverted(compare_tiebreaker(entry1, entry2), sort_data);+}++static int compare_size(void *user_data, const void *a1, const void *a2)+{+ const FileListInternEntry *entry1 = static_cast<const FileListInternEntry *>(a1);+ const FileListInternEntry *entry2 = static_cast<const FileListInternEntry *>(a2);+ const FileSortData *sort_data = static_cast<const FileSortData *>(user_data);+ uint64_t size1, size2;+ int ret;++ if ((ret = compare_direntry_generic(entry1, entry2))) {+ return ret;+ }++ size1 = entry1->st.st_size;+ size2 = entry2->st.st_size;+ if (size1 < size2) {+ return compare_apply_inverted(1, sort_data);+ }+ if (size1 > size2) {+ return compare_apply_inverted(-1, sort_data);+ }++ return compare_apply_inverted(compare_tiebreaker(entry1, entry2), sort_data);+}++static int compare_extension(void *user_data, const void *a1, const void *a2)+{+ const FileListInternEntry *entry1 = static_cast<const FileListInternEntry *>(a1);+ const FileListInternEntry *entry2 = static_cast<const FileListInternEntry *>(a2);+ const FileSortData *sort_data = static_cast<const FileSortData *>(user_data);+ int ret;++ if ((ret = compare_direntry_generic(entry1, entry2))) {+ return ret;+ }++ if ((entry1->typeflag & FILE_TYPE_BLENDERLIB) && !(entry2->typeflag & FILE_TYPE_BLENDERLIB)) {+ return -1;+ }+ if (!(entry1->typeflag & FILE_TYPE_BLENDERLIB) && (entry2->typeflag & FILE_TYPE_BLENDERLIB)) {+ return 1;+ }+ if ((entry1->typeflag & FILE_TYPE_BLENDERLIB) && (entry2->typeflag & FILE_TYPE_BLENDERLIB)) {+ if ((entry1->typeflag & FILE_TYPE_DIR) && !(entry2->typeflag & FILE_TYPE_DIR)) {+ return 1;+ }+ if (!(entry1->typeflag & FILE_TYPE_DIR) && (entry2->typeflag & FILE_TYPE_DIR)) {+ return -1;+ }+ if (entry1->blentype < entry2->blentype) {+ return compare_apply_inverted(-1, sort_data);+ }+ if (entry1->blentype > entry2->blentype) {+ return compare_apply_inverted(1, sort_data);+ }+ }+ else {+ const char *sufix1, *sufix2;++ if (!(sufix1 = strstr(entry1->relpath, ".blend.gz"))) {+ sufix1 = strrchr(entry1->relpath, '.');+ }+ if (!(sufix2 = strstr(entry2->relpath, ".blend.gz"))) {+ sufix2 = strrchr(entry2->relpath, '.');+ }+ if (!sufix1) {+ sufix1 = "";+ }+ if (!sufix2) {+ sufix2 = "";+ }++ if ((ret = BLI_strcasecmp(sufix1, sufix2))) {+ return compare_apply_inverted(ret, sort_data);+ }+ }++ return compare_apply_inverted(compare_tiebreaker(entry1, entry2), sort_data);+}++static int compare_asset_catalog(void *user_data, const void *a1, const void *a2)+{+ const FileListInternEntry *entry1 = static_cast<const FileListInternEntry *>(a1);+ const FileListInternEntry *entry2 = static_cast<const FileListInternEntry *>(a2);+ const FileSortData *sort_data = static_cast<const FileSortData *>(user_data);+ const asset_system::AssetRepresentation *asset1 = entry1->get_asset();+ const asset_system::AssetRepresentation *asset2 = entry2->get_asset();++ /* Order non-assets. */+ if (asset1 && !asset2) {+ return 1;+ }+ if (!asset1 && asset2) {+ return -1;+ }+ if (!asset1 && !asset2) {+ if (int order = compare_direntry_generic(entry1, entry2); order) {+ return compare_apply_inverted(order, sort_data);+ }++ return compare_apply_inverted(compare_tiebreaker(entry1, entry2), sort_data);+ }++ const asset_system::AssetLibrary &asset_library1 = asset1->owner_asset_library();+ const asset_system::AssetLibrary &asset_library2 = asset2->owner_asset_library();++ const asset_system::AssetCatalog *catalog1 = asset_library1.catalog_service().find_catalog(+ asset1->get_metadata().catalog_id);+ const asset_system::AssetCatalog *catalog2 = asset_library2.catalog_service().find_catalog(+ asset2->get_metadata().catalog_id);++ /* Order by catalog. Always keep assets without catalog last. */+ int order = 0;++ if (catalog1 && !catalog2) {+ order = 1;+ }+ else if (!catalog1 && catalog2) {+ order = -1;+ }+ else if (catalog1 && catalog2) {+ order = BLI_strcasecmp_natural(catalog1->path.c_str(), catalog2->path.c_str());+ }++ if (!order) {+ /* Order by name. */+ order = compare_tiebreaker(entry1, entry2);+ if (!order) {+ /* Order by library name. */+ order = BLI_strcasecmp_natural(asset_library1.name().c_str(), asset_library2.name().c_str());+ }+ }++ return compare_apply_inverted(order, sort_data);+}++void filelist_sort(FileList *filelist)+{+ if (filelist->flags & FL_NEED_SORTING) {+ int (*sort_cb)(void *, const void *, const void *) = nullptr;++ switch (filelist->sort) {+ case FILE_SORT_ALPHA:+ sort_cb = compare_name;+ break;+ case FILE_SORT_TIME:+ sort_cb = compare_date;+ break;+ case FILE_SORT_SIZE:+ sort_cb = compare_size;+ break;+ case FILE_SORT_EXTENSION:+ sort_cb = compare_extension;+ break;+ case FILE_SORT_ASSET_CATALOG:+ sort_cb = compare_asset_catalog;+ break;+ case FILE_SORT_DEFAULT:+ default:+ BLI_assert(0);+ break;+ }++ FileSortData sort_data{};+ sort_data.inverted = (filelist->flags & FL_SORT_INVERT) != 0;+ BLI_listbase_sort_r(&filelist->filelist_intern.entries, sort_cb, &sort_data);++ filelist_tag_needs_filtering(filelist);+ filelist->flags &= ~FL_NEED_SORTING;+ }+}++void filelist_setsorting(FileList *filelist, const short sort, bool invert_sort)+{+ const bool was_invert_sort = filelist->flags & FL_SORT_INVERT;++ if ((filelist->sort != sort) || (was_invert_sort != invert_sort)) {+ filelist->sort = sort;+ filelist->flags |= FL_NEED_SORTING;+ filelist->flags = invert_sort ? (filelist->flags | FL_SORT_INVERT) :+ (filelist->flags & ~FL_SORT_INVERT);+ }+}++} // namespace blenderdiff --git a/ui/space_file/filesel.cc b/ui/space_file/filesel.ccnew file mode 100644index 0000000..124bc70--- /dev/null+++ b/ui/space_file/filesel.cc@@ -0,0 +1,1543 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include <cstring>++#include <sys/stat.h>+#include <sys/types.h>++/* path/file handling stuff */+#ifdef WIN32+# include "BLI_winstuff.hh"+# include <direct.h>+# include <io.h>+#else+# include <dirent.h>+# include <sys/times.h>+# include <unistd.h>+#endif++#include "AS_asset_representation.hh"++#include "DNA_screen_types.h"+#include "DNA_space_enums.h"+#include "DNA_space_types.h"+#include "DNA_userdef_types.h"++#include "MEM_guardedalloc.h"++#include "BLI_fileops.hh"+#include "BLI_fnmatch.h"+#include "BLI_math_base.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_string_utf8.h"+#include "BLI_utildefines.h"++#include "BLT_date_string.hh"+#include "BLT_lang.hh"+#include "BLT_translation.hh"++#include "BKE_appdir.hh"+#include "BKE_context.hh"+#include "BKE_idtype.hh"+#include "BKE_main.hh"+#include "BKE_preferences.h"++#include "BLO_userdef_default.h"++#include "BLF_api.hh"++#include "ED_fileselect.hh"+#include "ED_screen.hh"++#include "WM_api.hh"+#include "WM_types.hh"++#include "RNA_access.hh"++#include "UI_interface.hh"+#include "UI_interface_icons.hh"+#include "UI_view2d.hh"++#include "AS_asset_library.hh"+#include "AS_essentials_library.hh"++#include "file_banner.hh"+#include "file_intern.hh"+#include "filelist.hh"++namespace blender {++static void fileselect_initialize_params_common(SpaceFile *sfile, FileSelectParams *params)+{+ const char *blendfile_path = BKE_main_blendfile_path_from_global();++ /* operator has no setting for this */+ params->active_file = -1;++ if (!params->dir[0]) {+ if (blendfile_path[0] != '\0') {+ BLI_path_split_dir_part(blendfile_path, params->dir);+ }+ else {+ const char *doc_path = BKE_appdir_folder_default();+ if (doc_path) {+ STRNCPY(params->dir, doc_path);+ }+ }+ }++ folder_history_list_ensure_for_active_browse_mode(sfile);+ folderlist_pushdir(sfile->folders_prev, params->dir);++ /* Switching thumbnails needs to recalc layout #28809. */+ if (sfile->layout) {+ sfile->layout->dirty = true;+ }+}++static void fileselect_ensure_updated_asset_params(SpaceFile *sfile)+{+ UserDef U_default = {};++ BLI_assert(sfile->browse_mode == FILE_BROWSE_MODE_ASSETS);+ BLI_assert(sfile->op == nullptr);++ FileAssetSelectParams *asset_params = sfile->asset_params;++ if (!asset_params) {+ asset_params = sfile->asset_params = MEM_new<FileAssetSelectParams>("FileAssetSelectParams");+ asset_params->base_params.details_flags = U_default.file_space_data.details_flags;+ asset_params->asset_library_ref.type = ASSET_LIBRARY_ALL;+ asset_params->asset_library_ref.custom_library_index = -1;+ asset_params->import_method = FILE_ASSET_IMPORT_FOLLOW_PREFS;+ asset_params->import_flags = FILE_ASSET_IMPORT_INSTANCE_COLLECTIONS_ON_LINK;+ }++ FileSelectParams *base_params = &asset_params->base_params;+ base_params->file[0] = '\0';+ base_params->filter_glob[0] = '\0';+ base_params->flag |= U_default.file_space_data.flag | FILE_ASSETS_ONLY | FILE_FILTER;+ base_params->flag &= ~FILE_DIRSEL_ONLY;+ base_params->filter |= FILE_TYPE_BLENDERLIB;+ base_params->filter_id = FILTER_ID_ALL;+ base_params->display = FILE_IMGDISPLAY;+ base_params->sort = FILE_SORT_ASSET_CATALOG;+ /* No details columns supported for assets (wouldn't contain anything), disable them all. */+ base_params->details_flags = eFileDetails{};+ /* Asset libraries include all sub-directories, so enable maximal recursion. */+ base_params->recursion_level = FILE_SELECT_MAX_RECURSIONS;+ /* 'SMALL' size by default. More reasonable since this is typically used as regular editor,+ * space is more of an issue here. */+ base_params->thumbnail_size = 96;+ base_params->list_thumbnail_size = 32;+ base_params->list_column_size = 220;++ fileselect_initialize_params_common(sfile, base_params);+}++/**+ * \note #RNA_struct_property_is_set_ex is used here because we want+ * the previously used settings to be used here rather than overriding them.+ */+static FileSelectParams *fileselect_ensure_updated_file_params(SpaceFile *sfile)+{+ BLI_assert(sfile->browse_mode == FILE_BROWSE_MODE_FILES);++ UserDef U_default = {};+ FileSelectParams *params;+ wmOperator *op = sfile->op;++ const char *blendfile_path = BKE_main_blendfile_path_from_global();++ /* create new parameters if necessary */+ if (!sfile->params) {+ sfile->params = MEM_new<FileSelectParams>("fileselparams");+ /* set path to most recently opened .blend */+ BLI_path_split_dir_file(blendfile_path, sfile->params->dir, sfile->params->file);+ sfile->params->filter_glob[0] = '\0';+ sfile->params->thumbnail_size = U_default.file_space_data.thumbnail_size;+ sfile->params->details_flags = U_default.file_space_data.details_flags;+ sfile->params->filter_id = U_default.file_space_data.filter_id;+ sfile->params->list_thumbnail_size = 16;+ sfile->params->list_column_size = 500;+ }++ params = sfile->params;++ /* set the parameters from the operator, if it exists */+ if (op) {+ PropertyRNA *prop;+ const bool is_files = (RNA_struct_find_property(op->ptr, "files") != nullptr);+ const bool is_filepath = (RNA_struct_find_property(op->ptr, "filepath") != nullptr);+ const bool is_filename = (RNA_struct_find_property(op->ptr, "filename") != nullptr);+ const bool is_directory = (RNA_struct_find_property(op->ptr, "directory") != nullptr);+ const bool is_relative_path = (RNA_struct_find_property(op->ptr, "relative_path") != nullptr);++ BLI_strncpy_utf8(+ params->title, WM_operatortype_name(op->type, op->ptr).c_str(), sizeof(params->title));++ if ((prop = RNA_struct_find_property(op->ptr, "filemode"))) {+ params->type = eFileSelectType(RNA_property_int_get(op->ptr, prop));+ }+ else {+ params->type = FILE_SPECIAL;+ }++ if (is_filepath && RNA_struct_property_is_set_ex(op->ptr, "filepath", false)) {+ char filepath[FILE_MAX];+ RNA_string_get(op->ptr, "filepath", filepath);+ if (params->type == FILE_LOADLIB) {+ STRNCPY(params->dir, filepath);+ params->file[0] = '\0';+ }+ else {+ BLI_path_split_dir_file(filepath, params->dir, params->file);+ }+ }+ else {+ if (is_directory && RNA_struct_property_is_set_ex(op->ptr, "directory", false)) {+ RNA_string_get(op->ptr, "directory", params->dir);+ params->file[0] = '\0';+ }++ if (is_filename && RNA_struct_property_is_set_ex(op->ptr, "filename", false)) {+ RNA_string_get(op->ptr, "filename", params->file);+ }+ }++ if (params->dir[0]) {+ BLI_path_abs(params->dir, blendfile_path);+ BLI_path_normalize_dir(params->dir);+ }++ params->flag = eFileSel_Params_Flag{};+ if (is_directory == true && is_filename == false && is_filepath == false && is_files == false)+ {+ params->flag |= FILE_DIRSEL_ONLY;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "check_existing"))) {+ params->flag |= RNA_property_boolean_get(op->ptr, prop) ? FILE_CHECK_EXISTING :+ eFileSel_Params_Flag{};+ }+ if ((prop = RNA_struct_find_property(op->ptr, "hide_props_region"))) {+ params->flag |= RNA_property_boolean_get(op->ptr, prop) ? FILE_HIDE_TOOL_PROPS :+ eFileSel_Params_Flag{};+ }++ params->filter = 0;+ if ((prop = RNA_struct_find_property(op->ptr, "filter_blender"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_BLENDER) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_blenlib"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_BLENDERLIB) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_backup"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_BLENDER_BACKUP) :+ 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_image"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_IMAGE) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_movie"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_MOVIE) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_python"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_PYSCRIPT) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_font"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_FTFONT) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_sound"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_SOUND) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_text"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_TEXT) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_archive"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_ARCHIVE) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_folder"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_FOLDER) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_btx"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_BTX) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_alembic"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_ALEMBIC) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_usd"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_USD) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_obj"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_OBJECT_IO) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_volume"))) {+ params->filter |= RNA_property_boolean_get(op->ptr, prop) ? int(FILE_TYPE_VOLUME) : 0;+ }+ if ((prop = RNA_struct_find_property(op->ptr, "filter_glob"))) {+ /* Protection against Python scripts not setting proper size limit. */+ char *glob = RNA_property_string_get_alloc(op->ptr, prop, std::nullopt, nullptr);+ BLI_SCOPED_DEFER([&]() { MEM_delete(glob); });+ STRNCPY_UTF8(params->filter_glob, glob);+ /* Fix stupid things that truncating might have generated,+ * like last group being a 'match everything' wildcard-only one... */+ BLI_path_extension_glob_validate(params->filter_glob);+ if (glob[0] != '\0') {+ params->filter |= (FILE_TYPE_OPERATOR | FILE_TYPE_FOLDER);+ }+ }+ else {+ params->filter_glob[0] = '\0';+ }++ if (params->filter != 0) {+ if (U.uiflag & USER_FILTERFILEEXTS) {+ params->flag |= FILE_FILTER;+ }+ else {+ params->flag &= ~FILE_FILTER;+ }+ }++ if (U.uiflag & USER_HIDE_DOT) {+ params->flag |= FILE_HIDE_DOT;+ }+ else {+ params->flag &= ~FILE_HIDE_DOT;+ }++ if (params->type == FILE_LOADLIB) {+ params->flag |= RNA_boolean_get(op->ptr, "link") ? FILE_LINK : eFileSel_Params_Flag{};+ params->flag |= RNA_boolean_get(op->ptr, "autoselect") ? FILE_AUTOSELECT :+ eFileSel_Params_Flag{};+ params->flag |= RNA_boolean_get(op->ptr, "active_collection") ? FILE_ACTIVE_COLLECTION :+ eFileSel_Params_Flag{};+ }++ if ((prop = RNA_struct_find_property(op->ptr, "allow_path_tokens"))) {+ params->flag |= RNA_property_boolean_get(op->ptr, prop) ? FILE_PATH_TOKENS_ALLOW :+ eFileSel_Params_Flag{};+ }++ if ((prop = RNA_struct_find_property(op->ptr, "display_type"))) {+ params->display = eFileDisplayType(RNA_property_enum_get(op->ptr, prop));+ }++ if (params->display == FILE_DEFAULTDISPLAY) {+ params->display = U_default.file_space_data.display_type;+ }++ if ((prop = RNA_struct_find_property(op->ptr, "sort_method"))) {+ params->sort = eFileSortType(RNA_property_enum_get(op->ptr, prop));+ }++ if (params->sort == FILE_SORT_DEFAULT) {+ params->sort = U_default.file_space_data.sort_type;+ }++ if (is_relative_path) {+ if ((prop = RNA_struct_find_property(op->ptr, "relative_path"))) {+ if (!RNA_property_is_set_ex(op->ptr, prop, false)) {+ RNA_property_boolean_set(op->ptr, prop, (U.flag & USER_RELPATHS) != 0);+ }+ }+ }+ }+ else {+ /* default values, if no operator */+ params->type = FILE_UNIX;+ params->flag |= U_default.file_space_data.flag;+ params->flag &= ~FILE_DIRSEL_ONLY;+ params->display = FILE_VERTICALDISPLAY;+ params->sort = FILE_SORT_ALPHA;+ params->filter = 0;+ params->filter_glob[0] = '\0';+ }++ fileselect_initialize_params_common(sfile, params);++ return params;+}++FileSelectParams *ED_fileselect_ensure_active_params(SpaceFile *sfile)+{+ switch (eFileBrowse_Mode(sfile->browse_mode)) {+ case FILE_BROWSE_MODE_FILES:+ if (!sfile->params) {+ fileselect_ensure_updated_file_params(sfile);+ }+ return sfile->params;+ case FILE_BROWSE_MODE_ASSETS:+ if (!sfile->asset_params) {+ fileselect_ensure_updated_asset_params(sfile);+ }+ return &sfile->asset_params->base_params;+ }++ BLI_assert_msg(0, "Invalid browse mode set in file space.");+ return nullptr;+}++FileSelectParams *ED_fileselect_get_active_params(const SpaceFile *sfile)+{+ if (!sfile) {+ /* Sometimes called in poll before space type was checked. */+ return nullptr;+ }++ switch (eFileBrowse_Mode(sfile->browse_mode)) {+ case FILE_BROWSE_MODE_FILES:+ return sfile->params;+ case FILE_BROWSE_MODE_ASSETS:+ return reinterpret_cast<FileSelectParams *>(sfile->asset_params);+ }++ BLI_assert_msg(0, "Invalid browse mode set in file space.");+ return nullptr;+}++FileSelectParams *ED_fileselect_get_file_params(const SpaceFile *sfile)+{+ return (sfile->browse_mode == FILE_BROWSE_MODE_FILES) ? sfile->params : nullptr;+}++FileAssetSelectParams *ED_fileselect_get_asset_params(const SpaceFile *sfile)+{+ return (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS) ? sfile->asset_params : nullptr;+}++bool ED_fileselect_is_local_asset_library(const SpaceFile *sfile)+{+ const FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);+ if (asset_params == nullptr) {+ return false;+ }+ return asset_params->asset_library_ref.type == ASSET_LIBRARY_LOCAL;+}++static void fileselect_refresh_asset_params(FileAssetSelectParams *asset_params)+{+ AssetLibraryReference *library = &asset_params->asset_library_ref;+ FileSelectParams *base_params = &asset_params->base_params;+ bUserAssetLibrary *user_library = nullptr;++ /* Ensure valid repository, or fall-back to local one. */+ if (library->type == ASSET_LIBRARY_CUSTOM) {+ BLI_assert(library->custom_library_index >= 0);++ user_library = BKE_preferences_asset_library_find_index(&U, library->custom_library_index);+ if (!user_library || !BKE_preferences_asset_library_is_valid(&U, user_library, false)) {+ library->type = ASSET_LIBRARY_ALL;+ }+ }++ switch (eAssetLibraryType(library->type)) {+ case ASSET_LIBRARY_ESSENTIALS:+ STRNCPY(base_params->dir, asset_system::essentials_directory_path().c_str());+ base_params->type = FILE_ASSET_LIBRARY_ESSENTIALS;+ break;+ case ASSET_LIBRARY_ONLINE_ESSENTIALS:+ STRNCPY(base_params->dir, asset_system::online_essentials_cache_directory_path().c_str());+ base_params->type = FILE_ASSET_LIBRARY_ESSENTIALS;+ break;+ case ASSET_LIBRARY_ALL:+ base_params->dir[0] = '\0';+ base_params->type = FILE_ASSET_LIBRARY_ALL;+ break;+ case ASSET_LIBRARY_LOCAL:+ base_params->dir[0] = '\0';+ base_params->type = FILE_MAIN_ASSET;+ break;+ case ASSET_LIBRARY_CUSTOM:+ BLI_assert(user_library);+ STRNCPY(base_params->dir, user_library->resolved_dirpath);+ base_params->type = (user_library->flag & ASSET_LIBRARY_USE_REMOTE_URL) ?+ FILE_ASSET_LIBRARY_REMOTE :+ FILE_ASSET_LIBRARY;+ break;+ }+}++void fileselect_refresh_params(SpaceFile *sfile)+{+ FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);+ if (asset_params) {+ fileselect_refresh_asset_params(asset_params);+ }+}++bool ED_fileselect_is_file_browser(const SpaceFile *sfile)+{+ return (sfile->browse_mode == FILE_BROWSE_MODE_FILES);+}++bool ED_fileselect_is_asset_browser(const SpaceFile *sfile)+{+ return (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS);+}++asset_system::AssetLibrary *ED_fileselect_active_asset_library_get(const SpaceFile *sfile)+{+ if (!ED_fileselect_is_asset_browser(sfile) || !sfile->files) {+ return nullptr;+ }++ return filelist_asset_library(sfile->files);+}++ID *ED_fileselect_active_asset_get(const SpaceFile *sfile)+{+ if (!ED_fileselect_is_asset_browser(sfile)) {+ return nullptr;+ }++ if (sfile->files == nullptr) {+ return nullptr;+ }++ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const FileDirEntry *file = filelist_file(sfile->files, params->active_file);+ if (file == nullptr) {+ return nullptr;+ }++ return filelist_file_get_id(file);+}++void ED_fileselect_activate_asset_catalog(const SpaceFile *sfile, const bUUID catalog_id)+{+ if (!ED_fileselect_is_asset_browser(sfile)) {+ return;+ }++ FileAssetSelectParams *params = ED_fileselect_get_asset_params(sfile);+ params->asset_catalog_visibility = FILE_SHOW_ASSETS_FROM_CATALOG;+ params->catalog_id = catalog_id;+ WM_main_add_notifier(NC_SPACE | ND_SPACE_ASSET_PARAMS, nullptr);+}++int ED_fileselect_asset_import_method_get(const SpaceFile *sfile, const FileDirEntry *file)+{+ if (!ED_fileselect_is_asset_browser(sfile) || !file->asset) {+ return -1;+ }++ /* First handle the case where the asset system dictates a certain import method. */+ if (file->asset->may_override_import_method() == false) {+ BLI_assert(file->asset->get_import_method().has_value());+ return *file->asset->get_import_method();+ }++ const FileAssetSelectParams *params = ED_fileselect_get_asset_params(sfile);+ eFileAssetImportMethod import_method = eFileAssetImportMethod(params->import_method);++ if (import_method == FILE_ASSET_IMPORT_LINK && file->asset->owner_asset_library().remote_url()) {+ /* Remote library assets cannot be linked. Use #remote_url() here since All and+ * Essentials libraries are already handled above. */+ import_method = FILE_ASSET_IMPORT_FOLLOW_PREFS;+ }++ if (import_method == FILE_ASSET_IMPORT_FOLLOW_PREFS) {+ std::optional asset_import_method = file->asset->get_import_method();+ return asset_import_method ? *asset_import_method : -1;+ }++ switch (import_method) {+ case FILE_ASSET_IMPORT_LINK:+ return ASSET_IMPORT_LINK;+ case FILE_ASSET_IMPORT_APPEND:+ return ASSET_IMPORT_APPEND;+ case FILE_ASSET_IMPORT_APPEND_REUSE:+ return ASSET_IMPORT_APPEND_REUSE;+ case FILE_ASSET_IMPORT_PACK:+ return ASSET_IMPORT_PACK;++ /* Should be handled above already. Break and fail below. */+ case FILE_ASSET_IMPORT_FOLLOW_PREFS:+ break;+ }++ BLI_assert_unreachable();+ return -1;+}++static void on_reload_activate_by_id(SpaceFile *sfile, onReloadFnData custom_data)+{+ ID *asset_id = static_cast<ID *>(custom_data);+ ED_fileselect_activate_by_id(sfile, asset_id, false);+}++void ED_fileselect_activate_by_id(SpaceFile *sfile, ID *asset_id, const bool deferred)+{+ if (!ED_fileselect_is_asset_browser(sfile)) {+ return;+ }++ /* If there are filelist operations running now ("pending" true) or soon ("force reset" true),+ * there is a fair chance that the to-be-activated ID will only be present after these operations+ * have completed. Defer activation until then. */+ if (deferred || filelist_pending(sfile->files) || filelist_needs_force_reset(sfile->files)) {+ /* This should be thread-safe, as this function is likely called from the main thread, and+ * notifiers (which cause a call to the on-reload callback function) are handled on the main+ * thread as well. */+ file_on_reload_callback_register(sfile, on_reload_activate_by_id, asset_id);+ return;+ }++ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileList *files = sfile->files;++ const int file_index = filelist_file_find_id(files, asset_id);+ const FileDirEntry *file = filelist_file_ex(files, file_index, true);+ if (file == nullptr) {+ return;+ }++ params->active_file = file_index;+ filelist_entry_select_set(files, file, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);++ WM_main_add_notifier(NC_ASSET | NA_ACTIVATED, nullptr);+ WM_main_add_notifier(NC_ASSET | NA_SELECTED, nullptr);+}++static void on_reload_select_by_relpath(SpaceFile *sfile, onReloadFnData custom_data)+{+ const char *relative_path = static_cast<const char *>(custom_data);+ ED_fileselect_activate_by_relpath(sfile, relative_path);+}++void ED_fileselect_activate_by_relpath(SpaceFile *sfile, const char *relative_path)+{+ /* If there are filelist operations running now ("pending" true) or soon ("force reset" true),+ * there is a fair chance that the to-be-activated file at relative_path will only be present+ * after these operations have completed. Defer activation until then. */+ FileList *files = sfile->files;+ if (files == nullptr || filelist_pending(files) || filelist_needs_force_reset(files)) {+ /* Casting away the constness of `relative_path` is safe here, because eventually it just ends+ * up in another call to this function, and then it's a const char* again. */+ file_on_reload_callback_register(+ sfile, on_reload_select_by_relpath, const_cast<char *>(relative_path));+ return;+ }++ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ const int num_files_filtered = filelist_files_ensure(files);++ for (int file_index = 0; file_index < num_files_filtered; ++file_index) {+ const FileDirEntry *file = filelist_file(files, file_index);++ if (STREQ(file->relpath, relative_path)) {+ params->active_file = file_index;+ filelist_entry_select_set(files, file, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ }+ }+ WM_main_add_notifier(NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+}++void ED_fileselect_deselect_all(SpaceFile *sfile)+{+ BLI_assert(sfile->files);+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);+ WM_main_add_notifier(NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);+}++/* The subset of FileSelectParams.flag items we store into preferences. Note that FILE_SORT_ALPHA+ * may also be remembered, but only conditionally. */+#define PARAMS_FLAGS_REMEMBERED (FILE_HIDE_DOT)++void ED_fileselect_window_params_get(const wmWindow *win, int r_win_size[2], bool *r_is_maximized)+{+ /* Get DPI/pixel-size independent size to be stored in preferences. */+ WM_window_dpi_set_userdef(win); /* Ensure the DPI is taken from the right window. */++ const int2 win_size = WM_window_native_pixel_size(win);+ r_win_size[0] = win_size[0] / UI_SCALE_FAC;+ r_win_size[1] = win_size[1] / UI_SCALE_FAC;++ *r_is_maximized = WM_window_is_maximized(win);+}++static bool file_select_use_default_display_type(const SpaceFile *sfile)+{+ PropertyRNA *prop;+ return (sfile->op == nullptr) ||+ !(prop = RNA_struct_find_property(sfile->op->ptr, "display_type")) ||+ (RNA_property_enum_get(sfile->op->ptr, prop) == FILE_DEFAULTDISPLAY);+}++static bool file_select_use_default_sort_type(const SpaceFile *sfile)+{+ PropertyRNA *prop;+ return (sfile->op == nullptr) ||+ !(prop = RNA_struct_find_property(sfile->op->ptr, "sort_method")) ||+ (RNA_property_enum_get(sfile->op->ptr, prop) == FILE_SORT_DEFAULT);+}++void ED_fileselect_set_params_from_userdef(SpaceFile *sfile)+{+ wmOperator *op = sfile->op;+ UserDef_FileSpaceData *sfile_udata = &U.file_space_data;++ sfile->browse_mode = FILE_BROWSE_MODE_FILES;++ FileSelectParams *params = fileselect_ensure_updated_file_params(sfile);+ if (!op) {+ return;+ }++ if (sfile_udata->thumbnail_size == 0) {+ /* Saved params are invalid so continue with defaults. */+ return;+ }++ params->thumbnail_size = sfile_udata->thumbnail_size;+ params->details_flags = sfile_udata->details_flags;+ params->filter_id = sfile_udata->filter_id;++ /* Combine flags we take from params with the flags we take from userdef. */+ params->flag = (params->flag & ~PARAMS_FLAGS_REMEMBERED) |+ (sfile_udata->flag & PARAMS_FLAGS_REMEMBERED);++ if (file_select_use_default_display_type(sfile)) {+ params->display = sfile_udata->display_type;+ }+ if (file_select_use_default_sort_type(sfile)) {+ params->sort = sfile_udata->sort_type;+ /* For the default sorting, also take invert flag from userdef. */+ params->flag = (params->flag & ~FILE_SORT_INVERT) | (sfile_udata->flag & FILE_SORT_INVERT);+ }+}++void ED_fileselect_params_to_userdef(SpaceFile *sfile)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ UserDef_FileSpaceData *sfile_udata_new = &U.file_space_data;+ UserDef_FileSpaceData sfile_udata_old = U.file_space_data;++ sfile_udata_new->thumbnail_size = params->thumbnail_size;+ sfile_udata_new->details_flags = params->details_flags;+ sfile_udata_new->flag = params->flag & PARAMS_FLAGS_REMEMBERED;+ sfile_udata_new->filter_id = params->filter_id;++ /* In some rare cases, operators ask for a specific display or sort type (e.g. chronological+ * sorting for "Recover Auto Save"). So the settings are optimized for a specific operation.+ * Don't let that change the userdef memory for more general cases. */+ if (file_select_use_default_display_type(sfile)) {+ sfile_udata_new->display_type = params->display;+ }+ if (file_select_use_default_sort_type(sfile)) {+ sfile_udata_new->sort_type = params->sort;+ /* In this case also remember the invert flag. */+ sfile_udata_new->flag = (sfile_udata_new->flag & ~FILE_SORT_INVERT) |+ (params->flag & FILE_SORT_INVERT);+ }++ /* Tag preferences as dirty if something has changed. */+ if (memcmp(sfile_udata_new, &sfile_udata_old, sizeof(sfile_udata_old)) != 0) {+ U.runtime.is_dirty = true;+ }+}++void fileselect_file_set(bContext *C, SpaceFile *sfile, const int index)+{+ const FileDirEntry *file = filelist_file(sfile->files, index);+ if (file && file->relpath && file->relpath[0] && !(file->typeflag & FILE_TYPE_DIR)) {+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ STRNCPY(params->file, file->relpath);+ if (sfile->op) {+ /* Update the filepath properties of the operator. */+ Main *bmain = CTX_data_main(C);+ file_sfile_to_operator(C, bmain, sfile->op, sfile);+ }+ }+}++int ED_fileselect_layout_numfiles(FileLayout *layout, ARegion *region)+{+ int numfiles;++ /* Values in pixels.+ *+ * - *_item: size of each (row|col), (including padding)+ * - *_view: (x|y) size of the view.+ * - *_over: extra pixels, to take into account, when the fit isn't exact+ * (needed since you may see the end of the previous column and the beginning of the next).+ *+ * Could be more clever and take scrolling into account,+ * but for now don't bother.+ */+ if (layout->flag & FILE_LAYOUT_HOR) {+ const int x_item = layout->tile_w + (2 * layout->tile_border_x);+ const int x_view = int(BLI_rctf_size_x(®ion->v2d.cur));+ const int x_over = x_item - (x_view % x_item);+ numfiles = int(float(x_view + x_over) / float(x_item));+ return numfiles * layout->rows;+ }++ const int y_item = layout->tile_h + (2 * layout->tile_border_y);+ const int y_view = int(BLI_rctf_size_y(®ion->v2d.cur)) - layout->offset_top;+ const int y_over = y_item - (y_view % y_item);+ numfiles = int(float(y_view + y_over) / float(y_item));+ return numfiles * layout->flow_columns;+}++static bool is_inside(int x, int y, int cols, int rows)+{+ return ((x >= 0) && (x < cols) && (y >= 0) && (y < rows));+}++FileSelection ED_fileselect_layout_offset_rect(FileLayout *layout, const rcti *rect)+{+ int colmin, colmax, rowmin, rowmax;+ FileSelection sel;+ sel.first = sel.last = -1;++ if (layout == nullptr) {+ return sel;+ }++ colmin = (rect->xmin) / (layout->tile_w + 2 * layout->tile_border_x);+ rowmin = (rect->ymin - layout->offset_top - layout->list_padding_top) /+ (layout->tile_h + 2 * layout->tile_border_y);+ colmax = (rect->xmax) / (layout->tile_w + 2 * layout->tile_border_x);+ rowmax = (rect->ymax - layout->offset_top - layout->list_padding_top) /+ (layout->tile_h + 2 * layout->tile_border_y);++ if (is_inside(colmin, rowmin, layout->flow_columns, layout->rows) ||+ is_inside(colmax, rowmax, layout->flow_columns, layout->rows))+ {+ CLAMP(colmin, 0, layout->flow_columns - 1);+ CLAMP(rowmin, 0, layout->rows - 1);+ CLAMP(colmax, 0, layout->flow_columns - 1);+ CLAMP(rowmax, 0, layout->rows - 1);+ }++ if ((colmin > layout->flow_columns - 1) || (rowmin > layout->rows - 1)) {+ sel.first = -1;+ }+ else {+ if (layout->flag & FILE_LAYOUT_HOR) {+ sel.first = layout->rows * colmin + rowmin;+ }+ else {+ sel.first = colmin + layout->flow_columns * rowmin;+ }+ }+ if ((colmax > layout->flow_columns - 1) || (rowmax > layout->rows - 1)) {+ sel.last = -1;+ }+ else {+ if (layout->flag & FILE_LAYOUT_HOR) {+ sel.last = layout->rows * colmax + rowmax;+ }+ else {+ sel.last = colmax + layout->flow_columns * rowmax;+ }+ }++ return sel;+}++int ED_fileselect_layout_offset(FileLayout *layout, int x, int y)+{+ int offsetx, offsety;+ int active_file;++ if (layout == nullptr) {+ return -1;+ }++ offsetx = (x) / (layout->tile_w + 2 * layout->tile_border_x);+ offsety = (y - layout->offset_top - layout->list_padding_top) /+ (layout->tile_h + 2 * layout->tile_border_y);++ if (offsetx > layout->flow_columns - 1) {+ return -1;+ }+ if (offsety > layout->rows - 1) {+ return -1;+ }++ if (layout->flag & FILE_LAYOUT_HOR) {+ active_file = layout->rows * offsetx + offsety;+ }+ else {+ active_file = offsetx + layout->flow_columns * offsety;+ }+ return active_file;+}++void ED_fileselect_layout_maskrect(const FileLayout *layout, const View2D *v2d, rcti *r_rect)+{+ *r_rect = v2d->mask;+ r_rect->ymax -= layout->offset_top;+}++bool ED_fileselect_layout_is_inside_pt(const FileLayout *layout, const View2D *v2d, int x, int y)+{+ rcti maskrect;+ ED_fileselect_layout_maskrect(layout, v2d, &maskrect);+ return BLI_rcti_isect_pt(&maskrect, x, y);+}++bool ED_fileselect_layout_isect_rect(const FileLayout *layout,+ const View2D *v2d,+ const rcti *rect,+ rcti *r_dst)+{+ rcti maskrect;+ ED_fileselect_layout_maskrect(layout, v2d, &maskrect);+ return BLI_rcti_isect(&maskrect, rect, r_dst);+}++void ED_fileselect_layout_tilepos(const FileLayout *layout, int tile, int *x, int *y)+{+ if (layout->flag == FILE_LAYOUT_HOR) {+ *x = layout->tile_border_x ++ (tile / layout->rows) * (layout->tile_w + 2 * layout->tile_border_x);+ *y = layout->offset_top + layout->list_padding_top + layout->tile_border_y ++ (tile % layout->rows) * (layout->tile_h + 2 * layout->tile_border_y);+ }+ else {+ *x = layout->tile_border_x ++ ((tile) % layout->flow_columns) * (layout->tile_w + 2 * layout->tile_border_x);+ *y = layout->offset_top + layout->list_padding_top + layout->tile_border_y ++ ((tile) / layout->flow_columns) * (layout->tile_h + 2 * layout->tile_border_y);+ }+}++bool file_attribute_column_header_is_inside(const View2D *v2d,+ const FileLayout *layout,+ int x,+ int y)+{+ rcti header_rect = v2d->mask;+ header_rect.ymin = header_rect.ymax - layout->attribute_column_header_h;+ return BLI_rcti_isect_pt(&header_rect, x, y);+}++bool file_attribute_column_type_enabled(const FileSelectParams *params,+ FileAttributeColumnType column,+ const FileLayout *layout)+{+ switch (column) {+ case COLUMN_NAME:+ /* Always enabled */+ return true;+ case COLUMN_DATETIME:+ return ((params->details_flags & FILE_DETAILS_DATETIME) != 0) &&+ !FILE_LAYOUT_HIDE_DATE(layout);+ case COLUMN_SIZE:+ return ((params->details_flags & FILE_DETAILS_SIZE) != 0) && !FILE_LAYOUT_HIDE_SIZE(layout);+ default:+ return false;+ }+}++FileAttributeColumnType file_attribute_column_type_find_isect(const View2D *v2d,+ const FileSelectParams *params,+ FileLayout *layout,+ int x)+{+ float mx, my;+ int offset_tile;++ ui::view2d_region_to_view(v2d, x, v2d->mask.ymax - layout->offset_top - 1, &mx, &my);+ offset_tile = ED_fileselect_layout_offset(+ layout, int(v2d->tot.xmin + mx), int(v2d->tot.ymax - my));+ if (offset_tile > -1) {+ int tile_x, tile_y;+ int pos_x = 0;+ int rel_x; /* x relative to the hovered tile */++ ED_fileselect_layout_tilepos(layout, offset_tile, &tile_x, &tile_y);+ /* Column header drawing doesn't use left tile border, so subtract it. */+ rel_x = mx - (tile_x - layout->tile_border_x);++ for (FileAttributeColumnType column = FileAttributeColumnType(0);+ column < ATTRIBUTE_COLUMN_MAX;+ column = FileAttributeColumnType(int(column) + 1))+ {+ if (!file_attribute_column_type_enabled(params, column, layout)) {+ continue;+ }+ const int width = layout->attribute_columns[column].width;++ if (IN_RANGE(rel_x, pos_x, pos_x + width)) {+ return column;+ }++ pos_x += width;+ }+ }++ return COLUMN_NONE;+}++float file_string_width(const char *str)+{+ const uiStyle *style = ui::style_get();+ ui::fontstyle_set(&style->widget);+ return BLF_width(style->widget.uifont_id, str, BLF_DRAW_STR_DUMMY_MAX);+}++float file_font_pointsize()+{+ const uiStyle *style = ui::style_get();+ return ui::fontstyle_height_max(&style->widget);+}++static void file_attribute_columns_widths(const FileSelectParams *params, FileLayout *layout)+{+ FileAttributeColumn *columns = layout->attribute_columns;+ const int pad = ATTRIBUTE_COLUMN_PADDING * 2;+ const bool compact = FILE_LAYOUT_COMPACT(layout);++ for (int i = 0; i < ATTRIBUTE_COLUMN_MAX; i++) {+ layout->attribute_columns[i].width = 0;+ }++ /* Biggest possible reasonable values... */+ if (file_attribute_column_type_enabled(params, COLUMN_DATETIME, layout)) {+ const char *lang = BLT_lang_get();+ constexpr tm test = {59, 59, 3, 30, 8, 199, 6, 365, 0}; /* September 30, 2099 03:59:59 */+ std::string modified_s = compact ?+ date_string::date(test, lang) :+ date_string::datetime(test,+ lang,+ date_string::DateFormat(U.date_format),+ date_string::TimeFormat(U.time_format));+ int width = file_string_width(modified_s.c_str());+ columns[COLUMN_DATETIME].width = width + pad + (0.5f * UI_UNIT_X);+ }+ if (file_attribute_column_type_enabled(params, COLUMN_SIZE, layout)) {+ columns[COLUMN_SIZE].width = file_string_width(compact ? "369G" : "098.7 MiB") + pad;+ }++ if (params->display == FILE_IMGDISPLAY) {+ columns[COLUMN_NAME].width = (float(params->thumbnail_size) / 8.0f) * UI_UNIT_X;+ }+ /* Name column uses remaining width */+ else {+ int remwidth = layout->tile_w;+ for (FileAttributeColumnType column_type =+ FileAttributeColumnType(int(ATTRIBUTE_COLUMN_MAX) - 1);+ column_type >= 0;+ column_type = FileAttributeColumnType(int(column_type) - 1))+ {+ if ((column_type == COLUMN_NAME) ||+ !file_attribute_column_type_enabled(params, column_type, layout))+ {+ continue;+ }+ remwidth -= columns[column_type].width;+ }+ columns[COLUMN_NAME].width = remwidth;+ }+}++static void file_attribute_columns_init(const FileSelectParams *params, FileLayout *layout)+{+ file_attribute_columns_widths(params, layout);++ layout->attribute_columns[COLUMN_NAME].name = N_("Name");+ layout->attribute_columns[COLUMN_NAME].sort_type = FILE_SORT_ALPHA;+ layout->attribute_columns[COLUMN_NAME].text_align = ui::UI_STYLE_TEXT_LEFT;++ const bool compact = FILE_LAYOUT_COMPACT(layout);+ layout->attribute_columns[COLUMN_DATETIME].name = compact ? N_("Date") : N_("Date Modified");++ layout->attribute_columns[COLUMN_DATETIME].sort_type = FILE_SORT_TIME;+ layout->attribute_columns[COLUMN_DATETIME].text_align = ui::UI_STYLE_TEXT_LEFT;+ layout->attribute_columns[COLUMN_SIZE].name = N_("Size");+ layout->attribute_columns[COLUMN_SIZE].sort_type = FILE_SORT_SIZE;+ layout->attribute_columns[COLUMN_SIZE].text_align = ui::UI_STYLE_TEXT_RIGHT;+}++void ED_fileselect_init_layout(SpaceFile *sfile, ARegion *region)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FileLayout *layout = nullptr;+ View2D *v2d = ®ion->v2d;+ int numfiles;++ if (sfile->layout == nullptr) {+ sfile->layout = MEM_new_zeroed<FileLayout>("file_layout");+ sfile->layout->dirty = true;+ }+ else if (sfile->layout->dirty == false) {+ return;+ }++ numfiles = filelist_files_ensure(sfile->files);+ layout = sfile->layout;+ /* Slightly increased than font height for padding. */+ layout->text_line_height = file_font_pointsize();+ layout->text_lines_count = 1;+ layout->offset_top = 0;++ if (params->display == FILE_IMGDISPLAY) {+ /* More compact spacing for asset browser. */+ const float pad_fac = ED_fileselect_is_asset_browser(sfile) ? 0.15f : 0.3f;+ /* Matches preview_tile_size_x()/_y() by default. */+ layout->prv_w = (float(params->thumbnail_size) / 20.0f) * UI_UNIT_X;+ layout->prv_h = (float(params->thumbnail_size) / 20.0f) * UI_UNIT_Y;+ layout->tile_border_x = pad_fac * UI_UNIT_X;+ layout->tile_border_y = pad_fac * UI_UNIT_X;+ layout->list_padding_top = 0;+ layout->prv_border_x = pad_fac * UI_UNIT_X;+ layout->prv_border_y = pad_fac * UI_UNIT_Y;+ layout->tile_w = layout->prv_w + 2 * layout->prv_border_x;+ layout->text_lines_count = 2;+ layout->tile_h = layout->prv_h + 2 * layout->prv_border_y ++ layout->text_lines_count * layout->text_line_height;+ layout->width = int(BLI_rctf_size_x(&v2d->cur) - 2 * layout->tile_border_x);+ layout->flow_columns = layout->width / (layout->tile_w + 2 * layout->tile_border_x);+ layout->attribute_column_header_h = 0;+ layout->offset_top = 0;+ if (layout->flow_columns > 0) {+ layout->rows = divide_ceil_u(numfiles, layout->flow_columns);+ }+ else {+ layout->flow_columns = 1;+ layout->rows = numfiles;+ }+ layout->height = sfile->layout->rows * (layout->tile_h + 2 * layout->tile_border_y) ++ layout->tile_border_y * 2 - layout->offset_top;+ layout->flag = FILE_LAYOUT_VER;+ }+ else if (params->display == FILE_VERTICALDISPLAY) {+ int rowcount;++ layout->prv_w = ICON_DEFAULT_WIDTH_SCALE;+ layout->prv_h = ICON_DEFAULT_HEIGHT_SCALE;+ layout->tile_border_x = 0.4f * UI_UNIT_X;+ layout->tile_border_y = 0.05f * UI_UNIT_Y;+ layout->list_padding_top = 2 * layout->tile_border_y;+ layout->tile_h = round_fl_to_int(layout->text_line_height * 1.4f);+ layout->width = int(BLI_rctf_size_x(&v2d->cur) - 2 * layout->tile_border_x);+ layout->tile_w = layout->width;+ layout->flow_columns = 1;+ layout->attribute_column_header_h = layout->tile_h * 1.2f + 2 * layout->tile_border_y;+ layout->offset_top = layout->attribute_column_header_h;+ rowcount = int(BLI_rctf_size_y(&v2d->cur) - layout->offset_top -+ 2 * layout->list_padding_top) /+ (layout->tile_h + 2 * layout->tile_border_y);+ file_attribute_columns_init(params, layout);++ layout->rows = std::max(rowcount, numfiles);++ /* layout->rows can be zero if a very small area is changed to a File Browser. #124168. */++ layout->height = sfile->layout->rows * (layout->tile_h + 2 * layout->tile_border_y) ++ layout->list_padding_top * 2 + layout->offset_top;+ layout->flag = FILE_LAYOUT_VER;+ }+ else if (params->display == FILE_HORIZONTALDISPLAY) {+ layout->prv_w = params->list_thumbnail_size * UI_SCALE_FAC;+ layout->prv_h = params->list_thumbnail_size * UI_SCALE_FAC;+ layout->tile_border_x = 0.4f * UI_UNIT_X;+ layout->tile_border_y = 0.05f * UI_UNIT_Y;+ layout->list_padding_top = 2 * layout->tile_border_y;+ layout->tile_h = std::max(round_fl_to_int(layout->text_line_height * 1.4f), layout->prv_h);+ layout->attribute_column_header_h = 0;+ layout->offset_top = layout->attribute_column_header_h;+ layout->height = int(BLI_rctf_size_y(&v2d->cur) - 2 * layout->tile_border_y);+ /* Padding by full scroll-bar H is too much, can overlap tile border Y. */+ layout->rows = (layout->height - V2D_SCROLL_HEIGHT + layout->tile_border_y) /+ (layout->tile_h + 2 * layout->tile_border_y);++ layout->tile_w = params->list_column_size * UI_SCALE_FAC;+ file_attribute_columns_init(params, layout);++ if (layout->rows > 0) {+ layout->flow_columns = divide_ceil_u(numfiles, layout->rows);+ }+ else {+ layout->rows = 1;+ layout->flow_columns = numfiles;+ }+ layout->width = (numfiles > 0) ? (sfile->layout->flow_columns *+ (layout->tile_w + 2 * layout->tile_border_x) ++ layout->tile_border_x * 2) :+ int(BLI_rctf_size_x(&v2d->cur) - 2 * layout->tile_border_x);+ layout->flag = FILE_LAYOUT_HOR;+ }+ layout->dirty = false;++ if (sfile->runtime->banners_state.any_visible) {+ layout->offset_top += UI_UNIT_Y + 2 * sfile->layout->tile_border_y;+ }+}++FileLayout *ED_fileselect_get_layout(SpaceFile *sfile, ARegion *region)+{+ if (!sfile->layout) {+ ED_fileselect_init_layout(sfile, region);+ }+ return sfile->layout;+}++void ED_file_change_dir_ex(bContext *C, ScrArea *area)+{+ /* May happen when manipulating non-active spaces. */+ if (area->spacetype != SPACE_FILE) [[unlikely]] {+ return;+ }+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ if (params) {+ wmWindowManager *wm = CTX_wm_manager(C);+ ED_fileselect_clear(wm, sfile);++ /* Clear search string, it is very rare to want to keep that filter while changing dir,+ * and usually very annoying to keep it actually! */+ params->filter_search[0] = '\0';+ params->active_file = -1;++ if (!filelist_is_dir(sfile->files, params->dir)) {+ STRNCPY(params->dir, filelist_dir(sfile->files));+ /* could return but just refresh the current dir */+ }+ filelist_setdir(sfile->files, params->dir);++ if (folderlist_clear_next(sfile)) {+ folderlist_free(sfile->folders_next);+ }++ folderlist_pushdir(sfile->folders_prev, params->dir);++ file_draw_check_ex(C, area);+ }+}++void ED_file_change_dir(bContext *C)+{+ ScrArea *area = CTX_wm_area(C);+ ED_file_change_dir_ex(C, area);+}++void file_select_deselect_all(SpaceFile *sfile, const eDirEntry_SelectFlag flag)+{+ FileSelection sel;+ sel.first = 0;+ sel.last = filelist_files_ensure(sfile->files) - 1;++ filelist_entries_select_index_range_set(sfile->files, &sel, FILE_SEL_REMOVE, flag, CHECK_ALL);+}++int file_select_match(SpaceFile *sfile, const char *pattern, char *matched_file)+{+ int match = 0;++ int n = filelist_files_ensure(sfile->files);++ /* select any file that matches the pattern, this includes exact match+ * if the user selects a single file by entering the filename+ */+ for (int i = 0; i < n; i++) {+ const char *relpath = filelist_entry_get_relpath(sfile->files, i);+ /* Do not check whether file is a file or dir here! Causes: #44243+ * (we do accept directories at this stage). */+ if (fnmatch(pattern, relpath, 0) == 0) {+ filelist_entry_select_index_set(sfile->files, i, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ if (!match) {+ BLI_strncpy(matched_file, relpath, FILE_MAX);+ }+ match++;+ }+ }++ return match;+}++int autocomplete_directory(bContext *C, char *str, void * /*arg_v*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ int match = AUTOCOMPLETE_NO_MATCH;++ /* search if str matches the beginning of name */+ if (str[0] && sfile->files) {+ char dirname[FILE_MAX];++ DIR *dir;+ dirent *de;++ BLI_path_split_dir_part(str, dirname);++ BLI_assert(!BLI_path_is_rel(dirname));+ dir = opendir(dirname);++ if (dir) {+ ui::AutoComplete *autocpl = ui::autocomplete_begin(str, FILE_MAX);++ while ((de = readdir(dir)) != nullptr) {+ if (FILENAME_IS_CURRPAR(de->d_name)) {+ /* pass */+ }+ else {+ char dirpath[FILE_MAX];+ BLI_stat_t status;++ BLI_path_join(dirpath, dirname, de->d_name);++ if (BLI_stat(dirpath, &status) == 0) {+ if (S_ISDIR(status.st_mode)) { /* is subdir */+ autocomplete_update_name(autocpl, dirpath);+ }+ }+ }+ }+ closedir(dir);++ match = autocomplete_end(autocpl, str);+ if (match == AUTOCOMPLETE_FULL_MATCH) {+ BLI_path_slash_ensure(MutableCStr(str, FILE_MAX));+ }+ }+ }++ return match;+}++int autocomplete_file(bContext *C, char *str, void * /*arg_v*/)+{+ SpaceFile *sfile = CTX_wm_space_file(C);+ int match = AUTOCOMPLETE_NO_MATCH;++ /* search if str matches the beginning of name */+ if (str[0] && sfile->files) {+ ui::AutoComplete *autocpl = ui::autocomplete_begin(str, FILE_MAX);+ int nentries = filelist_files_ensure(sfile->files);++ for (int i = 0; i < nentries; i++) {+ const char *relpath = filelist_entry_get_relpath(sfile->files, i);+ autocomplete_update_name(autocpl, relpath);+ }+ match = autocomplete_end(autocpl, str);+ }++ return match;+}++void ED_fileselect_clear(wmWindowManager *wm, SpaceFile *sfile)+{+ /* Only null in rare cases, see: #29734. */+ if (sfile->files) {+ filelist_readjob_stop(sfile->files, wm);+ filelist_freelib(sfile->files);+ filelist_clear(sfile->files);+ }++ if (FileSelectParams *params = ED_fileselect_get_active_params(sfile)) {+ params->highlight_file = -1;+ }+ WM_main_add_notifier(NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+}++void ED_fileselect_clear_main_assets(wmWindowManager *wm, SpaceFile *sfile)+{+ /* Only null in rare cases, see: #29734. */+ if (sfile->files) {+ filelist_readjob_stop(sfile->files, wm);+ filelist_freelib(sfile->files);+ filelist_tag_force_reset_mainfiles(sfile->files);+ filelist_tag_reload_asset_library(sfile->files);+ filelist_clear_from_reset_tag(sfile->files);+ }++ if (FileSelectParams *params = ED_fileselect_get_active_params(sfile)) {+ params->highlight_file = -1;+ }+ WM_main_add_notifier(NC_SPACE | ND_SPACE_FILE_LIST, nullptr);+}++void ED_fileselect_exit(wmWindowManager *wm, SpaceFile *sfile)+{+ if (!sfile) {+ return;+ }+ if (sfile->op) {+ ED_fileselect_params_to_userdef(sfile);+ WM_event_fileselect_event(wm, sfile->op, EVT_FILESELECT_EXTERNAL_CANCEL);+ sfile->op = nullptr;+ }++ folder_history_list_free(sfile);++ if (sfile->files) {+ ED_fileselect_clear(wm, sfile);+ filelist_free(sfile->files);+ sfile->files = nullptr;+ }+}++void file_params_smoothscroll_timer_clear(wmWindowManager *wm, wmWindow *win, SpaceFile *sfile)+{+ WM_event_timer_remove(wm, win, sfile->smoothscroll_timer);+ sfile->smoothscroll_timer = nullptr;+}++void file_params_invoke_rename_postscroll(wmWindowManager *wm, wmWindow *win, SpaceFile *sfile)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ params->rename_flag = FILE_PARAMS_RENAME_POSTSCROLL_PENDING;++ if (sfile->smoothscroll_timer != nullptr) {+ file_params_smoothscroll_timer_clear(wm, win, sfile);+ }+ sfile->smoothscroll_timer = WM_event_timer_add(wm, win, TIMER1, 1.0 / 1000.0);+ sfile->scroll_offset = 0;+}++void file_params_rename_end(wmWindowManager *wm,+ wmWindow *win,+ SpaceFile *sfile,+ const FileDirEntry *rename_file)+{+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);++ filelist_entry_select_set(+ sfile->files, rename_file, FILE_SEL_REMOVE, FILE_SEL_EDITING, CHECK_ALL);++ /* Ensure smooth-scroll timer is active, even if not needed, because that way rename state is+ * handled properly. */+ file_params_invoke_rename_postscroll(wm, win, sfile);+ /* Also always activate the rename file, even if renaming was canceled. */+ file_params_renamefile_activate(sfile, params);+}++void file_params_renamefile_clear(FileSelectParams *params)+{+ params->renamefile[0] = '\0';+ params->rename_id = nullptr;+ params->rename_flag = eFileSel_Params_RenameFlag{};+}++static int file_params_find_renamed(const FileSelectParams *params, FileList *filelist)+{+ /* Find the file either through the local ID/asset it represents or its relative path. */+ return (params->rename_id != nullptr) ? filelist_file_find_id(filelist, params->rename_id) :+ filelist_file_find_path(filelist, params->renamefile);+}++void file_params_renamefile_activate(SpaceFile *sfile, FileSelectParams *params)+{+ BLI_assert(params->rename_flag != 0);++ if ((params->rename_flag & (FILE_PARAMS_RENAME_ACTIVE | FILE_PARAMS_RENAME_POSTSCROLL_ACTIVE)) !=+ 0)+ {+ return;+ }++ BLI_assert(params->renamefile[0] != '\0' || params->rename_id != nullptr);++ int idx = file_params_find_renamed(params, sfile->files);+ if (idx >= 0) {+ FileDirEntry *file = filelist_file(sfile->files, idx);+ BLI_assert(file != nullptr);++ params->active_file = idx;+ filelist_entry_select_set(sfile->files, file, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);++ if ((params->rename_flag & FILE_PARAMS_RENAME_PENDING) != 0) {+ filelist_entry_select_set(sfile->files, file, FILE_SEL_ADD, FILE_SEL_EDITING, CHECK_ALL);+ params->rename_flag = FILE_PARAMS_RENAME_ACTIVE;+ }+ else if ((params->rename_flag & FILE_PARAMS_RENAME_POSTSCROLL_PENDING) != 0) {+ /* file_select_deselect_all() will resort and re-filter, so `idx` will probably have changed.+ * Need to get the correct #FileDirEntry again. */+ file_select_deselect_all(sfile, FILE_SEL_SELECTED);+ idx = file_params_find_renamed(params, sfile->files);+ file = filelist_file(sfile->files, idx);+ filelist_entry_select_set(sfile->files, file, FILE_SEL_ADD, FILE_SEL_SELECTED, CHECK_ALL);+ params->active_file = idx;+ file_params_renamefile_clear(params);+ params->rename_flag = FILE_PARAMS_RENAME_POSTSCROLL_ACTIVE;+ }+ }+ /* File listing is now asynchronous, only reset renaming if matching entry is not found+ * when file listing is not done. */+ else if (filelist_is_ready(sfile->files)) {+ file_params_renamefile_clear(params);+ }+}++ScrArea *ED_fileselect_handler_area_find(const wmWindow *win, const wmOperator *file_operator)+{+ bScreen *screen = WM_window_get_active_screen(win);++ ED_screen_areas_iter (win, screen, area) {+ if (area->spacetype == SPACE_FILE) {+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();++ if (sfile->op == file_operator) {+ return area;+ }+ }+ }++ return nullptr;+}++ScrArea *ED_fileselect_handler_area_find_any_with_op(const wmWindow *win)+{+ const bScreen *screen = WM_window_get_active_screen(win);++ ED_screen_areas_iter (win, screen, area) {+ if (area->spacetype != SPACE_FILE) {+ continue;+ }++ const SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ if (sfile->op) {+ return area;+ }+ }++ return nullptr;+}++void ED_fileselect_ensure_default_filepath(bContext *C, wmOperator *op, const char *extension)+{+ if (!RNA_struct_property_is_set_ex(op->ptr, "filepath", false)) {+ Main *bmain = CTX_data_main(C);+ char filepath[FILE_MAX];+ const char *blendfile_path = BKE_main_blendfile_path(bmain);++ if (blendfile_path[0] == '\0') {+ STRNCPY(filepath, DATA_("Untitled"));+ }+ else {+ STRNCPY(filepath, blendfile_path);+ }++ BLI_path_extension_replace(filepath, extension);+ RNA_string_set(op->ptr, "filepath", filepath);+ }+}++Vector<std::string> ED_fileselect_selected_files_full_paths(const SpaceFile *sfile)+{+ Vector<std::string> paths;+ char path[FILE_MAX_LIBEXTRA];+ for (const int i : IndexRange(filelist_files_ensure(sfile->files))) {+ if (filelist_entry_is_selected(sfile->files, i)) {+ const FileDirEntry *entry = filelist_file(sfile->files, i);+ filelist_file_get_full_path(sfile->files, entry, path);+ paths.append(path);+ }+ }+ return paths;+}++} // namespace blenderdiff --git a/ui/space_file/folder_history.cc b/ui/space_file/folder_history.ccnew file mode 100644index 0000000..7b63f33--- /dev/null+++ b/ui/space_file/folder_history.cc@@ -0,0 +1,203 @@+/* SPDX-FileCopyrightText: 2007 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ *+ * Storage for a list of folders for history backward and forward navigation.+ */++#include <cstring>++#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"++#include "DNA_space_types.h"++#include "ED_fileselect.hh"++#include "MEM_guardedalloc.h"++#include "file_intern.hh"++namespace blender {++/* -------------------------------------------------------------------- */+/** \name FOLDERLIST (previous/next)+ * \{ */++struct FolderList {+ FolderList *next, *prev;+ char *foldername;+};++void folderlist_popdir(ListBaseT<FolderList> *folderlist, char *dir)+{+ const char *prev_dir;+ FolderList *folder;+ folder = folderlist->last();++ if (folder) {+ /* remove the current directory */+ MEM_delete(folder->foldername);+ BLI_freelinkN(folderlist, folder);++ folder = folderlist->last();+ if (folder) {+ prev_dir = folder->foldername;+ BLI_strncpy(dir, prev_dir, FILE_MAXDIR);+ }+ }+ /* Delete the folder next or use set-directory directly before PREVIOUS OP. */+}++void folderlist_pushdir(ListBaseT<FolderList> *folderlist, const char *dir)+{+ if (!dir[0]) {+ return;+ }++ FolderList *folder, *previous_folder;+ previous_folder = folderlist->last();++ /* check if already exists */+ if (previous_folder && previous_folder->foldername) {+ if (BLI_path_cmp(previous_folder->foldername, dir) == 0) {+ return;+ }+ }++ /* create next folder element */+ folder = MEM_new_zeroed<FolderList>(__func__);+ folder->foldername = BLI_strdup(dir);++ /* add it to the end of the list */+ BLI_addtail(folderlist, folder);+}++const char *folderlist_peeklastdir(ListBaseT<FolderList> *folderlist)+{+ FolderList *folder;++ if (!folderlist->last()) {+ return nullptr;+ }++ folder = folderlist->last();+ return folder->foldername;+}++bool folderlist_clear_next(SpaceFile *sfile)+{+ const FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ FolderList *folder;++ /* if there is no folder_next there is nothing we can clear */+ if (sfile->folders_next->is_empty()) {+ return false;+ }++ /* if previous_folder, next_folder or refresh_folder operators are executed+ * it doesn't clear folder_next */+ folder = sfile->folders_prev->last();+ if ((!folder) || (BLI_path_cmp(folder->foldername, params->dir) == 0)) {+ return false;+ }++ /* eventually clear flist->folders_next */+ return true;+}++void folderlist_free(ListBaseT<FolderList> *folderlist)+{+ if (folderlist) {+ for (FolderList &folder : folderlist->items_mutable()) {+ MEM_delete(folder.foldername);+ MEM_delete(&folder);+ }+ folderlist->clear_no_delete();+ }+}++static ListBaseT<FolderList> folderlist_duplicate(ListBaseT<FolderList> *folderlist)+{+ ListBaseT<FolderList> folderlistn = {nullptr};++ BLI_duplicatelist(&folderlistn, folderlist);++ for (FolderList &folder : folderlistn) {+ folder.foldername = MEM_dupalloc(folder.foldername);+ }+ return folderlistn;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Folder-History (wraps/owns file list above)+ * \{ */++static FileFolderHistory *folder_history_find(const SpaceFile *sfile, eFileBrowse_Mode browse_mode)+{+ for (FileFolderHistory &history : sfile->folder_histories) {+ if (history.browse_mode == browse_mode) {+ return &history;+ }+ }++ return nullptr;+}++void folder_history_list_ensure_for_active_browse_mode(SpaceFile *sfile)+{+ FileFolderHistory *history = folder_history_find(sfile, eFileBrowse_Mode(sfile->browse_mode));++ if (!history) {+ history = MEM_new<FileFolderHistory>(__func__);+ history->browse_mode = sfile->browse_mode;+ BLI_addtail(&sfile->folder_histories, history);+ }++ sfile->folders_next = &history->folders_next;+ sfile->folders_prev = &history->folders_prev;+}++static void folder_history_entry_free(SpaceFile *sfile, FileFolderHistory *history)+{+ if (sfile->folders_prev == &history->folders_prev) {+ sfile->folders_prev = nullptr;+ }+ if (sfile->folders_next == &history->folders_next) {+ sfile->folders_next = nullptr;+ }+ folderlist_free(&history->folders_prev);+ folderlist_free(&history->folders_next);+ BLI_freelinkN(&sfile->folder_histories, history);+}++void folder_history_list_free(SpaceFile *sfile)+{+ for (FileFolderHistory &history : sfile->folder_histories.items_mutable()) {+ folder_history_entry_free(sfile, &history);+ }+}++ListBaseT<FileFolderHistory> folder_history_list_duplicate(ListBaseT<FileFolderHistory> *listbase)+{+ ListBaseT<FileFolderHistory> histories = {nullptr};++ for (FileFolderHistory &history : *listbase) {+ FileFolderHistory *history_new = MEM_dupalloc(&history);+ history_new->folders_prev = folderlist_duplicate(&history.folders_prev);+ history_new->folders_next = folderlist_duplicate(&history.folders_next);+ BLI_addtail(&histories, history_new);+ }++ return histories;+}++/** \} */++} // namespace blenderdiff --git a/ui/space_file/fsmenu.cc b/ui/space_file/fsmenu.ccnew file mode 100644index 0000000..b75f6bb--- /dev/null+++ b/ui/space_file/fsmenu.cc@@ -0,0 +1,571 @@+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include <algorithm>+#include <cstdio>+#include <cstring>++#include "MEM_guardedalloc.h"++#include "BLI_fileops.hh"+#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_string_utils.hh"+#include "BLI_utildefines.h"++#include "DNA_userdef_types.h"++#include "BLT_translation.hh"++#include "BKE_appdir.hh"++#include "ED_fileselect.hh"++#include "UI_resources.hh"++#include "fsmenu.hh" /* include ourselves */++namespace blender {++/* FSMENU HANDLING */++struct FSMenu {+ FSMenuEntry *fsmenu_system;+ FSMenuEntry *fsmenu_system_bookmarks;+ FSMenuEntry *fsmenu_bookmarks;+ FSMenuEntry *fsmenu_recent;+ FSMenuEntry *fsmenu_other;+};++static FSMenu *g_fsmenu = nullptr;++FSMenu *ED_fsmenu_get()+{+ if (!g_fsmenu) {+ g_fsmenu = MEM_new_zeroed<FSMenu>(__func__);+ }+ return g_fsmenu;+}++FSMenuEntry *ED_fsmenu_get_category(FSMenu *fsmenu, FSMenuCategory category)+{+ FSMenuEntry *fsm_head = nullptr;++ switch (category) {+ case FS_CATEGORY_SYSTEM:+ fsm_head = fsmenu->fsmenu_system;+ break;+ case FS_CATEGORY_SYSTEM_BOOKMARKS:+ fsm_head = fsmenu->fsmenu_system_bookmarks;+ break;+ case FS_CATEGORY_BOOKMARKS:+ fsm_head = fsmenu->fsmenu_bookmarks;+ break;+ case FS_CATEGORY_RECENT:+ fsm_head = fsmenu->fsmenu_recent;+ break;+ case FS_CATEGORY_OTHER:+ fsm_head = fsmenu->fsmenu_other;+ break;+ }+ return fsm_head;+}++void ED_fsmenu_set_category(FSMenu *fsmenu, FSMenuCategory category, FSMenuEntry *fsm_head)+{+ switch (category) {+ case FS_CATEGORY_SYSTEM:+ fsmenu->fsmenu_system = fsm_head;+ break;+ case FS_CATEGORY_SYSTEM_BOOKMARKS:+ fsmenu->fsmenu_system_bookmarks = fsm_head;+ break;+ case FS_CATEGORY_BOOKMARKS:+ fsmenu->fsmenu_bookmarks = fsm_head;+ break;+ case FS_CATEGORY_RECENT:+ fsmenu->fsmenu_recent = fsm_head;+ break;+ case FS_CATEGORY_OTHER:+ fsmenu->fsmenu_other = fsm_head;+ break;+ }+}++int ED_fsmenu_get_nentries(FSMenu *fsmenu, FSMenuCategory category)+{+ FSMenuEntry *fsm_iter;+ int count = 0;++ for (fsm_iter = ED_fsmenu_get_category(fsmenu, category); fsm_iter; fsm_iter = fsm_iter->next) {+ count++;+ }++ return count;+}++FSMenuEntry *ED_fsmenu_get_entry(FSMenu *fsmenu, FSMenuCategory category, int idx)+{+ FSMenuEntry *fsm_iter;++ for (fsm_iter = ED_fsmenu_get_category(fsmenu, category); fsm_iter && idx;+ fsm_iter = fsm_iter->next)+ {+ idx--;+ }++ return fsm_iter;+}++char *ED_fsmenu_entry_get_path(FSMenuEntry *fsentry)+{+ return fsentry->path;+}++void ED_fsmenu_entry_set_path(FSMenuEntry *fsentry, const char *path)+{+ if ((!fsentry->path || !path || !STREQ(path, fsentry->path)) && (fsentry->path != path)) {+ char tmp_name[FILE_MAXFILE];++ MEM_SAFE_DELETE(fsentry->path);++ fsentry->path = (path && path[0]) ? BLI_strdup(path) : nullptr;++ const std::optional<std::string> user_config_dir = BKE_appdir_folder_id_create(+ BLENDER_USER_CONFIG, nullptr);++ if (user_config_dir.has_value()) {+ BLI_path_join(tmp_name, user_config_dir->c_str(), BLENDER_BOOKMARK_FILE);+ fsmenu_write_file(ED_fsmenu_get(), tmp_name);+ }+ }+}++int ED_fsmenu_entry_get_icon(FSMenuEntry *fsentry)+{+ return (fsentry->icon) ? fsentry->icon : ICON_FILE_FOLDER;+}++void ED_fsmenu_entry_set_icon(FSMenuEntry *fsentry, const int icon)+{+ fsentry->icon = icon;+}++static void fsmenu_entry_generate_name(FSMenuEntry *fsentry, MutableCStr name)+{+ int offset = 0;+ int len = name.size();++ if (BLI_path_name_at_index(fsentry->path, -1, &offset, &len)) {+ /* use as size */+ len += 1;+ }++ STRNCPY(name.take_front(len), &fsentry->path[offset]);+ if (!name[0]) {+ name[0] = '/';+ name[1] = '\0';+ }+}++char *ED_fsmenu_entry_get_name(FSMenuEntry *fsentry)+{+ if (fsentry->name[0]) {+ return fsentry->name;+ }++ /* Here we abuse fsm_iter->name, keeping first char nullptr. */+ char *name = fsentry->name + 1;+ size_t name_size = sizeof(fsentry->name) - 1;++ fsmenu_entry_generate_name(fsentry, MutableCStr(name, name_size));+ return name;+}++void ED_fsmenu_entry_set_name(FSMenuEntry *fsentry, const char *name)+{+ if (!STREQ(name, fsentry->name)) {+ char tmp_name[FILE_MAXFILE];++ fsmenu_entry_generate_name(fsentry, tmp_name);+ if (!name[0] || STREQ(tmp_name, name)) {+ /* reset name to default behavior. */+ fsentry->name[0] = '\0';+ }+ else {+ STRNCPY(fsentry->name, name);+ }++ const std::optional<std::string> user_config_dir = BKE_appdir_folder_id_create(+ BLENDER_USER_CONFIG, nullptr);++ if (user_config_dir.has_value()) {+ BLI_path_join(tmp_name, user_config_dir->c_str(), BLENDER_BOOKMARK_FILE);+ fsmenu_write_file(ED_fsmenu_get(), tmp_name);+ }+ }+}++short fsmenu_can_save(FSMenu *fsmenu, FSMenuCategory category, int idx)+{+ FSMenuEntry *fsm_iter;++ for (fsm_iter = ED_fsmenu_get_category(fsmenu, category); fsm_iter && idx;+ fsm_iter = fsm_iter->next)+ {+ idx--;+ }++ return fsm_iter ? fsm_iter->save : 0;+}++void fsmenu_insert_entry(FSMenu *fsmenu,+ FSMenuCategory category,+ const char *path,+ const char *name,+ int icon,+ FSMenuInsert flag)+{+ /* NOTE: this function must *not* perform file-system checks on `path`,+ * although the path may be inspected as a literal string.+ *+ * This is important because accessing the file system may reference drives+ * which are offline, network drives requiring an internet connection,+ * external drives that aren't plugged in, etc.+ * Delays in any file-system checks can causes hanging on startup.+ * See !138218 for details. */++ const uint path_len = strlen(path);+ BLI_assert(path_len > 0);+ if (path_len == 0) {+ return;+ }+ BLI_assert(!BLI_path_is_rel(path));+ const bool has_trailing_slash = (path[path_len - 1] == SEP);+ FSMenuEntry *fsm_prev;+ FSMenuEntry *fsm_iter;+ FSMenuEntry *fsm_head;++ fsm_head = ED_fsmenu_get_category(fsmenu, category);+ fsm_prev = fsm_head; /* this is odd and not really correct? */++ for (fsm_iter = fsm_head; fsm_iter; fsm_prev = fsm_iter, fsm_iter = fsm_iter->next) {+ if (fsm_iter->path) {+ if (fsm_iter->icon == FSMENU_CURRENT_FILE_ICON) {+ continue;+ }+ /* Compare, with/without the trailing slash in 'path'. */+ const int cmp_ret = BLI_path_ncmp(path, fsm_iter->path, path_len);+ if (cmp_ret == 0 && STREQ(fsm_iter->path + path_len, has_trailing_slash ? "" : SEP_STR)) {+ if (flag & FS_INSERT_FIRST) {+ if (fsm_iter != fsm_head) {+ fsm_prev->next = fsm_iter->next;+ fsm_iter->next = fsm_head;+ ED_fsmenu_set_category(fsmenu, category, fsm_iter);+ }+ }+ return;+ }+ if ((flag & FS_INSERT_SORTED) && cmp_ret < 0) {+ break;+ }+ }+ else {+ /* if we're bookmarking this, file should come+ * before the last separator, only automatically added+ * current dir go after the last separator. */+ if (flag & FS_INSERT_SAVE) {+ break;+ }+ }+ }++ fsm_iter = MEM_new_uninitialized<FSMenuEntry>("fsme");+ fsm_iter->path = has_trailing_slash ? BLI_strdup(path) : BLI_string_joinN(path, SEP_STR);+ fsm_iter->save = (flag & FS_INSERT_SAVE) != 0;++ /* If entry is also in another list, use that icon and maybe name. */+ /* On macOS we get icons and names for System Bookmarks from the FS_CATEGORY_OTHER list. */+ if (ELEM(category, FS_CATEGORY_SYSTEM_BOOKMARKS, FS_CATEGORY_BOOKMARKS, FS_CATEGORY_RECENT)) {++ const FSMenuCategory cats[] = {+ FS_CATEGORY_OTHER,+ FS_CATEGORY_SYSTEM,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FS_CATEGORY_BOOKMARKS,+ };+ int i = ARRAY_SIZE(cats);+ if (category == FS_CATEGORY_BOOKMARKS) {+ i--;+ }++ while (i--) {+ FSMenuEntry *tfsm = ED_fsmenu_get_category(fsmenu, cats[i]);+ for (; tfsm; tfsm = tfsm->next) {+ if (tfsm->icon == FSMENU_CURRENT_FILE_ICON) {+ continue;+ }+ if (STREQ(tfsm->path, fsm_iter->path)) {+ icon = tfsm->icon;+ if (tfsm->name[0] && (!name || !name[0])) {+ name = DATA_(tfsm->name);+ }+ break;+ }+ }+ if (tfsm) {+ break;+ }+ }+ }++ if (name && name[0]) {+ STRNCPY(fsm_iter->name, name);+ }+ else {+ fsm_iter->name[0] = '\0';+ }++ ED_fsmenu_entry_set_icon(fsm_iter, icon);++ if (fsm_prev) {+ if (flag & FS_INSERT_FIRST) {+ fsm_iter->next = fsm_head;+ ED_fsmenu_set_category(fsmenu, category, fsm_iter);+ }+ else {+ fsm_iter->next = fsm_prev->next;+ fsm_prev->next = fsm_iter;+ }+ }+ else {+ fsm_iter->next = fsm_head;+ ED_fsmenu_set_category(fsmenu, category, fsm_iter);+ }+}++void fsmenu_remove_entry(FSMenu *fsmenu, FSMenuCategory category, int idx)+{+ FSMenuEntry *fsm_prev = nullptr;+ FSMenuEntry *fsm_iter;+ FSMenuEntry *fsm_head;++ fsm_head = ED_fsmenu_get_category(fsmenu, category);++ for (fsm_iter = fsm_head; fsm_iter && idx; fsm_prev = fsm_iter, fsm_iter = fsm_iter->next) {+ idx--;+ }++ if (fsm_iter) {+ /* you should only be able to remove entries that were+ * not added by default, like windows drives.+ * also separators (where path == nullptr) shouldn't be removed */+ if (fsm_iter->save && fsm_iter->path) {++ /* remove fsme from list */+ if (fsm_prev) {+ fsm_prev->next = fsm_iter->next;+ }+ else {+ fsm_head = fsm_iter->next;+ ED_fsmenu_set_category(fsmenu, category, fsm_head);+ }+ /* free entry */+ MEM_delete(fsm_iter->path);+ MEM_delete(fsm_iter);+ }+ }+}++bool fsmenu_write_file(FSMenu *fsmenu, const char *filepath)+{+ FSMenuEntry *fsm_iter = nullptr;+ char fsm_name[FILE_MAX];+ int nwritten = 0;++ FILE *fp = BLI_fopen(filepath, "w");+ if (!fp) {+ return false;+ }++ bool has_error = false;+ has_error |= (fprintf(fp, "[Bookmarks]\n") < 0);+ for (fsm_iter = ED_fsmenu_get_category(fsmenu, FS_CATEGORY_BOOKMARKS); fsm_iter;+ fsm_iter = fsm_iter->next)+ {+ if (fsm_iter->path && fsm_iter->save) {+ fsmenu_entry_generate_name(fsm_iter, fsm_name);+ if (fsm_iter->name[0] && !STREQ(fsm_iter->name, fsm_name)) {+ has_error |= (fprintf(fp, "!%s\n", fsm_iter->name) < 0);+ }+ has_error |= (fprintf(fp, "%s\n", fsm_iter->path) < 0);+ }+ }+ has_error = (fprintf(fp, "[Recent]\n") < 0);+ for (fsm_iter = ED_fsmenu_get_category(fsmenu, FS_CATEGORY_RECENT);+ fsm_iter && (nwritten < FSMENU_RECENT_MAX);+ fsm_iter = fsm_iter->next, nwritten++)+ {+ if (fsm_iter->path && fsm_iter->save) {+ fsmenu_entry_generate_name(fsm_iter, fsm_name);+ if (fsm_iter->name[0] && !STREQ(fsm_iter->name, fsm_name)) {+ has_error |= (fprintf(fp, "!%s\n", fsm_iter->name) < 0);+ }+ has_error |= (fprintf(fp, "%s\n", fsm_iter->path) < 0);+ }+ }+ fclose(fp);++ return !has_error;+}++void fsmenu_read_bookmarks(FSMenu *fsmenu, const char *filepath)+{+ char line[FILE_MAXDIR];+ char name[FILE_MAXFILE];+ FSMenuCategory category = FS_CATEGORY_BOOKMARKS;+ FILE *fp;++ fp = BLI_fopen(filepath, "r");+ if (!fp) {+ return;+ }++ name[0] = '\0';++ while (fgets(line, sizeof(line), fp) != nullptr) { /* read a line */+ if (STRPREFIX(line, "[Bookmarks]")) {+ category = FS_CATEGORY_BOOKMARKS;+ }+ else if (STRPREFIX(line, "[Recent]")) {+ category = FS_CATEGORY_RECENT;+ }+ else if (line[0] == '!') {+ int len = strlen(line);+ if (len > 0) {+ if (line[len - 1] == '\n') {+ line[len - 1] = '\0';+ }+ STRNCPY(name, line + 1);+ }+ }+ else {+ int len = strlen(line);+ if (len > 0) {+ if (line[len - 1] == '\n') {+ line[len - 1] = '\0';+ }+ /* Don't check if the path exists before adding because it can be slow on network drives,+ * having a bookmark from a drive that's ejected or so isn't all that bad.+ * See !138218 for details. */+ fsmenu_insert_entry(fsmenu, category, line, name, ICON_FILE_FOLDER, FS_INSERT_SAVE);+ }+ /* always reset name. */+ name[0] = '\0';+ }+ }+ fclose(fp);+}++static void fsmenu_free_category(FSMenu *fsmenu, FSMenuCategory category)+{+ FSMenuEntry *fsm_iter = ED_fsmenu_get_category(fsmenu, category);++ while (fsm_iter) {+ FSMenuEntry *fsm_next = fsm_iter->next;++ if (fsm_iter->path) {+ MEM_delete(fsm_iter->path);+ }+ MEM_delete(fsm_iter);++ fsm_iter = fsm_next;+ }+}++void fsmenu_refresh_system_category(FSMenu *fsmenu)+{+ fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM);+ ED_fsmenu_set_category(fsmenu, FS_CATEGORY_SYSTEM, nullptr);++ fsmenu_free_category(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS);+ ED_fsmenu_set_category(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, nullptr);++ /* Add all entries to system category */+ fsmenu_read_system(fsmenu, true);+}++static void fsmenu_free_ex(FSMenu **fsmenu)+{+ if (*fsmenu != nullptr) {+ fsmenu_free_category(*fsmenu, FS_CATEGORY_SYSTEM);+ fsmenu_free_category(*fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS);+ fsmenu_free_category(*fsmenu, FS_CATEGORY_BOOKMARKS);+ fsmenu_free_category(*fsmenu, FS_CATEGORY_RECENT);+ fsmenu_free_category(*fsmenu, FS_CATEGORY_OTHER);+ MEM_delete(*fsmenu);+ }++ *fsmenu = nullptr;+}++void fsmenu_free()+{+ fsmenu_free_ex(&g_fsmenu);+}++int fsmenu_get_active_indices(FSMenu *fsmenu, enum FSMenuCategory category, const char *dir)+{+ FSMenuEntry *fsm_iter = ED_fsmenu_get_category(fsmenu, category);+ int i;++ for (i = 0; fsm_iter; fsm_iter = fsm_iter->next, i++) {+ if (BLI_path_cmp(dir, fsm_iter->path) == 0) {+ return i;+ }+ }++ return -1;+}++void fsmenu_add_common_platform_directories(FSMenu *fsmenu)+{+ /* For all platforms, we add some directories from User Preferences to+ * the FS_CATEGORY_OTHER category so that these directories+ * have the appropriate icons when they are added to the Bookmarks.+ *+ * NOTE: of the preferences support as `//` prefix.+ * Skip them since they depend on the current loaded blend file. */++ auto add_user_dir = [fsmenu](const char *dir, int icon) {+ if (dir[0] && !BLI_path_is_rel(dir)) {+ fsmenu_insert_entry(fsmenu, FS_CATEGORY_OTHER, dir, nullptr, icon, FS_INSERT_LAST);+ }+ };++ add_user_dir(U.fontdir, ICON_FILE_FONT);+ add_user_dir(U.textudir, ICON_FILE_IMAGE);++ for (bUserScriptDirectory &script_dir : U.script_directories) {+ if (script_dir.dir_path[0] == '\0') [[unlikely]] {+ continue;+ }+ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_OTHER,+ script_dir.dir_path,+ script_dir.name,+ ICON_FILE_SCRIPT,+ FS_INSERT_LAST);+ }++ add_user_dir(U.sounddir, ICON_FILE_SOUND);+ add_user_dir(U.tempdir, ICON_TEMP);+}++} // namespace blenderdiff --git a/ui/space_file/fsmenu.hh b/ui/space_file/fsmenu.hhnew file mode 100644index 0000000..e388abb--- /dev/null+++ b/ui/space_file/fsmenu.hh@@ -0,0 +1,65 @@+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#pragma once++#include "ED_fileselect.hh"++namespace blender {++/* XXX could become UserPref */+#define FSMENU_RECENT_MAX 10++#define FSMENU_CURRENT_FILE_ICON ICON_CURRENT_FILE++/**+ * Inserts a new fsmenu entry with the given \a path.+ * Duplicate entries are not added.+ * \param flag: Options for inserting the entry.+ *+ * \note The existence of `path` is *intentionally* not accessed,+ * see inline code-comments for details.+ */+void fsmenu_insert_entry(FSMenu *fsmenu,+ enum FSMenuCategory category,+ const char *path,+ const char *name,+ int icon,+ FSMenuInsert flag);++/** Return whether the entry was created by the user and can be saved and deleted */+short fsmenu_can_save(FSMenu *fsmenu, FSMenuCategory category, int idx);++/** Removes the fsmenu entry at the given \a index. */+void fsmenu_remove_entry(FSMenu *fsmenu, FSMenuCategory category, int idx);++/**+ * Saves the 'bookmarks' to the specified file.+ * \return true on success.+ */+bool fsmenu_write_file(FSMenu *fsmenu, const char *filepath);++/** reads the 'bookmarks' from the specified file */+void fsmenu_read_bookmarks(FSMenu *fsmenu, const char *filepath);++/** adds system specific directories */+void fsmenu_read_system(FSMenu *fsmenu, int read_bookmarks);++/** Frees all the memory associated with the `fsmenu`. */+void fsmenu_free();++/** Refresh system directory menu */+void fsmenu_refresh_system_category(FSMenu *fsmenu);++/** Get active index based on given directory. */+int fsmenu_get_active_indices(FSMenu *fsmenu, FSMenuCategory category, const char *dir);++/** Add base file bookmark menu directories common to all platforms. */+void fsmenu_add_common_platform_directories(FSMenu *fsmenu);++} // namespace blenderdiff --git a/ui/space_file/fsmenu_system_macos.mm b/ui/space_file/fsmenu_system_macos.mmnew file mode 100644index 0000000..e7583d6--- /dev/null+++ b/ui/space_file/fsmenu_system_macos.mm@@ -0,0 +1,163 @@+/* SPDX-FileCopyrightText: 2025 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ * \brief macOS System File menu implementation.+ */++#import "Foundation/Foundation.h"++#include "BLI_fileops.hh"+#include "BLI_path_utils.hh"+#include "BLI_string.hh"++#include "BLT_translation.hh"+#include "UI_resources.hh"++#include "fsmenu.hh"++namespace blender {++struct FSMenu;++void fsmenu_macos_insert_entry(FSMenu *fsmenu,+ const char *name,+ const char *default_path,+ const int icon,+ const char *home,+ const FSMenuCategory category = FS_CATEGORY_OTHER,+ const FSMenuInsert insert_flag = FS_INSERT_LAST)+{+ char path[FILE_MAXDIR];+ SNPRINTF(path, default_path, home);++ fsmenu_insert_entry(fsmenu, category, path, name, icon, insert_flag);+}++void fsmenu_read_system(FSMenu *fsmenu, int read_bookmarks)+{+ /* We store some known macOS system paths and corresponding icons+ * and names in the FS_CATEGORY_OTHER (not displayed directly) category. */+ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_OTHER, "/Library/Fonts/", N_("Fonts"), ICON_FILE_FONT, FS_INSERT_LAST);+ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_OTHER,+ "/Applications/",+ N_("Applications"),+ ICON_FILE_FOLDER,+ FS_INSERT_LAST);++ const char *home = BLI_dir_home();+ if (home) {+ fsmenu_macos_insert_entry(fsmenu, nullptr, "%s/", ICON_HOME, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Desktop"), "%s/Desktop/", ICON_DESKTOP, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Documents"), "%s/Documents/", ICON_DOCUMENTS, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Downloads"), "%s/Downloads/", ICON_IMPORT, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Movies"), "%s/Movies/", ICON_FILE_MOVIE, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Music"), "%s/Music/", ICON_FILE_SOUND, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Pictures"), "%s/Pictures/", ICON_FILE_IMAGE, home);+ fsmenu_macos_insert_entry(fsmenu, N_("Fonts"), "%s/Library/Fonts/", ICON_FILE_FONT, home);+ }++ NSFileManager *file_manager = [NSFileManager defaultManager];++ NSArray *resource_keys =+ @[ NSURLVolumeLocalizedNameKey, NSURLVolumeIsLocalKey, NSURLVolumeIsRemovableKey ];++ NSArray *mounted_volume_urls = [file_manager+ mountedVolumeURLsIncludingResourceValuesForKeys:resource_keys+ options:NSVolumeEnumerationSkipHiddenVolumes];++ for (NSURL *volume_url in mounted_volume_urls) {+ NSError *error = nil;+ NSDictionary *resources_values = [volume_url resourceValuesForKeys:resource_keys error:&error];++ if (!error) {+ NSString *volume_name = resources_values[NSURLVolumeLocalizedNameKey];+ NSNumber *volume_is_local = resources_values[NSURLVolumeIsLocalKey];+ NSNumber *volume_is_ejectable = resources_values[NSURLVolumeIsRemovableKey];++ /* Set icon for regular, removable or network drive. */+ int icon = ICON_DISK_DRIVE;+ if (!volume_is_local.boolValue) {+ icon = ICON_NETWORK_DRIVE;+ }+ else if (volume_is_ejectable.boolValue) {+ icon = ICON_EXTERNAL_DRIVE;+ }++ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_SYSTEM,+ volume_url.path.UTF8String,+ volume_name.UTF8String,+ icon,+ FS_INSERT_SORTED);+ }+ }++ /* iCloud Drive support, shown as a network volume, similarly to how it's displayed in Finder. */+ if (home) {+ fsmenu_macos_insert_entry(fsmenu,+ N_("iCloud Drive"),+ "%s/Library/Mobile Documents/com~apple~CloudDocs/",+ ICON_NETWORK_DRIVE,+ home,+ FS_CATEGORY_SYSTEM,+ FS_INSERT_FIRST);+ }++ /* The LSSharedFileList API has been deprecated, and no replacement has been provided to obtain+ * the user's Finder Favorites items from other applications. Ignore these deprecation warnings.+ * It is unknown when this API will be fully removed from macOS. */+ if (read_bookmarks) {+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"+ LSSharedFileListRef shared_list = LSSharedFileListCreate(+ nullptr, kLSSharedFileListFavoriteItems, nullptr);++ UInt32 seed;+ NSArray *paths_array = (__bridge NSArray *)LSSharedFileListCopySnapshot(shared_list, &seed);++ for (id item in paths_array) {+ LSSharedFileListItemRef item_ref = (__bridge LSSharedFileListItemRef)item;++ CFURLRef cf_url = nullptr;+ OSErr err = LSSharedFileListItemResolve(item_ref,+ kLSSharedFileListNoUserInteraction |+ kLSSharedFileListDoNotMountVolumes,+ &cf_url,+ nullptr);+ if (err != noErr || !cf_url) {+ continue;+ }++ NSURL *url = (__bridge NSURL *)cf_url;+ NSString *path = [url path];++ if (!path) {+ CFRelease(cf_url);+ continue;+ }++ // Exclude "all my files" and empty paths+ if (![path containsString:@"myDocuments.cannedSearch"] && [path length] > 0) {+ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ [path UTF8String],+ nullptr,+ ICON_FILE_FOLDER,+ FS_INSERT_LAST);+ }++ CFRelease(cf_url);+ }++ [paths_array release];+ CFRelease(shared_list);+#pragma GCC diagnostic pop+ }+}++} // namespace blenderdiff --git a/ui/space_file/fsmenu_system_unix.cc b/ui/space_file/fsmenu_system_unix.ccnew file mode 100644index 0000000..eb0ee94--- /dev/null+++ b/ui/space_file/fsmenu_system_unix.cc@@ -0,0 +1,279 @@+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ * \brief Generic Unix System File menu implementation.+ */++#include <cstdio>+#include <cstdlib>+#include <cstring>++#include "MEM_guardedalloc.h"++#include "BLI_fileops.hh"+#include "BLI_ghash.h"+#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string.h"+#include "BLI_utildefines.h"++#include "DNA_userdef_types.h"++#include "BLT_translation.hh"++#include "ED_fileselect.hh"++#include "UI_resources.hh"++#ifdef __linux__+# include "BLI_fileops_types.hh"+# include <mntent.h>++# include "CLG_log.h"++static CLG_LogRef LOG = {"system.path"};+#endif++#include "fsmenu.hh"++namespace blender {++struct FSMenu;++/* -------------------------------------------------------------------- */+/** \name XDG User Directory Support (Unix)+ *+ * Generic Unix, Use XDG when available, otherwise fall back to the home directory.+ * \{ */++/**+ * Look for `user-dirs.dirs`, where localized or custom user folders are defined,+ * and store their paths in a GHash.+ */+static GHash *fsmenu_xdg_user_dirs_parse(const char *home)+{+ /* Add to the default for variable, equals & quotes. */+ char l[128 + FILE_MAXDIR];+ FILE *fp;++ /* Check if the config file exists. */+ {+ char filepath[FILE_MAX];+ const char *xdg_config_home = getenv("XDG_CONFIG_HOME");+ if (xdg_config_home != nullptr) {+ BLI_path_join(filepath, xdg_config_home, "user-dirs.dirs");+ }+ else {+ BLI_path_join(filepath, home, ".config", "user-dirs.dirs");+ }+ fp = BLI_fopen(filepath, "r");+ if (!fp) {+ return nullptr;+ }+ }+ /* By default there are 8 paths. */+ GHash *xdg_map = BLI_ghash_str_new_ex(__func__, 8);+ while (fgets(l, sizeof(l), fp) != nullptr) { /* read a line */++ /* Avoid inserting invalid values. */+ if (STRPREFIX(l, "XDG_")) {+ char *l_value = strchr(l, '=');+ if (l_value != nullptr) {+ *l_value = '\0';+ l_value++;++ BLI_str_rstrip(l_value);+ const uint l_value_len = strlen(l_value);+ if ((l_value[0] == '"') && (l_value_len > 0) && (l_value[l_value_len - 1] == '"')) {+ l_value[l_value_len - 1] = '\0';+ l_value++;++ char l_value_expanded[FILE_MAX];+ char *l_value_final = l_value;++ /* This is currently the only variable used.+ * Based on the 'user-dirs.dirs' man page,+ * there is no need to resolve arbitrary environment variables. */+ if (STRPREFIX(l_value, "$HOME" SEP_STR)) {+ BLI_path_join(l_value_expanded, home, l_value + 6);+ l_value_final = l_value_expanded;+ }++ BLI_ghash_insert(xdg_map, BLI_strdup(l), BLI_strdup(l_value_final));+ }+ }+ }+ }+ fclose(fp);++ return xdg_map;+}++static void fsmenu_xdg_user_dirs_free(GHash *xdg_map)+{+ if (xdg_map != nullptr) {+ BLI_ghash_free(xdg_map, MEM_delete_void, MEM_delete_void);+ }+}++/**+ * Add fsmenu entry for system folders on linux.+ * - Check if a path is stored in the #GHash generated from `user-dirs.dirs`.+ * - If not, check for a default path in `$HOME`.+ *+ * \param key: Use `user-dirs.dirs` format "XDG_EXAMPLE_DIR"+ * \param default_path: Directory name to check in $HOME, also used for the menu entry name.+ */+static void fsmenu_xdg_insert_entry(GHash *xdg_map,+ FSMenu *fsmenu,+ const char *key,+ const char *default_path,+ int icon,+ const char *home)+{+ char xdg_path_buf[FILE_MAXDIR];+ const char *xdg_path = static_cast<const char *>(xdg_map ? BLI_ghash_lookup(xdg_map, key) :+ nullptr);+ if (xdg_path == nullptr) {+ BLI_path_join(xdg_path_buf, home, default_path);+ xdg_path = xdg_path_buf;+ }+ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, xdg_path, default_path, icon, FS_INSERT_LAST);+}++/** \} */++void fsmenu_read_system(FSMenu *fsmenu, int read_bookmarks)+{+ const char *home = BLI_dir_home();++ if (read_bookmarks && home) {+ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, home, N_("Home"), ICON_HOME, FS_INSERT_LAST);++ /* Follow the XDG spec, check if these are available. */+ GHash *xdg_map = fsmenu_xdg_user_dirs_parse(home);++ struct {+ const char *key;+ const char *default_path;+ BIFIconID icon;+ } xdg_items[] = {+ {"XDG_DESKTOP_DIR", "Desktop", ICON_DESKTOP},+ {"XDG_DOCUMENTS_DIR", "Documents", ICON_DOCUMENTS},+ {"XDG_DOWNLOAD_DIR", "Downloads", ICON_IMPORT},+ {"XDG_VIDEOS_DIR", "Videos", ICON_FILE_MOVIE},+ {"XDG_PICTURES_DIR", "Pictures", ICON_FILE_IMAGE},+ {"XDG_MUSIC_DIR", "Music", ICON_FILE_SOUND},+ };++ for (int i = 0; i < ARRAY_SIZE(xdg_items); i++) {+ fsmenu_xdg_insert_entry(+ xdg_map, fsmenu, xdg_items[i].key, xdg_items[i].default_path, xdg_items[i].icon, home);+ }++ fsmenu_xdg_user_dirs_free(xdg_map);+ }++ {+ bool found = false;+#ifdef __linux__+ /* loop over mount points */+ mntent *mnt;+ FILE *fp;++ fp = setmntent(MOUNTED, "r");+ if (fp == nullptr) {+ CLOG_WARN(&LOG, "Could not get a list of mounted file-systems");+ }+ else {++ /* Similar to `STRPREFIX`,+ * but ensures the prefix precedes a directory separator or null terminator.+ * Define locally since it's fairly specific to this particular use case. */+ auto strncmp_dir_delimit = [](const char *a, const char *b, size_t b_len) -> int {+ const int result = strncmp(a, b, b_len);+ return (result == 0 && !ELEM(a[b_len], '\0', '/')) ? 1 : result;+ };+# define STRPREFIX_DIR_DELIMIT(a, b) (strncmp_dir_delimit((a), (b), strlen(b)) == 0)++ while ((mnt = getmntent(fp))) {+ if (STRPREFIX_DIR_DELIMIT(mnt->mnt_dir, "/boot") ||+ /* According to: https://wiki.archlinux.org/title/EFI_system_partition (2025),+ * this is a common path to mount the EFI partition. */+ STRPREFIX_DIR_DELIMIT(mnt->mnt_dir, "/efi"))+ {+ /* Hide share not usable to the user. */+ continue;+ }+ if (!STRPREFIX_DIR_DELIMIT(mnt->mnt_fsname, "/dev")) {+ continue;+ }+ /* Use non-delimited prefix since a slash isn't expected after loop. */+ if (STRPREFIX(mnt->mnt_fsname, "/dev/loop")) {+ /* The `/dev/loop*` entries are SNAPS used by desktop environment+ * (GNOME) no need for them to show up in the list. */+ continue;+ }++ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM, mnt->mnt_dir, nullptr, ICON_DISK_DRIVE, FS_INSERT_SORTED);++ found = true;+ }+# undef STRPREFIX_DIR_DELIMIT++ if (endmntent(fp) == 0) {+ CLOG_WARN(&LOG, "Could not close the list of mounted file-systems");+ }+ }+ /* Check `gvfs` shares. */+ const char *const xdg_runtime_dir = BLI_getenv("XDG_RUNTIME_DIR");+ if (xdg_runtime_dir != nullptr) {+ direntry *dirs;+ char filepath[FILE_MAX];+ BLI_path_join(filepath, xdg_runtime_dir, "gvfs/");+ /* Avoid error message if the directory doesn't exist as this isn't a requirement. */+ if (BLI_is_dir(filepath)) {+ const uint dirs_num = BLI_filelist_dir_contents(filepath, &dirs);+ for (uint i = 0; i < dirs_num; i++) {+ if ((dirs[i].type & S_IFDIR) == 0) {+ continue;+ }+ const char *dirname = dirs[i].relname;+ if (dirname[0] == '.') {+ continue;+ }++ /* Directory names contain a lot of unwanted text.+ * Assuming every entry ends with the share name. */+ const char *label = strstr(dirname, "share=");+ if (label != nullptr) {+ /* Move pointer so `share=` is trimmed off or use full `dirname` as label. */+ const char *label_test = label + 6;+ label = *label_test ? label_test : dirname;+ }+ char line[FILE_MAXDIR];+ SNPRINTF(line, "%s%s", filepath, dirname);+ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM, line, label, ICON_NETWORK_DRIVE, FS_INSERT_SORTED);+ found = true;+ }+ BLI_filelist_free(dirs, dirs_num);+ }+ }+#endif /* __linux__ */++ /* fallback */+ if (!found) {+ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM, "/", nullptr, ICON_DISK_DRIVE, FS_INSERT_SORTED);+ }+ }+}++} // namespace blenderdiff --git a/ui/space_file/fsmenu_system_win32.cc b/ui/space_file/fsmenu_system_win32.ccnew file mode 100644index 0000000..61813aa--- /dev/null+++ b/ui/space_file/fsmenu_system_win32.cc@@ -0,0 +1,336 @@+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ * \brief Windows / Win32 System File menu implementation+ */++/* Need to include windows.h so _WIN32_IE is defined. */+#ifdef WIN32_LEAN_AND_MEAN+# undef WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+/* For SHGetSpecialFolderPath, has to be done before BLI_winstuff+ * because 'near' is disabled through BLI_windstuff. */+#include "BLI_winstuff.h"+#include <comdef.h>+#include <shlobj.h>+#include <shlwapi.h>+#include <winnetwk.h>+#include <wrl.h>++#include "utfconv.hh"++#include "MEM_guardedalloc.h"++#include "BLI_path_utils.hh"+#include "BLI_string.h"++#include "BLT_translation.hh"++#include "UI_resources.hh"++#include "fsmenu.hh"++namespace blender {++struct FSMenu;++/* Add Windows Quick Access items to the System list. */+static void fsmenu_add_windows_quick_access(FSMenu *fsmenu,+ FSMenuCategory category,+ FSMenuInsert flag)+{+ Microsoft::WRL::ComPtr<IShellDispatch> shell;+ if (CoCreateInstance(CLSID_Shell, nullptr, CLSCTX_ALL, IID_PPV_ARGS(shell.GetAddressOf())) !=+ S_OK)+ {+ return;+ }++ /* Open Quick Access folder. */+ Microsoft::WRL::ComPtr<Folder> dir;+ if (shell->NameSpace(_variant_t(L"shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}"),+ dir.GetAddressOf()) != S_OK)+ {+ return;+ }++ /* Get FolderItems. */+ Microsoft::WRL::ComPtr<FolderItems> items;+ if (dir->Items(items.GetAddressOf()) != S_OK) {+ return;+ }++ long count = 0;+ if (items->get_Count(&count) != S_OK) {+ return;+ }++ /* Iterate through the folder. */+ for (long i = 0; i < count; i++) {+ Microsoft::WRL::ComPtr<FolderItem> item;++ if (items->Item(_variant_t(i), item.GetAddressOf()) != S_OK) {+ continue;+ }++ VARIANT_BOOL isFolder;+ /* Skip if it's not a folder. */+ if (item->get_IsFolder(&isFolder) != S_OK || isFolder == VARIANT_FALSE) {+ continue;+ }++ _bstr_t path;+ if (item->get_Path(path.GetAddress()) != S_OK) {+ continue;+ }++ char utf_path[FILE_MAXDIR];+ conv_utf_16_to_8(path, utf_path, FILE_MAXDIR);++ /* Despite the above IsFolder check, Windows considers libraries and archives to be folders.+ * However, as Blender does not support opening them, they must be filtered out. #138863. */+ const char *ext_folderlike[] = {+ ".library-ms",+ ".zip",+ ".rar",+ ".7z",+ ".tar",+ ".gz",+ ".bz2",+ ".zst",+ ".xz",+ ".cab",+ ".iso",+ nullptr,+ };+ if (!BLI_path_extension_check_array(utf_path, ext_folderlike)) {+ /* Add folder to the fsmenu. */+ fsmenu_insert_entry(fsmenu, category, utf_path, NULL, ICON_FILE_FOLDER, flag);+ }+ }+}++/* Add a Windows known folder path to the System list. */+static void fsmenu_add_windows_folder(FSMenu *fsmenu,+ FSMenuCategory category,+ REFKNOWNFOLDERID rfid,+ const char *name,+ const int icon,+ FSMenuInsert flag)+{+ LPWSTR pPath;+ char line[FILE_MAXDIR];+ if (SHGetKnownFolderPath(rfid, 0, nullptr, &pPath) == S_OK) {+ conv_utf_16_to_8(pPath, line, FILE_MAXDIR);+ fsmenu_insert_entry(fsmenu, category, line, name, icon, flag);+ }+ CoTaskMemFree(pPath);+}++static int fsmenu_external_drive_icon(char drive_letter)+{+ bool is_removable = false; /* ZIP, JAZ, CDROM, MO, etc. instead of a HDD. */+ bool is_hotplug = false; /* 1394, USB, etc. */+ bool is_usb = false; /* USB bus. */+ char volumeName[8] = "";+ SNPRINTF(volumeName, "\\\\.\\%c:", drive_letter);+ HANDLE volume = ::CreateFile(volumeName, 0, 0, NULL, OPEN_EXISTING, 0, NULL);++ if (volume != INVALID_HANDLE_VALUE) {+ STORAGE_HOTPLUG_INFO Info = {0};+ DWORD bytesReturned = 0;+ if (::DeviceIoControl(volume,+ IOCTL_STORAGE_GET_HOTPLUG_INFO,+ 0,+ 0,+ &Info,+ sizeof(Info),+ &bytesReturned,+ NULL))+ {+ is_removable = Info.MediaRemovable != 0;+ is_hotplug = Info.DeviceHotplug != 0;+ }++ STORAGE_PROPERTY_QUERY Prop;+ Prop.PropertyId = StorageDeviceProperty;+ Prop.QueryType = PropertyStandardQuery;+ Prop.AdditionalParameters[0] = 0;+ STORAGE_DEVICE_DESCRIPTOR DevInfo = {0};+ if (::DeviceIoControl(volume,+ IOCTL_STORAGE_QUERY_PROPERTY,+ &Prop,+ sizeof(Prop),+ &DevInfo,+ sizeof(DevInfo),+ &bytesReturned,+ NULL))+ {+ is_usb = (DevInfo.BusType == BusTypeUsb);+ }+ ::CloseHandle(volume);+ }++ return (is_removable && is_hotplug && is_usb) ? ICON_USB_DRIVE : ICON_EXTERNAL_DRIVE;+}++void fsmenu_read_system(FSMenu *fsmenu, int read_bookmarks)+{+ char line[FILE_MAXDIR];+ /* Add the drive names to the listing */+ wchar_t wline[FILE_MAXDIR];+ __int64 tmp;+ char tmps[4], *name;++ tmp = GetLogicalDrives();++ for (int i = 0; i < 26; i++) {+ if ((tmp >> i) & 1) {+ tmps[0] = 'A' + i;+ tmps[1] = ':';+ tmps[2] = '\\';+ tmps[3] = '\0';+ name = nullptr;++ /* Skip over floppy disks A & B. */+ if (i > 1) {+ /* Friendly volume descriptions without using SHGetFileInfoW (#85689). */+ conv_utf_8_to_16(tmps, wline, 4);+ IShellFolder *desktop;+ if (SHGetDesktopFolder(&desktop) == S_OK) {+ PIDLIST_RELATIVE volume;+ if (desktop->ParseDisplayName(nullptr, nullptr, wline, nullptr, &volume, nullptr) ==+ S_OK)+ {+ STRRET volume_name;+ volume_name.uType = STRRET_WSTR;+ if (desktop->GetDisplayNameOf(volume, SHGDN_FORADDRESSBAR, &volume_name) == S_OK) {+ wchar_t *volume_name_wchar;+ if (StrRetToStrW(&volume_name, volume, &volume_name_wchar) == S_OK) {+ conv_utf_16_to_8(volume_name_wchar, line, FILE_MAXDIR);+ name = line;+ CoTaskMemFree(volume_name_wchar);+ }+ }+ CoTaskMemFree(volume);+ }+ desktop->Release();+ }+ }+ if (name == nullptr) {+ name = tmps;+ }++ int icon = ICON_DISK_DRIVE;+ switch (GetDriveType(tmps)) {+ case DRIVE_REMOVABLE:+ icon = fsmenu_external_drive_icon('A' + i);+ break;+ case DRIVE_CDROM:+ icon = ICON_DISC;+ break;+ case DRIVE_FIXED: {+ DWORD fileSystemFlags;+ const bool is_cloud =+ (GetVolumeInformation(+ tmps, nullptr, 0, nullptr, nullptr, &fileSystemFlags, nullptr, 0) &&+ (fileSystemFlags & FILE_SUPPORTS_REMOTE_STORAGE));+ icon = is_cloud ? ICON_INTERNET : ICON_DISK_DRIVE;+ break;+ }+ case DRIVE_RAMDISK:+ icon = ICON_DISK_DRIVE;+ break;+ case DRIVE_REMOTE: {+ char lpLocalName[] = {static_cast<char>('A' + i), ':', 0};+ char lpRemoteName[MAX_PATH];+ DWORD lpnLength = sizeof(lpRemoteName);+ const bool is_cloud = (WNetGetConnection(lpLocalName, lpRemoteName, &lpnLength) ==+ NO_ERROR &&+ STRPREFIX(lpRemoteName, "https:"));+ icon = is_cloud ? ICON_INTERNET : ICON_NETWORK_DRIVE;+ break;+ }+ default:+ icon = ICON_DISK_DRIVE;+ break;+ }++ fsmenu_insert_entry(+ fsmenu, FS_CATEGORY_SYSTEM, tmps, name, icon, FSMenuInsert(FS_INSERT_SORTED));+ }+ }++ /* Get Special Folder Locations. */+ if (read_bookmarks) {++ /* These items are shown in System List. */+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Profile,+ N_("Home"),+ ICON_HOME,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Desktop,+ N_("Desktop"),+ ICON_DESKTOP,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Documents,+ N_("Documents"),+ ICON_DOCUMENTS,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Downloads,+ N_("Downloads"),+ ICON_IMPORT,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Music,+ N_("Music"),+ ICON_FILE_SOUND,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Pictures,+ N_("Pictures"),+ ICON_FILE_IMAGE,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Videos,+ N_("Videos"),+ ICON_FILE_MOVIE,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_Fonts,+ N_("Fonts"),+ ICON_FILE_FONT,+ FS_INSERT_LAST);+ fsmenu_add_windows_folder(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ FOLDERID_SkyDrive,+ N_("OneDrive"),+ ICON_INTERNET,+ FS_INSERT_LAST);++ /* These items are just put in path cache for thumbnail views and if bookmarked. */+ fsmenu_add_windows_folder(+ fsmenu, FS_CATEGORY_OTHER, FOLDERID_UserProfiles, nullptr, ICON_COMMUNITY, FS_INSERT_LAST);++ /* Last add Quick Access items to avoid duplicates and use icons if available. */+ fsmenu_add_windows_quick_access(fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, FS_INSERT_LAST);+ }+}++} // namespace blenderdiff --git a/ui/space_file/space_file.cc b/ui/space_file/space_file.ccnew file mode 100644index 0000000..8d1f649--- /dev/null+++ b/ui/space_file/space_file.cc@@ -0,0 +1,1182 @@+/* SPDX-FileCopyrightText: 2008 Blender Authors+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++/** \file+ * \ingroup spfile+ */++#include <cstring>++#include "AS_asset_library.hh"++#include "MEM_guardedalloc.h"++#include "BLI_listbase.h"+#include "BLI_path_utils.hh"+#include "BLI_string_utf8.h"+#include "BLI_utildefines.h"++#include "BKE_appdir.hh"+#include "BKE_context.hh"+#include "BKE_global.hh"+#include "BKE_lib_query.hh"+#include "BKE_main.hh"+#include "BKE_report.hh"+#include "BKE_screen.hh"++#include "BLT_translation.hh"++#include "RNA_access.hh"+#include "RNA_define.hh"+#include "RNA_enum_types.hh"++#include "WM_api.hh"+#include "WM_message.hh"+#include "WM_types.hh"++#include "ED_asset.hh"+#include "ED_asset_indexer.hh"+#include "ED_fileselect.hh"+#include "ED_screen.hh"+#include "ED_space_api.hh"++#include "IMB_thumbs.hh"++#include "UI_resources.hh"+#include "UI_view2d.hh"++#include "BLO_read_write.hh"++#include "file_banner.hh"+#include "file_indexer.hh"+#include "file_intern.hh" /* own include */+#include "filelist.hh"+#include "fsmenu.hh"++namespace blender {++/* ******************** default callbacks for file space ***************** */++static SpaceLink *file_create(const ScrArea * /*area*/, const Scene * /*scene*/)+{+ ARegion *region;+ SpaceFile *sfile;++ sfile = MEM_new<SpaceFile>("initfile");+ sfile->spacetype = SPACE_FILE;++ /* header */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_HEADER;+ /* Ignore user preference "USER_HEADER_BOTTOM" here (always show top for new types). */+ region->alignment = RGN_ALIGN_TOP;++ /* Tools region */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_TOOLS;+ region->alignment = RGN_ALIGN_LEFT;++ /* ui list region */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_UI;+ region->alignment = RGN_ALIGN_TOP;+ region->flag = RGN_FLAG_DYNAMIC_SIZE | RGN_FLAG_NO_USER_RESIZE;++ /* execute region */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_EXECUTE;+ region->alignment = RGN_ALIGN_BOTTOM;+ region->flag = RGN_FLAG_DYNAMIC_SIZE | RGN_FLAG_NO_USER_RESIZE;++ /* tools props region */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_TOOL_PROPS;+ region->alignment = RGN_ALIGN_RIGHT;+ region->flag = RGN_FLAG_HIDDEN;++ /* main region */+ region = BKE_area_region_new();+ BLI_addtail(&sfile->regionbase, region);+ region->regiontype = RGN_TYPE_WINDOW;+ region->v2d.scroll = (V2D_SCROLL_RIGHT | V2D_SCROLL_BOTTOM);+ region->v2d.align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_POS_Y);+ region->v2d.keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);+ region->v2d.keeptot = V2D_KEEPTOT_STRICT;+ region->v2d.minzoom = region->v2d.maxzoom = 1.0f;++ return reinterpret_cast<SpaceLink *>(sfile);+}++/* Doesn't free the space-link itself. */+static void file_free(SpaceLink *sl)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(sl);++ BLI_assert(sfile->previews_timer == nullptr);++ if (sfile->files) {+ /* XXX would need to do thumbnails_stop here, but no context available */+ filelist_freelib(sfile->files);+ filelist_free(sfile->files);+ sfile->files = nullptr;+ }++ folder_history_list_free(sfile);++ MEM_SAFE_DELETE(sfile->params);+ MEM_SAFE_DELETE(sfile->asset_params);+ if (sfile->runtime != nullptr) {+ BKE_reports_free(&sfile->runtime->is_blendfile_readable_reports);+ }+ MEM_SAFE_DELETE(sfile->runtime);++ MEM_SAFE_DELETE(sfile->layout);+}++/* spacetype; init callback, area size changes, screen set, etc */+static void file_init(wmWindowManager * /*wm*/, ScrArea *area)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();++ if (sfile->layout) {+ sfile->layout->dirty = true;+ }++ if (sfile->runtime == nullptr) {+ sfile->runtime = MEM_new_zeroed<SpaceFile_Runtime>(__func__);+ BKE_reports_init(&sfile->runtime->is_blendfile_readable_reports, RPT_STORE);+ }+ /* Validate the params right after file read. */+ fileselect_refresh_params(sfile);+}++static void file_exit(wmWindowManager *wm, ScrArea *area)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();++ if (sfile->previews_timer) {+ WM_event_timer_remove_notifier(wm, nullptr, sfile->previews_timer);+ sfile->previews_timer = nullptr;+ }++ wmWindow *win = WM_window_find_by_area(wm, area);+ file_params_smoothscroll_timer_clear(wm, win, sfile);++ ED_fileselect_exit(wm, sfile);+}++static SpaceLink *file_duplicate(SpaceLink *sl)+{+ SpaceFile *sfileo = reinterpret_cast<SpaceFile *>(sl);+ SpaceFile *sfilen = MEM_dupalloc(reinterpret_cast<SpaceFile *>(sl));++ /* clear or remove stuff from old */+ sfilen->op = nullptr; /* file window doesn't own operators */+ sfilen->runtime = nullptr;++ sfilen->previews_timer = nullptr;+ sfilen->smoothscroll_timer = nullptr;++ FileSelectParams *active_params_old = ED_fileselect_get_active_params(sfileo);+ if (active_params_old) {+ sfilen->files = filelist_new(active_params_old->type);+ filelist_setdir(sfilen->files, active_params_old->dir);+ }++ if (sfileo->params) {+ sfilen->params = MEM_dupalloc(sfileo->params);+ }+ if (sfileo->asset_params) {+ sfilen->asset_params = static_cast<FileAssetSelectParams *>(+ MEM_dupalloc(sfileo->asset_params));+ }++ sfilen->folder_histories = folder_history_list_duplicate(&sfileo->folder_histories);++ if (sfileo->layout) {+ sfilen->layout = MEM_dupalloc(sfileo->layout);+ }+ return reinterpret_cast<SpaceLink *>(sfilen);+}++static void file_refresh(const bContext *C, ScrArea *area)+{+ using namespace blender::ed;+ wmWindowManager *wm = CTX_wm_manager(C);+ wmWindow *win = CTX_wm_window(C);+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_ensure_active_params(sfile);+ FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);+ FSMenu *fsmenu = ED_fsmenu_get();++ fileselect_refresh_params(sfile);+ folder_history_list_ensure_for_active_browse_mode(sfile);++ if (sfile->runtime != nullptr) {+ sfile->runtime->is_blendfile_status_set = false;+ }++ if (sfile->files && (sfile->tags & FILE_TAG_REBUILD_MAIN_FILES) &&+ filelist_needs_reset_on_main_changes(sfile->files))+ {+ filelist_tag_force_reset_mainfiles(sfile->files);+ }+ sfile->tags &= ~FILE_TAG_REBUILD_MAIN_FILES;++ if (!sfile->files) {+ sfile->files = filelist_new(params->type);+ params->highlight_file = -1; /* added this so it opens nicer (ton) */+ }++ if (ED_fileselect_is_asset_browser(sfile)) {+ /* Ask the asset code for appropriate ID filter flags for the supported assets, and mask others+ * out. */+ params->filter_id &= asset::types_supported_as_filter_flags();+ }++ filelist_settype(sfile->files, params->type);+ filelist_setdir(sfile->files, params->dir);+ filelist_setrecursion(sfile->files, params->recursion_level);+ filelist_setglob(sfile->files, params->filter_glob);+ filelist_setsorting(sfile->files, params->sort, params->flag & FILE_SORT_INVERT);+ filelist_setlibrary(+ sfile->files, asset_params ? &asset_params->asset_library_ref : nullptr, [&]() {+ /* When switching to the essentials library and the "Unassigned" catalog is active, switch+ * to the "All" library instead. The "Unassigned" catalog should be empty for the+ * essentials library and isn't shown in the UI. */+ if ((asset_params->asset_library_ref.type == ASSET_LIBRARY_ESSENTIALS) &&+ asset_params->asset_catalog_visibility == FILE_SHOW_ASSETS_WITHOUT_CATALOG)+ {+ asset_params->asset_catalog_visibility = FILE_SHOW_ASSETS_ALL_CATALOGS;+ }+ });++ const bool show_assets_online = asset_params && ELEM(asset_params->asset_access,+ AssetAccess::OnlineAndOffline,+ AssetAccess::OnlyOnline);+ const bool show_assets_offline = asset_params && ELEM(asset_params->asset_access,+ AssetAccess::OnlineAndOffline,+ AssetAccess::OnlyOffline);+ filelist_setfilter_options(+ sfile->files,+ (params->flag & FILE_FILTER) != 0,+ (params->flag & FILE_HIDE_DOT) != 0,+ true, /* Just always hide parent, prefer to not add an extra user option for this. */+ params->filter,+ params->filter_id,+ (params->flag & FILE_ASSETS_ONLY) != 0,+ /*filter_assets_hide_online=*/!show_assets_online,+ /*filter_assets_hide_offline=*/!show_assets_offline,+ params->filter_search);+ if (asset_params) {+ filelist_set_asset_include_online(sfile->files, show_assets_online);+ filelist_set_asset_catalog_filter_options(+ sfile->files,+ eFileSel_Params_AssetCatalogVisibility(asset_params->asset_catalog_visibility),+ &asset_params->catalog_id);+ }++ if (ED_fileselect_is_asset_browser(sfile)) {+ const bool use_asset_indexer = !USER_DEVELOPER_TOOL_TEST(&U, no_asset_indexing);+ filelist_setindexer(+ sfile->files, use_asset_indexer ? &asset::index::file_indexer_asset : &file_indexer_noop);+ }++ /* Update the active indices of bookmarks & co. */+ sfile->systemnr = fsmenu_get_active_indices(fsmenu, FS_CATEGORY_SYSTEM, params->dir);+ sfile->system_bookmarknr = fsmenu_get_active_indices(+ fsmenu, FS_CATEGORY_SYSTEM_BOOKMARKS, params->dir);+ sfile->bookmarknr = fsmenu_get_active_indices(fsmenu, FS_CATEGORY_BOOKMARKS, params->dir);+ sfile->recentnr = fsmenu_get_active_indices(fsmenu, FS_CATEGORY_RECENT, params->dir);++ if (filelist_needs_force_reset(sfile->files)) {+ filelist_readjob_stop(sfile->files, wm);+ filelist_clear_from_reset_tag(sfile->files);+ }++ if (filelist_needs_reading(sfile->files)) {+ if (!filelist_pending(sfile->files)) {+ filelist_readjob_start(sfile->files, NC_SPACE | ND_SPACE_FILE_LIST, C);+ }+ }++ filelist_sort(sfile->files);++ if (filelist_needs_filtering(sfile->files)) {+ filelist_filter(sfile->files);+ params->active_file = -1;+ }++ if (params->display == FILE_IMGDISPLAY) {+ filelist_cache_previews_set(sfile->files, true);+ }+ else {+ filelist_cache_previews_set(sfile->files, false);+ if (sfile->previews_timer) {+ WM_event_timer_remove_notifier(wm, win, sfile->previews_timer);+ sfile->previews_timer = nullptr;+ }+ }++ if (params->rename_flag != 0) {+ file_params_renamefile_activate(sfile, params);+ }++ if (sfile->layout) {+ sfile->layout->dirty = true;+ }++ if (area) {+ ARegion *region_props = BKE_area_find_region_type(area, RGN_TYPE_TOOL_PROPS);+ const short region_flag_old = region_props->flag;+ if (!(region_props->v2d.flag & V2D_IS_INIT)) {+ if (ED_fileselect_is_asset_browser(sfile)) {+ /* Hide by default in asset browser. */+ region_props->flag |= RGN_FLAG_HIDDEN;+ }+ else {+ if (params->flag & FILE_HIDE_TOOL_PROPS) {+ region_props->flag |= RGN_FLAG_HIDDEN;+ }+ else {+ region_props->flag &= ~RGN_FLAG_HIDDEN;+ }+ }+ }+ if (region_flag_old != region_props->flag) {+ ED_region_visibility_change_update(const_cast<bContext *>(C), area, region_props);+ }+ }++ ED_area_tag_redraw(area);+}++void file_on_reload_callback_register(SpaceFile *sfile,+ onReloadFn callback,+ onReloadFnData custom_data)+{+ sfile->runtime->on_reload = callback;+ sfile->runtime->on_reload_custom_data = custom_data;+}++static void file_on_reload_callback_call(SpaceFile *sfile)+{+ if (sfile->runtime->on_reload == nullptr) {+ return;+ }++ sfile->runtime->on_reload(sfile, sfile->runtime->on_reload_custom_data);++ sfile->runtime->on_reload = nullptr;+ sfile->runtime->on_reload_custom_data = nullptr;+}++static void file_reset_filelist_showing_main_data(ScrArea *area, SpaceFile *sfile)+{+ if (sfile->files && filelist_needs_reset_on_main_changes(sfile->files)) {+ filelist_tag_force_reset_mainfiles(sfile->files);+ ED_area_tag_refresh(area);+ }+}++static void file_listener(const wmSpaceTypeListenerParams *listener_params)+{+ ScrArea *area = listener_params->area;+ const wmNotifier *wmn = listener_params->notifier;+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();++ /* context changes */+ switch (wmn->category) {+ case NC_UI:+ if (wmn->data == ND_UI_LANG && sfile && sfile->files) {+ filelist_tag_force_reset(sfile->files);+ }+ break;+ case NC_SPACE:+ switch (wmn->data) {+ case ND_SPACE_FILE_LIST:+ ED_area_tag_refresh(area);+ break;+ case ND_SPACE_FILE_PARAMS:+ ED_area_tag_refresh(area);+ break;+ case ND_SPACE_FILE_PREVIEW:+ if (sfile->files && filelist_cache_previews_update(sfile->files)) {+ ED_area_tag_refresh(area);+ }+ break;+ case ND_SPACE_ASSET_PARAMS:+ if (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS) {+ ED_area_tag_refresh(area);+ }+ break;+ case ND_SPACE_CHANGED:+ /* If the space was just turned into a file/asset browser, the file-list may need to be+ * updated to reflect latest changes in main data. */+ file_reset_filelist_showing_main_data(area, sfile);+ break;+ }+ switch (wmn->action) {+ case NA_JOB_FINISHED:+ file_on_reload_callback_call(sfile);+ break;+ }+ break;+ case NC_ID: {+ switch (wmn->action) {+ case NA_RENAME: {+ const ID *active_file_id = ED_fileselect_active_asset_get(sfile);+ /* If a renamed ID is active in the file browser, update scrolling to keep it in view. */+ if (active_file_id && (wmn->reference == active_file_id)) {+ FileSelectParams *params = ED_fileselect_get_active_params(sfile);+ params->rename_id = active_file_id;+ file_params_invoke_rename_postscroll(+ G_MAIN->wm.first(), listener_params->window, sfile);+ }++ /* Force list to update sorting (with a full reset for now). */+ file_reset_filelist_showing_main_data(area, sfile);+ break;+ }+ }+ break;+ }+ case NC_ASSET: {+ switch (wmn->action) {+ case NA_SELECTED:+ case NA_ACTIVATED:+ ED_area_tag_refresh(area);+ break;+ case NA_ADDED:+ case NA_REMOVED:+ case NA_EDITED:+ file_reset_filelist_showing_main_data(area, sfile);+ break;+ case NA_DOWNLOAD_FINISHED:+ ED_area_tag_redraw(area);+ break;+ }+ break;+ }+ }+}++/* add handlers, stuff you only do once or on area/region changes */+static void file_main_region_init(wmWindowManager *wm, ARegion *region)+{+ wmKeyMap *keymap;++ view2d_region_reinit(®ion->v2d, ui::V2D_COMMONVIEW_LIST, region->winx, region->winy);++ region->flag |= RGN_FLAG_INDICATE_OVERFLOW;++ /* Truncate, otherwise these can be on ".5" and give fuzzy text. #77696. */+ region->v2d.cur.ymin = trunc(region->v2d.cur.ymin);+ region->v2d.cur.ymax = trunc(region->v2d.cur.ymax);++ /* own keymaps */+ keymap = WM_keymap_ensure(wm->runtime->defaultconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);++ keymap = WM_keymap_ensure(+ wm->runtime->defaultconf, "File Browser Main", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);++ keymap = WM_keymap_ensure(+ wm->runtime->defaultconf, "Asset Browser Main", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);+ keymap->poll = [](bContext *C) { return ED_operator_asset_browsing_active(C); };+}++static void file_main_region_listener(const wmRegionListenerParams *listener_params)+{+ ARegion *region = listener_params->region;+ const wmNotifier *wmn = listener_params->notifier;++ /* context changes */+ switch (wmn->category) {+ case NC_SPACE:+ switch (wmn->data) {+ case ND_SPACE_FILE_LIST:+ ED_region_tag_redraw(region);+ break;+ case ND_SPACE_FILE_PARAMS:+ ED_region_tag_redraw(region);+ break;+ }+ break;+ case NC_ID:+ if (ELEM(wmn->action, NA_SELECTED, NA_ACTIVATED, NA_RENAME)) {+ ED_region_tag_redraw(region);+ }+ break;+ }+}++static void file_main_region_message_subscribe(const wmRegionMessageSubscribeParams *params)+{+ wmMsgBus *mbus = params->message_bus;+ bScreen *screen = params->screen;+ ScrArea *area = params->area;+ ARegion *region = params->region;+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();++ FileSelectParams *file_params = ED_fileselect_ensure_active_params(sfile);+ /* This is a bit odd that a region owns the subscriber for an area,+ * keep for now since all subscribers for WM are regions.+ * May be worth re-visiting later. */+ wmMsgSubscribeValue msg_sub_value_area_tag_refresh{};+ msg_sub_value_area_tag_refresh.owner = region;+ msg_sub_value_area_tag_refresh.user_data = area;+ msg_sub_value_area_tag_refresh.notify = ED_area_do_msg_notify_tag_refresh;++ /* SpaceFile itself. */+ {+ PointerRNA ptr = RNA_pointer_create_discrete(&screen->id, RNA_SpaceFileBrowser, sfile);++ /* All properties for this space type. */+ WM_msg_subscribe_rna(mbus, &ptr, nullptr, &msg_sub_value_area_tag_refresh, __func__);+ }++ /* FileSelectParams */+ {+ PointerRNA ptr = RNA_pointer_create_discrete(&screen->id, RNA_FileSelectParams, file_params);++ /* All properties for this space type. */+ WM_msg_subscribe_rna(mbus, &ptr, nullptr, &msg_sub_value_area_tag_refresh, __func__);+ }++ /* Experimental Asset Browser features option. */+ {+ PointerRNA ptr = RNA_pointer_create_discrete(+ nullptr, RNA_PreferencesExperimental, &U.experimental);+ PropertyRNA *prop = RNA_struct_find_property(&ptr, "use_extended_asset_browser");++ /* All properties for this space type. */+ WM_msg_subscribe_rna(mbus, &ptr, prop, &msg_sub_value_area_tag_refresh, __func__);+ }++ /* Use online access option (for remote asset libraries). */+ {+ wmMsgSubscribeValue msg_sub_value_region_clear_remote_libraries{};+ msg_sub_value_region_clear_remote_libraries.owner = region;+ msg_sub_value_region_clear_remote_libraries.user_data = sfile;+ msg_sub_value_region_clear_remote_libraries.notify = [](/* Follow wmMsgNotifyFn spec */+ bContext *C,+ wmMsgSubscribeKey * /*msg_key*/,+ wmMsgSubscribeValue *msg_val) {+ SpaceFile *sfile = static_cast<SpaceFile *>(msg_val->user_data);+ if (const FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile)) {+ if (blender::asset_system::is_or_contains_remote_libraries(+ asset_params->asset_library_ref))+ {+ /* Calls #ED_fileselect_clear() for all open asset browsers. */+ ed::asset::list::clear(&asset_params->asset_library_ref, C);+ }+ }+ };+ WM_msg_subscribe_rna_prop(mbus,+ nullptr,+ &U,+ PreferencesSystem,+ use_online_access,+ &msg_sub_value_region_clear_remote_libraries);+ WM_msg_subscribe_rna_prop(mbus,+ nullptr,+ &U,+ PreferencesExperimental,+ use_remote_asset_libraries,+ &msg_sub_value_region_clear_remote_libraries);+ }+}++bool file_main_region_needs_refresh_before_draw(SpaceFile *sfile)+{+ /* Needed, because filelist is not initialized on loading */+ if (!sfile->files || filelist_needs_reading(sfile->files)) {+ return true;+ }++ /* File reading tagged the space because main data changed that may require a filelist reset. */+ if (filelist_needs_reset_on_main_changes(sfile->files) &&+ (sfile->tags & FILE_TAG_REBUILD_MAIN_FILES))+ {+ return true;+ }++ return false;+}++static void file_main_region_draw(const bContext *C, ARegion *region)+{+ /* draw entirely, view changes should be handled here */+ SpaceFile *sfile = CTX_wm_space_file(C);+ FileSelectParams *params = ED_fileselect_ensure_active_params(sfile);++ View2D *v2d = ®ion->v2d;++ if (file_main_region_needs_refresh_before_draw(sfile)) {+ file_refresh(C, nullptr);+ }++ /* clear and setup matrix */+ ui::theme::frame_buffer_clear(TH_BACK);++ /* Allow dynamically sliders to be set, saves notifiers etc. */++ if (params->display == FILE_IMGDISPLAY) {+ v2d->scroll = V2D_SCROLL_RIGHT;+ v2d->keepofs &= ~V2D_LOCKOFS_Y;+ v2d->keepofs |= V2D_LOCKOFS_X;+ }+ else if (params->display == FILE_VERTICALDISPLAY) {+ v2d->scroll = V2D_SCROLL_RIGHT;+ v2d->keepofs &= ~V2D_LOCKOFS_Y;+ v2d->keepofs |= V2D_LOCKOFS_X;+ }+ else {+ v2d->scroll = V2D_SCROLL_BOTTOM;+ v2d->keepofs &= ~V2D_LOCKOFS_X;+ v2d->keepofs |= V2D_LOCKOFS_Y;++ /* XXX this happens on scaling down Screen (like from startup.blend) */+ /* view2d has no type specific for file-window case, which doesn't scroll vertically. */+ if (v2d->cur.ymax < 0) {+ v2d->cur.ymin -= v2d->cur.ymax;+ v2d->cur.ymax = 0;+ }+ }+ /* v2d has initialized flag, so this call will only set the mask correct */+ view2d_region_reinit(v2d, ui::V2D_COMMONVIEW_LIST, region->winx, region->winy);++ /* on first read, find active file */+ if (params->highlight_file == -1) {+ const wmEvent *event = CTX_wm_window(C)->runtime->eventstate;+ file_highlight_set(sfile, region, event->xy[0], event->xy[1]);+ }++ file_banners_update(*sfile);+ ED_fileselect_init_layout(sfile, region);++ if (!file_draw_hint_if_invalid(C, sfile, region)) {+ ui::view2d_totRect_set(v2d, sfile->layout->width, sfile->layout->height);++ /* set view */+ ui::view2d_view_ortho(v2d);++ file_draw_list(C, region);+ /* After the list, so it draws on top. */+ file_draw_banner(C, sfile, region);+ }++ /* reset view matrix */+ ui::view2d_view_restore(C);++ /* scrollers */+ rcti view_rect;+ ED_fileselect_layout_maskrect(sfile->layout, v2d, &view_rect);+ ui::view2d_scrollers_draw(v2d, &view_rect);++ ED_region_draw_overflow_indication(CTX_wm_area(C), region, &view_rect);+}++static void file_operatortypes()+{+ WM_operatortype_append(FILE_OT_select);+ WM_operatortype_append(FILE_OT_select_walk);+ WM_operatortype_append(FILE_OT_select_all);+ WM_operatortype_append(FILE_OT_select_box);+ WM_operatortype_append(FILE_OT_select_bookmark);+ WM_operatortype_append(FILE_OT_highlight);+ WM_operatortype_append(FILE_OT_sort_column_ui_context);+ WM_operatortype_append(FILE_OT_execute);+ WM_operatortype_append(FILE_OT_mouse_execute);+ WM_operatortype_append(FILE_OT_cancel);+ WM_operatortype_append(FILE_OT_parent);+ WM_operatortype_append(FILE_OT_previous);+ WM_operatortype_append(FILE_OT_next);+ WM_operatortype_append(FILE_OT_refresh);+ WM_operatortype_append(FILE_OT_bookmark_add);+ WM_operatortype_append(FILE_OT_bookmark_delete);+ WM_operatortype_append(FILE_OT_bookmark_cleanup);+ WM_operatortype_append(FILE_OT_bookmark_move);+ WM_operatortype_append(FILE_OT_reset_recent);+ WM_operatortype_append(FILE_OT_hidedot);+ WM_operatortype_append(FILE_OT_filenum);+ WM_operatortype_append(FILE_OT_directory_new);+ WM_operatortype_append(FILE_OT_delete);+ WM_operatortype_append(FILE_OT_rename);+ WM_operatortype_append(FILE_OT_smoothscroll);+ WM_operatortype_append(FILE_OT_filepath_drop);+ WM_operatortype_append(FILE_OT_start_filter);+ WM_operatortype_append(FILE_OT_edit_directory_path);+ WM_operatortype_append(FILE_OT_view_selected);+ WM_operatortype_append(FILE_OT_external_operation);+}++/* NOTE: do not add .blend file reading on this level */+static void file_keymap(wmKeyConfig *keyconf)+{+ /* keys for all regions */+ WM_keymap_ensure(keyconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);++ /* keys for main region */+ WM_keymap_ensure(keyconf, "File Browser Main", SPACE_FILE, RGN_TYPE_WINDOW);++ /* keys for button region (top) */+ WM_keymap_ensure(keyconf, "File Browser Buttons", SPACE_FILE, RGN_TYPE_WINDOW);+}++static bool file_region_poll(const RegionPollParams *params)+{+ const SpaceFile *sfile = params->area->spacedata.first_as<SpaceFile>();+ /* Always visible except when browsing assets. */+ return sfile->browse_mode != FILE_BROWSE_MODE_ASSETS;+}++static bool file_tool_props_region_poll(const RegionPollParams *params)+{+ const SpaceFile *sfile = params->area->spacedata.first_as<SpaceFile>();+ return (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS) || (sfile->op != nullptr);+}++static bool file_execution_region_poll(const RegionPollParams *params)+{+ const SpaceFile *sfile = params->area->spacedata.first_as<SpaceFile>();+ return sfile->op != nullptr;+}++static void file_tools_region_init(wmWindowManager *wm, ARegion *region)+{+ wmKeyMap *keymap;++ region->v2d.scroll = V2D_SCROLL_RIGHT | V2D_SCROLL_VERTICAL_HIDE;+ ED_region_panels_init(wm, region);++ /* own keymaps */+ keymap = WM_keymap_ensure(wm->runtime->defaultconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);+}++static void file_tools_region_draw(const bContext *C, ARegion *region)+{+ ED_region_panels(C, region);+}++static void file_tools_region_listener(const wmRegionListenerParams *listener_params)+{+ const wmNotifier *wmn = listener_params->notifier;+ ARegion *region = listener_params->region;++ switch (wmn->category) {+ case NC_SCENE:+ if (ELEM(wmn->data, ND_MODE)) {+ ED_region_tag_redraw(region);+ }+ break;+ }+}++static void file_tool_props_region_listener(const wmRegionListenerParams *listener_params)+{+ const wmNotifier *wmn = listener_params->notifier;+ ARegion *region = listener_params->region;++ switch (wmn->category) {+ case NC_ID:+ if (ELEM(wmn->action, NA_RENAME)) {+ /* In case the filelist shows ID names. */+ ED_region_tag_redraw(region);+ }+ break;+ case NC_SCENE:+ if (ELEM(wmn->data, ND_MODE)) {+ ED_region_tag_redraw(region);+ }+ break;+ }+}++/* add handlers, stuff you only do once or on area/region changes */+static void file_header_region_init(wmWindowManager *wm, ARegion *region)+{+ wmKeyMap *keymap;++ ED_region_header_init(region);++ keymap = WM_keymap_ensure(wm->runtime->defaultconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);+}++static void file_header_region_draw(const bContext *C, ARegion *region)+{+ ED_region_header(C, region);+}++/* add handlers, stuff you only do once or on area/region changes */+static void file_region_init(wmWindowManager *wm, ARegion *region)+{+ wmKeyMap *keymap;++ ED_region_panels_init(wm, region);+ region->v2d.keepzoom |= V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y;++ /* own keymap */+ keymap = WM_keymap_ensure(wm->runtime->defaultconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);++ keymap = WM_keymap_ensure(+ wm->runtime->defaultconf, "File Browser Buttons", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);+}++static void file_region_draw(const bContext *C, ARegion *region)+{+ ED_region_panels(C, region);+}++static void file_execution_region_init(wmWindowManager *wm, ARegion *region)+{+ wmKeyMap *keymap;++ ED_region_panels_init(wm, region);+ region->v2d.keepzoom |= V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y;++ /* own keymap */+ keymap = WM_keymap_ensure(wm->runtime->defaultconf, "File Browser", SPACE_FILE, RGN_TYPE_WINDOW);+ WM_event_add_keymap_handler_v2d_mask(®ion->runtime->handlers, keymap);+}++static void file_execution_region_draw(const bContext *C, ARegion *region)+{+ ED_region_panels(C, region);+}++static void file_region_listener(const wmRegionListenerParams *listener_params)+{+ ARegion *region = listener_params->region;+ const wmNotifier *wmn = listener_params->notifier;++ /* context changes */+ switch (wmn->category) {+ case NC_SPACE:+ switch (wmn->data) {+ case ND_SPACE_FILE_LIST:+ ED_region_tag_redraw(region);+ break;+ }+ break;+ }+}++static bool filepath_drop_poll(bContext *C, wmDrag *drag, const wmEvent * /*event*/)+{+ if (drag->type == WM_DRAG_PATH) {+ SpaceFile *sfile = CTX_wm_space_file(C);+ if (sfile) {+ return true;+ }+ }+ return false;+}++static void filepath_drop_copy(bContext * /*C*/, wmDrag *drag, wmDropBox *drop)+{+ RNA_string_set(drop->ptr, "filepath", WM_drag_get_single_path(drag));+}++/* region dropbox definition */+static void file_dropboxes()+{+ ListBaseT<wmDropBox> *lb = WM_dropboxmap_find("Window", SPACE_EMPTY, RGN_TYPE_WINDOW);++ WM_dropbox_add(+ lb, "FILE_OT_filepath_drop", filepath_drop_poll, filepath_drop_copy, nullptr, nullptr);+}++static int file_space_subtype_get(ScrArea *area)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ return sfile->browse_mode;+}++static void file_space_subtype_set(ScrArea *area, int value)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ /* Force re-init. */+ for (ARegion ®ion : area->regionbase) {+ region.v2d.flag &= ~V2D_IS_INIT;+ }++ /* Exit all data specific to the current browse mode when that changes. */+ if (sfile->browse_mode != eFileBrowse_Mode(value)) {+ wmWindowManager *wm = G_MAIN->wm.first();+ file_exit(wm, area);+ }++ sfile->browse_mode = eFileBrowse_Mode(value);+}++static void file_space_subtype_item_extend(bContext * /*C*/, EnumPropertyItem **item, int *totitem)+{+ RNA_enum_items_add(item, totitem, rna_enum_space_file_browse_mode_items);+}++static StringRefNull file_space_name_get(const ScrArea *area)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ const int index = RNA_enum_from_value(rna_enum_space_file_browse_mode_items, sfile->browse_mode);+ const EnumPropertyItem item = rna_enum_space_file_browse_mode_items[index];+ return item.name;+}++static int file_space_icon_get(const ScrArea *area)+{+ SpaceFile *sfile = area->spacedata.first_as<SpaceFile>();+ const int index = RNA_enum_from_value(rna_enum_space_file_browse_mode_items, sfile->browse_mode);+ const EnumPropertyItem item = rna_enum_space_file_browse_mode_items[index];+ return item.icon;+}++static void file_id_remap(ScrArea *area, SpaceLink *sl, const bke::id::IDRemapper & /*mappings*/)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(sl);++ /* If the file shows main data (IDs), tag it for reset.+ * Full reset of the file list if main data was changed, don't even attempt remap pointers.+ * We could give file list types a id-remap callback, but it's probably not worth it.+ * Refreshing local file lists is relatively cheap. */+ file_reset_filelist_showing_main_data(area, sfile);+}++static void file_foreach_id(SpaceLink *space_link, LibraryForeachIDData *data)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(space_link);+ const int data_flags = BKE_lib_query_foreachid_process_flags_get(data);+ const bool is_readonly = (data_flags & IDWALK_READONLY) != 0;++ /* TODO: investigate whether differences between this code and the one in #file_id_remap are+ * meaningful and make sense or not. */+ if (!is_readonly) {+ sfile->op = nullptr;+ sfile->tags = FILE_TAG_REBUILD_MAIN_FILES;+ }+}++static void file_space_blend_read_data(BlendDataReader *reader, SpaceLink *sl)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(sl);++ /* this sort of info is probably irrelevant for reloading...+ * plus, it isn't saved to files yet!+ */+ sfile->folders_prev = sfile->folders_next = nullptr;+ sfile->folder_histories.clear_no_delete();+ sfile->files = nullptr;+ sfile->layout = nullptr;+ sfile->op = nullptr;+ sfile->previews_timer = nullptr;+ sfile->tags = eFileTags{};+ sfile->runtime = nullptr;+ BLO_read_struct(reader, FileSelectParams, &sfile->params);+ BLO_read_struct(reader, FileAssetSelectParams, &sfile->asset_params);+ if (sfile->params) {+ sfile->params->rename_id = nullptr;+ }+ if (sfile->asset_params) {+ sfile->asset_params->base_params.rename_id = nullptr;+ /* Code (file-browser etc.) asserts that this setting is one of the currently known values.+ * So fall back to #FILE_ASSET_IMPORT_FOLLOW_PREFS if it is not+ * (e.g. because of forward-compatibility while reading a blend-file from the future). */+ switch (eFileAssetImportMethod(sfile->asset_params->import_method)) {+ case FILE_ASSET_IMPORT_LINK:+ case FILE_ASSET_IMPORT_APPEND:+ case FILE_ASSET_IMPORT_APPEND_REUSE:+ case FILE_ASSET_IMPORT_FOLLOW_PREFS:+ case FILE_ASSET_IMPORT_PACK:+ break;+ default:+ sfile->asset_params->import_method = FILE_ASSET_IMPORT_FOLLOW_PREFS;+ }+ }+}++static void file_space_blend_read_after_liblink(BlendLibReader * /*reader*/,+ ID * /*parent_id*/,+ SpaceLink *sl)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(sl);++ sfile->tags |= FILE_TAG_REBUILD_MAIN_FILES;+}++static void file_space_blend_write(BlendWriter *writer, SpaceLink *sl)+{+ SpaceFile *sfile = reinterpret_cast<SpaceFile *>(sl);++ writer->write_struct_cast<SpaceFile>(sl, [](BlendStructWriter<SpaceFile> &struct_writer) {+ struct_writer.shallow_data.runtime = nullptr;+ });+ if (sfile->params) {+ writer->write_struct(sfile->params);+ }+ if (sfile->asset_params) {+ writer->write_struct(sfile->asset_params);+ }+}++void ED_spacetype_file()+{+ std::unique_ptr<SpaceType> st = std::make_unique<SpaceType>();+ ARegionType *art;++ st->spaceid = SPACE_FILE;+ STRNCPY_UTF8(st->name, "File");+ st->struct_size = sizeof(SpaceFile);++ st->create = file_create;+ st->free = file_free;+ st->init = file_init;+ st->exit = file_exit;+ st->duplicate = file_duplicate;+ st->refresh = file_refresh;+ st->listener = file_listener;+ st->operatortypes = file_operatortypes;+ st->keymap = file_keymap;+ st->dropboxes = file_dropboxes;+ st->space_subtype_item_extend = file_space_subtype_item_extend;+ st->space_subtype_get = file_space_subtype_get;+ st->space_subtype_set = file_space_subtype_set;+ st->space_name_get = file_space_name_get;+ st->space_icon_get = file_space_icon_get;+ st->context = file_context;+ st->id_remap = file_id_remap;+ st->foreach_id = file_foreach_id;+ st->blend_read_data = file_space_blend_read_data;+ st->blend_read_after_liblink = file_space_blend_read_after_liblink;+ st->blend_write = file_space_blend_write;++ /* regions: main window */+ art = MEM_new_zeroed<ARegionType>("spacetype file region");+ art->regionid = RGN_TYPE_WINDOW;+ art->init = file_main_region_init;+ art->draw = file_main_region_draw;+ art->listener = file_main_region_listener;+ art->message_subscribe = file_main_region_message_subscribe;+ art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D;+ BLI_addhead(&st->regiontypes, art);++ /* regions: header */+ art = MEM_new_zeroed<ARegionType>("spacetype file region");+ art->regionid = RGN_TYPE_HEADER;+ art->prefsizey = HEADERY;+ art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_HEADER;+ art->init = file_header_region_init;+ art->draw = file_header_region_draw;+ // art->listener = file_header_region_listener;+ BLI_addhead(&st->regiontypes, art);++ /* regions: ui */+ art = MEM_new_zeroed<ARegionType>("spacetype file region");+ art->regionid = RGN_TYPE_UI;+ art->flag = ARegionTypeFlag::HideSinglePanelCategories;+ art->keymapflag = ED_KEYMAP_UI;+ art->poll = file_region_poll;+ art->listener = file_region_listener;+ art->init = file_region_init;+ art->draw = file_region_draw;+ BLI_addhead(&st->regiontypes, art);++ /* regions: execution */+ art = MEM_new_zeroed<ARegionType>("spacetype file region");+ art->regionid = RGN_TYPE_EXECUTE;+ art->keymapflag = ED_KEYMAP_UI;+ art->poll = file_execution_region_poll;+ art->listener = file_region_listener;+ art->init = file_execution_region_init;+ art->draw = file_execution_region_draw;+ BLI_addhead(&st->regiontypes, art);+ file_execute_region_panels_register(art);++ /* regions: channels (directories) */+ art = MEM_new_zeroed<ARegionType>("spacetype file region");+ art->regionid = RGN_TYPE_TOOLS;+ art->prefsizex = 240;+ art->prefsizey = 60;+ art->keymapflag = ED_KEYMAP_UI;+ art->listener = file_tools_region_listener;+ art->init = file_tools_region_init;+ art->draw = file_tools_region_draw;+ BLI_addhead(&st->regiontypes, art);+ file_tools_region_panels_register(art);++ /* regions: tool properties */+ art = MEM_new_zeroed<ARegionType>("spacetype file operator region");+ art->regionid = RGN_TYPE_TOOL_PROPS;+ art->prefsizex = 240;+ art->prefsizey = 60;+ art->keymapflag = ED_KEYMAP_UI;+ art->poll = file_tool_props_region_poll;+ art->listener = file_tool_props_region_listener;+ art->init = file_tools_region_init;+ art->draw = file_tools_region_draw;+ BLI_addhead(&st->regiontypes, art);+ file_tool_props_region_panels_register(art);+ file_external_operations_menu_register();++ BKE_spacetype_register(std::move(st));+}++void ED_file_init()+{+ ED_file_read_bookmarks();+ IMB_thumb_makedirs();+}++void ED_file_exit()+{+ fsmenu_free();++ if (G.background == false) {+ filelist_free_icons();+ }+}++void ED_file_read_bookmarks()+{+ const std::optional<std::string> cfgdir = BKE_appdir_folder_id(BLENDER_USER_CONFIG, nullptr);++ fsmenu_free();++ FSMenu *fsmenu = ED_fsmenu_get();++ const char *blendfile_path = BKE_main_blendfile_path_from_global();+ if (blendfile_path && blendfile_path[0]) {+ /* Folder containing the currently-loaded Blend file. */+ char dir[FILE_MAX];+ BLI_path_split_dir_part(blendfile_path, dir);+ fsmenu_insert_entry(fsmenu,+ FS_CATEGORY_SYSTEM_BOOKMARKS,+ dir,+ IFACE_("Current File"),+ FSMENU_CURRENT_FILE_ICON,+ FS_INSERT_FIRST);+ }++ fsmenu_read_system(fsmenu, true);+ fsmenu_add_common_platform_directories(fsmenu);++ if (cfgdir.has_value()) {+ char filepath[FILE_MAX];+ BLI_path_join(filepath, cfgdir->c_str(), BLENDER_BOOKMARK_FILE);+ fsmenu_read_bookmarks(fsmenu, filepath);+ }+}++} // namespace blender