Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

fix: math & search

Preetham Pemmasanie4a2810abbfe
diff --git a/AGENTS.md b/AGENTS.md
index e5cc6e6..666a128 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,3 +21,4 @@ These are recommended:
If writing Rust:
- STRICTLY DO NOT HAVE Rc<Refcell>. DO IT COMPILE TIME!! It just swaps gc for runtime borrow checks and refcount churn. you won't get real rust perf without a second pass flattening entitices into an arena or ECS with indices.
- Please have the clippy lints: all = { level = "warn", priority = -2 }, pedantic = { level = "warn", priority = -2 }, perf = { level = "warn", priority = -1 }, complexity = { level = "warn", priority = -1 }, inline_always = "allow", unseparated_literal_suffix = "allow", similar_names = "allow", missing_panics_doc = "allow", missing_errors_doc = "allow", absolute_paths = "allow", module_name_repetitions = "allow", doc_markdown = "allow", too_many_lines = "allow", unused_self = "allow", cast_possible_truncation = "allow", cast_sign_loss = "allow", cast_precision_loss = "allow", unreadable_literal = "allow", implicit_hasher = "allow", significant_drop_tightening = "warn", redundant_clone = "warn", use_self = "warn", redundant_else = "warn", or_fun_call = "warn", missing_const_for_fn = "warn", derive_partial_eq_without_eq = "warn"
+- Always NEVER ALLOCATE, try to use the refs, never clone unless necessary. even for strings, use CoW and refs.
diff --git a/README.md b/README.md
index 8102fab..3109140 100644
--- a/README.md
+++ b/README.md
@@ -45,9 +45,11 @@ You can drive it five ways, and all of them share the same C runtime:
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
| **tkinter** code, even existing programs, unchanged | Blender-styled apps; every tkinter and ttk API | ✅ Complete |
| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | 🟡 Partial |
-| **Blender components** in Python (`Panel`, `NumberSlider`, `PieMenu` ...) | 45 native Blender widgets and editors | ✅ Complete |
-| **Rust**: HTML + CSS + Tailwind, JSX (`rsx!`), hooks, or gpui syntax | A web-like framework: HTML that looks like a browser's, Blender's look with `styled`, and Blender components (`<NumberSlider>`, `<Button>` ...) | ✅ Working |
+| **Rust**: HTML + CSS + Tailwind, JSX (`rsx!`), hooks, or [gpui](https://www.gpui.rs) / [zopra](https://zopra.preetham.top) syntax | A web-like framework: HTML that looks like a browser's, Blender's look with `styled`, and Blender components (`<NumberSlider>`, `<Button>` ...) | ✅ Working |
| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine and components in native windows, over napi-rs; React's hooks backed by signals ([guide](docs/javascript.md)) | ✅ Working |
+| **Dear ImGUI** | Dear Imgui | ✅ Working |
+| **MyGo** | MyGo | 🟡 Not yet |
+| **Blender components** (framework agnostic) (`Panel`, `NumberSlider`, `PieMenu` ...) | 45 native Blender widgets and editors | ✅ Complete |
### HTML, Blender, or both
diff --git a/bindings/imgui/c/cimgui.h b/bindings/imgui/c/cimgui.h
index 41664e5..6906d56 100644
--- a/bindings/imgui/c/cimgui.h
+++ b/bindings/imgui/c/cimgui.h
@@ -995,8 +995,6 @@ enum ImGuiViewportFlags_ {
ImGuiViewportFlags_IsPlatformMonitor = 2,
ImGuiViewportFlags_OwnedByApp = 4,
};
-enum ImDrawListFlags_ {
-};
// Callbacks
typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data);
diff --git a/bindings/imgui/gen/gen.py b/bindings/imgui/gen/gen.py
index 0f4ef6e..d607d73 100644
--- a/bindings/imgui/gen/gen.py
+++ b/bindings/imgui/gen/gen.py
@@ -1104,10 +1104,11 @@ def emit_c(api, model):
if name and not name.endswith("_"):
w("typedef %s %s;" % (e["underlying"] or "int", name))
tag = name if name.endswith("_") else name + "_"
+ values = [v for v in e["values"] if not v["obsolete"]]
+ if not values:
+ continue # C has no empty enums (gcc: "empty enum is invalid")
w("enum %s {" % tag)
- for v in e["values"]:
- if v["obsolete"]:
- continue
+ for v in values:
w(" %s = %d," % (v["name"], v["value"]))
w("};")
w("")
diff --git a/bindings/python/tests/__pycache__/test_components.cpython-314.pyc b/bindings/python/tests/__pycache__/test_components.cpython-314.pyc
index d88b668..82a572d 100644
Binary files a/bindings/python/tests/__pycache__/test_components.cpython-314.pyc and b/bindings/python/tests/__pycache__/test_components.cpython-314.pyc differ
diff --git a/bindings/python/tests/test_components.py b/bindings/python/tests/test_components.py
index 783381e..bf886dc 100644
--- a/bindings/python/tests/test_components.py
+++ b/bindings/python/tests/test_components.py
@@ -305,12 +305,55 @@ def test_disabled_ignores_input():
assert f.value == 1.0 and not f.editing
+def test_text_edit_undo():
+ """Ctrl+Z / Ctrl+Shift+Z inside an active text edit (Blender's interface_undo.cc)."""
+ t = TextField("", "")
+ d = Driver(t)
+ d.click(t)
+ d.type("abc")
+ assert t.get_str("edit") == "abc"
+ d.key("z", "z", mods(ctrl=True))
+ assert t.get_str("edit") == "ab", t.get_str("edit")
+ d.key("z", "z", mods(ctrl=True))
+ d.key("z", "z", mods(ctrl=True))
+ assert t.get_str("edit") == ""
+ d.key("z", "z", mods(ctrl=True)) # nothing before the start
+ assert t.get_str("edit") == ""
+ d.key("Z", "Z", mods(ctrl=True, shift=True)) # redo
+ d.key("y", "y", mods(ctrl=True))
+ assert t.get_str("edit") == "ab", t.get_str("edit")
+ d.type("X") # new typing drops the redo states
+ d.key("Z", "Z", mods(ctrl=True, shift=True))
+ assert t.get_str("edit") == "abX"
+ d.key("Return")
+ assert t.value == "abX"
+
+
+def test_float_display_precision():
+ """Blender's UI_calc_float_precision: small values get the decimals they need."""
+ f = NumberField("", 0.00002) # precision 3 would read "0.000"
+ assert f.get_str("display") == "0.0000", f.get_str("display") # Blender's digit count
+ f.value = 0.000123
+ assert f.get_str("display") == "0.00012", f.get_str("display")
+ f.value = 1.5
+ assert f.get_str("display") == "1.500"
+ f.value = 10.0001 # only small values get more
+ assert f.get_str("display") == "10.000"
+
+
def test_eval_number():
assert abs(eval_number("2*pi") - 2 * 3.141592653589793) < 1e-12
assert eval_number("__import__('os')") is None
assert eval_number("1/0") is None
assert eval_number("10 ** 2 - 1") == 99
assert eval_number("2^3") == 8 and eval_number("sqrt(16)") == 4
+ # Blender's expr_pylike_eval (core/intern): its functions, conditionals and min/max
+ assert eval_number("max(1, 7, 3) + min(4, 2)") == 9
+ assert eval_number("1 if 3 > 2 else 0") == 1
+ assert abs(eval_number("atan2(1, 1)") - 3.141592653589793 / 4) < 1e-12
+ assert eval_number("7 // 2") == 3 and eval_number("7 % 4") == 3
+ assert abs(eval_number("tau - 2*pi")) < 1e-12 and abs(eval_number("e") - 2.718281828459045) < 1e-12
+ assert eval_number("1 +") is None
# -- cursors, continuous grab, context menus -------------------------------------
@@ -383,6 +426,40 @@ def test_menu_search_submenu_and_bar():
assert picked == ["a"] and not d.popups()
+def test_menu_search_fuzzy():
+ """Blender's string search (blenlib string_search.cc): word initials, typos, recent first."""
+ from bui.components import MenuBar, MenuItem
+ names = ["Shade Smooth", "Subdivision Surface", "Add Cube", "Add Cylinder", "Separate"]
+ picked = []
+ bar = MenuBar(("Object", [MenuItem(n, (lambda n=n: picked.append(n))) for n in names]))
+ d = Driver(Label("body"), header=bar)
+ (obj_b,) = bar.buttons
+
+ def search(q):
+ d.click(obj_b)
+ d.type(q)
+ rows = [t for t, _ in d.ctx.menu_rows(0)]
+ return rows
+
+ rows = search("ss") # word-initial match
+ assert set(rows[:2]) == {"Shade Smooth", "Subdivision Surface"}, rows
+ d.ctx.close_popups()
+ rows = search("cylnder") # a typo still finds it
+ assert rows and rows[0] == "Add Cylinder", rows
+ d.ctx.close_popups()
+ assert search("zzzz") == [] # no substring fallback junk
+ d.ctx.close_popups()
+ # choosing an item makes it rank first next time for a short query
+ rows = search("s")
+ i = rows.index("Separate")
+ for _ in range(i):
+ d.key("Down")
+ d.key("Return")
+ assert picked == ["Separate"]
+ assert search("s")[0] == "Separate"
+ d.ctx.close_popups()
+
+
def test_press_drag_release_picks():
dd = Dropdown("", ["One", "Two", "Three"])
d = Driver(dd)
@@ -710,6 +787,34 @@ def test_vertical_multi_drag():
assert [f.value for f in fields] == [0.0, 0.0, 0.0]
+def test_panel_animation_timing():
+ """Blender's interface_panel.cc do_animate: ANIMATION_TIME 0.30 s eased by sqrt(fac)."""
+ buipy.kit_set_animations(True)
+ try:
+ p = Panel("One", Column(*[Button(str(i)) for i in range(12)]))
+ d = Driver(p, Button("after"))
+ h_open = p.h
+ t0 = time.perf_counter()
+ d.click(at=(p.x + 20, p.y + 5))
+ d.frame()
+ samples = []
+ while d.ctx.animating() and time.perf_counter() - t0 < 2:
+ time.sleep(0.005)
+ d.frame()
+ samples.append((time.perf_counter() - t0, p.h))
+ took = samples[-1][0]
+ h_closed = p.h
+ assert 0.25 < took < 0.6, took # ~0.30 s (was a linear 0.12 s)
+ # sqrt easing: a third of the way in, it has moved well over a third
+ early = [(t, hh) for t, hh in samples if 0.06 < t < 0.10]
+ assert early, samples
+ t, hh = early[0]
+ moved = (h_open - hh) / (h_open - h_closed)
+ assert moved > (t / 0.30) + 0.1, (t, moved)
+ finally:
+ buipy.kit_set_animations(False)
+
+
def test_panel_animation():
buipy.kit_set_animations(True)
try:
diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rs
index 369a435..85fb63c 100644
--- a/bindings/rust/blenderui-sys/build.rs
+++ b/bindings/rust/blenderui-sys/build.rs
@@ -56,8 +56,9 @@ fn main() {
println!("cargo:rustc-link-lib=static={lib}");
}
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
- if imgui && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() != Ok("msvc") {
- // the C++ runtime of Dear ImGui (MSVC links its own)
+ if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() != Ok("msvc") {
+ // the C++ runtime: the kit and core carry Blender C++ sources (string
+ // search, expressions, ...), and Dear ImGui with `imgui` (MSVC links its own)
println!("cargo:rustc-link-lib={}", if target == "macos" { "c++" } else { "stdc++" });
}
if target == "windows" {
diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt
index bcea937..1e56f9a 100644
--- a/core/CMakeLists.txt
+++ b/core/CMakeLists.txt
@@ -37,7 +37,34 @@ set(SRC
intern/wcwidth/wcwidth.c
)
-add_library(bui_core STATIC ${SRC})
+# Blender C++ (blenlib) used through C wrappers (include/BUI_blender_c.h):
+# an object library (no forced C shim) whose objects go into bui_core.
+add_library(bui_core_cxx OBJECT
+ intern/expr_pylike_eval.cc
+ intern/string_search.cc
+ intern/bui_blender_c.cc
+)
+target_include_directories(bui_core_cxx PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/include
+ ${CMAKE_SOURCE_DIR}/types/dna/include
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}/intern
+)
+
+add_library(bui_core STATIC ${SRC} $<TARGET_OBJECTS:bui_core_cxx>)
+
+# Blender builds with unsigned `char` (-funsigned-char, /J); blenlib's UTF-8
+# decoding (string_utf8.c, `c < 128` / `c >= 192` tests) depends on it.
+foreach(_t bui_core bui_core_cxx)
+ if(MSVC)
+ target_compile_options(${_t} PRIVATE /J)
+ else()
+ target_compile_options(${_t} PRIVATE -funsigned-char)
+ endif()
+endforeach()
+if(MSVC)
+ target_compile_options(bui_core_cxx PRIVATE /permissive-)
+endif()
add_library(bui::core ALIAS bui_core)
target_include_directories(bui_core PUBLIC
diff --git a/core/include/BLI_assert.h b/core/include/BLI_assert.h
index 493579c..26de153 100644
--- a/core/include/BLI_assert.h
+++ b/core/include/BLI_assert.h
@@ -17,11 +17,18 @@
/* Utility functions. */
+/* BUI: BLI_assert.c is C; C linkage for the C++ sources in core/intern. */
+#ifdef __cplusplus
+extern "C" {
+#endif
void _BLI_assert_print_pos(const char *file, int line, const char *function, const char *id);
void _BLI_assert_print_extra(const char *str);
-void _BLI_assert_print_backtrace();
-void _BLI_assert_abort();
+void _BLI_assert_print_backtrace(void);
+void _BLI_assert_abort(void);
void _BLI_assert_unreachable_print(const char *file, int line, const char *function);
+#ifdef __cplusplus
+}
+#endif
#ifdef _MSC_VER
# include <crtdbg.h> /* for _STATIC_ASSERT */
diff --git a/core/include/BLI_string.h b/core/include/BLI_string.h
index c9913b2..41d246a 100644
--- a/core/include/BLI_string.h
+++ b/core/include/BLI_string.h
@@ -18,6 +18,11 @@
# include <string>
#endif
+/* BUI: string.c is compiled as C; C++ callers (core/intern/*.cc) need C linkage. */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
/* Buffer size of maximum `uint64` plus commas and terminator. */
#define BLI_STR_FORMAT_UINT64_GROUPED_SIZE 27
@@ -241,7 +246,7 @@ size_t BLI_str_escape(char *__restrict dst, const char *__restrict src, size_t d
#ifdef __cplusplus
/** Same as above, but returns an std::string. */
-std::string BLI_str_escape(const char *str);
+extern "C++" std::string BLI_str_escape(const char *str); /* BUI: extern "C++" */
#endif
/**
@@ -694,8 +699,14 @@ void BLI_string_debug_size_after_nil(char *str, size_t str_maxncpy);
/* Upstream-compatible safe copy for fixed-size char arrays. */
#ifdef __cplusplus
+extern "C++" { /* BUI */
template<size_t N> inline char *STRNCPY(char (&dst)[N], const char *src)
{
return BLI_strncpy(dst, src, N);
}
+}
+#endif
+
+#ifdef __cplusplus
+} /* BUI: extern "C" */
#endif
diff --git a/core/include/BLI_string_utf8.h b/core/include/BLI_string_utf8.h
index 663f079..fdfadfd 100644
--- a/core/include/BLI_string_utf8.h
+++ b/core/include/BLI_string_utf8.h
@@ -13,6 +13,11 @@
#include "BLI_compiler_attrs.h"
#include "BLI_sys_types.h"
+/* BUI: string_utf8.c is compiled as C; C++ callers need C linkage. */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
char *BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy)
ATTR_NONNULL(1, 2);
@@ -348,3 +353,7 @@ int BLI_str_utf8_column_count(const char *str, size_t str_len) ATTR_WARN_UNUSED_
+
+#ifdef __cplusplus
+} /* BUI: extern "C" */
+#endif
diff --git a/core/include/BUI_blender_c.h b/core/include/BUI_blender_c.h
new file mode 100644
index 0000000..ce16cb7
--- /dev/null
+++ b/core/include/BUI_blender_c.h
@@ -0,0 +1,38 @@
+/* C entry points to Blender C++ code vendored in core/ (blenlib):
+ * - expr_pylike_eval.cc: the number-field expression evaluator,
+ * - string_search.cc: Blender's fuzzy search (menu search, search fields).
+ * Implemented in core/intern/bui_blender_c.cc.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Evaluate a Python-like expression (BLI_expr_pylike_eval): numbers, + - * / // % ** ^,
+ * comparisons, and/or/not, x if c else y, pi e tau, sin cos sqrt ... min max.
+ * Optional named parameters. Returns 1 and sets *r_value on success, 0 on a
+ * parse error, division by zero or a non-finite result. */
+int BUI_expr_eval(const char *expr,
+ const char **param_names,
+ const double *param_values,
+ int params_len,
+ double *r_value);
+
+/* blender::string_search::StringSearch<void>. `recent_cache` is a
+ * blender::string_search::RecentCache (or NULL), e.g. bk_recent_search_cache(). */
+typedef struct BUIStringSearch BUIStringSearch;
+enum { BUI_SEARCH_MAIN_FIRST = 0, BUI_SEARCH_MAIN_LAST = 1, BUI_SEARCH_MAIN_ALL = 2 };
+BUIStringSearch *BUI_string_search_new(const void *recent_cache, int main_words_heuristic);
+void BUI_string_search_add(BUIStringSearch *search, const char *str, void *user_data, int weight);
+/* Filters and sorts the added items for `query`; writes at most `max` user
+ * data pointers, best first. Returns the number of matches (may exceed max). */
+int BUI_string_search_query(BUIStringSearch *search, const char *query, void **r_items, int max);
+void BUI_string_search_free(BUIStringSearch *search);
+/* blender::string_search::get_fuzzy_match_errors: -1 no match, else typo count. */
+int BUI_string_search_fuzzy_errors(const char *query, const char *full);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/core/include/MEM_guardedalloc.h b/core/include/MEM_guardedalloc.h
index 68ef94c..8f50978 100644
--- a/core/include/MEM_guardedalloc.h
+++ b/core/include/MEM_guardedalloc.h
@@ -12,13 +12,6 @@
/* Upstream reserves bytes for per-block bookkeeping; this shim keeps none. */
#define MEM_SIZE_OVERHEAD ((size_t)0)
-/* Modern MEM API used by the C++ BLI headers. */
-void *MEM_new_uninitialized(size_t size, const char *name);
-void *MEM_new_zeroed(size_t size, const char *name);
-void *MEM_new_uninitialized_aligned(size_t size, size_t alignment, const char *name);
-void MEM_delete_void(void *ptr);
-void *MEM_dupalloc_void(const void *vmemh);
-
/* Alignment guaranteed by MEM_new_zeroed / malloc on all supported targets. */
#define MEM_MIN_CPP_ALIGNMENT ((size_t)16)
@@ -26,6 +19,14 @@ void *MEM_dupalloc_void(const void *vmemh);
extern "C" {
#endif
+/* Modern MEM API used by the C++ BLI headers (C linkage: guardedalloc.c is C,
+ * and core/intern/*.cc call it). */
+void *MEM_new_uninitialized(size_t size, const char *name);
+void *MEM_new_zeroed(size_t size, const char *name);
+void *MEM_new_uninitialized_aligned(size_t size, size_t alignment, const char *name);
+void MEM_delete_void(void *ptr);
+void *MEM_dupalloc_void(const void *vmemh);
+
void *MEM_mallocN(size_t len, const char *str);
void *MEM_malloc_arrayN(size_t len, size_t size, const char *str);
void *MEM_mallocN_aligned(size_t len, size_t alignment, const char *str);
diff --git a/core/intern/bui_blender_c.cc b/core/intern/bui_blender_c.cc
new file mode 100644
index 0000000..fea6013
--- /dev/null
+++ b/core/intern/bui_blender_c.cc
@@ -0,0 +1,76 @@
+/* C wrappers over the Blender C++ code vendored in core/ (see BUI_blender_c.h).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <cmath>
+
+#include "BLI_expr_pylike_eval.h"
+#include "BLI_string_search.hh"
+
+#include "BUI_blender_c.h"
+
+using namespace blender;
+
+int BUI_expr_eval(const char *expr,
+ const char **param_names,
+ const double *param_values,
+ int params_len,
+ double *r_value)
+{
+ if (expr == nullptr) {
+ return 0;
+ }
+ ExprPyLike_Parsed *parsed = BLI_expr_pylike_parse(expr, param_names, params_len);
+ double value = 0.0;
+ int ok = 0;
+ if (BLI_expr_pylike_is_valid(parsed)) {
+ ok = BLI_expr_pylike_eval(parsed, param_values, params_len, &value) == EXPR_PYLIKE_SUCCESS &&
+ std::isfinite(value);
+ }
+ BLI_expr_pylike_free(parsed);
+ if (ok) {
+ *r_value = value;
+ }
+ return ok;
+}
+
+struct BUIStringSearch {
+ string_search::StringSearch<void> search;
+ BUIStringSearch(const string_search::RecentCache *cache, string_search::MainWordsHeuristic h)
+ : search(cache, h)
+ {
+ }
+};
+
+BUIStringSearch *BUI_string_search_new(const void *recent_cache, int main_words_heuristic)
+{
+ const string_search::MainWordsHeuristic h =
+ main_words_heuristic == BUI_SEARCH_MAIN_LAST ? string_search::MainWordsHeuristic::LastGroup :
+ main_words_heuristic == BUI_SEARCH_MAIN_ALL ? string_search::MainWordsHeuristic::All :
+ string_search::MainWordsHeuristic::FirstGroup;
+ return new BUIStringSearch(static_cast<const string_search::RecentCache *>(recent_cache), h);
+}
+
+void BUI_string_search_add(BUIStringSearch *search, const char *str, void *user_data, int weight)
+{
+ search->search.add(StringRef(str ? str : ""), user_data, weight);
+}
+
+int BUI_string_search_query(BUIStringSearch *search, const char *query, void **r_items, int max)
+{
+ const Vector<void *> found = search->search.query(StringRef(query ? query : ""));
+ for (int i = 0; i < int(found.size()) && i < max; i++) {
+ r_items[i] = found[i];
+ }
+ return int(found.size());
+}
+
+void BUI_string_search_free(BUIStringSearch *search)
+{
+ delete search;
+}
+
+int BUI_string_search_fuzzy_errors(const char *query, const char *full)
+{
+ return string_search::get_fuzzy_match_errors(StringRef(query), StringRef(full));
+}
diff --git a/core/intern/expr_pylike_eval.cc b/core/intern/expr_pylike_eval.cc
new file mode 100644
index 0000000..6e480e6
--- /dev/null
+++ b/core/intern/expr_pylike_eval.cc
@@ -0,0 +1,1139 @@
+/* SPDX-FileCopyrightText: 2018 Blender Authors, Alexander Gavrilov. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ *
+ * Simple evaluator for a subset of Python expressions that can be
+ * computed using purely double precision floating point values.
+ *
+ * Supported subset:
+ *
+ * - Identifiers use only ASCII characters.
+ * - Literals:
+ * floating point and decimal integer.
+ * - Constants:
+ * pi, True, False
+ * - Operators:
+ * +, -, *, /, ==, !=, <, <=, >, >=, and, or, not, ternary if
+ * - Functions:
+ * min, max, radians, degrees,
+ * abs, fabs, floor, ceil, trunc, int,
+ * sin, cos, tan, asin, acos, atan, atan2,
+ * exp, log, sqrt, pow, fmod
+ *
+ * The implementation has no global state and can be used multi-threaded.
+ *
+ * BUI: copied from blenlib/intern/expr_pylike_eval.cc for number-field input
+ * (BK_eval_number, kit/intern/kit_core.c). BUI edits, each marked "BUI:":
+ * the `e` and `tau` constants, the power operators `**` and `^`, floor
+ * division `//` and modulo `%` (the kit's number input always accepted
+ * them), and leading zeros ("05") are allowed.
+ */
+
+#include <cctype>
+#include <cfenv>
+#include <cmath>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <variant>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_alloca.h"
+#include "BLI_expr_pylike_eval.h"
+#include "BLI_math_base.h"
+#include "BLI_utildefines.h"
+#include "BLI_vector.hh"
+
+namespace blender {
+
+#ifdef _MSC_VER
+# pragma fenv_access(on)
+#endif
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Types
+ * \{ */
+
+enum eOpCode {
+ /** Double constant: `(-> dval)`. */
+ OPCODE_CONST,
+ /** 1 argument function call: `(a -> func1(a))`. */
+ OPCODE_FUNC1,
+ /** 2 argument function call: `(a b -> func2(a,b))`. */
+ OPCODE_FUNC2,
+ /** 3 argument function call: `(a b c -> func3(a,b,c))`. */
+ OPCODE_FUNC3,
+ /** Parameter access: `(-> params[ival])`. */
+ OPCODE_PARAMETER,
+ /** Minimum of multiple inputs: `(a b c... -> min); ival = arg count`. */
+ OPCODE_MIN,
+ /** Maximum of multiple inputs: `(a b c... -> max); ival = arg count`. */
+ OPCODE_MAX,
+ /** Jump `(pc += jmp_offset)` */
+ OPCODE_JMP,
+ /** Pop and jump if zero: `(a -> ); JUMP IF NOT a`. */
+ OPCODE_JMP_ELSE,
+ /** Jump if nonzero, or pop: `(a -> a JUMP) IF a ELSE (a -> )`. */
+ OPCODE_JMP_OR,
+ /** Jump if zero, or pop: `(a -> a JUMP) IF NOT a ELSE (a -> )`. */
+ OPCODE_JMP_AND,
+ /** For comparison chaining: `(a b -> 0 JUMP) IF NOT func2(a,b) ELSE (a b -> b)`. */
+ OPCODE_CMP_CHAIN,
+};
+
+using UnaryOpFunc = double (*)(double);
+using BinaryOpFunc = double (*)(double, double);
+using TernaryOpFunc = double (*)(double, double, double);
+
+struct ExprOp {
+ eOpCode opcode;
+
+ int jmp_offset;
+
+ union {
+ int ival;
+ double dval;
+ void *ptr;
+ UnaryOpFunc func1;
+ BinaryOpFunc func2;
+ TernaryOpFunc func3;
+ } arg;
+};
+
+struct ExprPyLike_Parsed {
+ Vector<ExprOp> ops;
+ int max_stack;
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Public API
+ * \{ */
+
+void BLI_expr_pylike_free(ExprPyLike_Parsed *expr)
+{
+ MEM_delete(expr);
+}
+
+bool BLI_expr_pylike_is_valid(const ExprPyLike_Parsed *expr)
+{
+ return expr != nullptr && expr->ops.size() > 0;
+}
+
+bool BLI_expr_pylike_is_constant(const ExprPyLike_Parsed *expr)
+{
+ return expr != nullptr && expr->ops.size() == 1 && expr->ops[0].opcode == OPCODE_CONST;
+}
+
+bool BLI_expr_pylike_is_using_param(const ExprPyLike_Parsed *expr, int index)
+{
+ int i;
+
+ if (expr == nullptr) {
+ return false;
+ }
+
+ for (i = 0; i < expr->ops.size(); i++) {
+ if (expr->ops[i].opcode == OPCODE_PARAMETER && expr->ops[i].arg.ival == index) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Stack Machine Evaluation
+ * \{ */
+
+eExprPyLike_EvalStatus BLI_expr_pylike_eval(ExprPyLike_Parsed *expr,
+ const double *param_values,
+ int param_values_len,
+ double *r_result)
+{
+ *r_result = 0.0;
+
+ if (!BLI_expr_pylike_is_valid(expr)) {
+ return EXPR_PYLIKE_INVALID;
+ }
+
+#define FAIL_IF(condition) \
+ if (condition) { \
+ return EXPR_PYLIKE_FATAL_ERROR; \
+ } \
+ ((void)0)
+
+ /* Check the stack requirement is at least remotely sane and allocate on the actual stack. */
+ FAIL_IF(expr->max_stack <= 0 || expr->max_stack > 1000);
+
+ double *stack = BLI_array_alloca(stack, expr->max_stack);
+
+ /* Evaluate expression. */
+ ExprOp *ops = expr->ops.data();
+ int sp = 0, pc;
+
+ feclearexcept(FE_ALL_EXCEPT);
+
+ for (pc = 0; pc >= 0 && pc < expr->ops.size(); pc++) {
+ switch (ops[pc].opcode) {
+ /* Arithmetic */
+ case OPCODE_CONST:
+ FAIL_IF(sp >= expr->max_stack);
+ stack[sp++] = ops[pc].arg.dval;
+ break;
+ case OPCODE_PARAMETER:
+ FAIL_IF(sp >= expr->max_stack || ops[pc].arg.ival >= param_values_len);
+ stack[sp++] = param_values[ops[pc].arg.ival];
+ break;
+ case OPCODE_FUNC1:
+ FAIL_IF(sp < 1);
+ stack[sp - 1] = ops[pc].arg.func1(stack[sp - 1]);
+ break;
+ case OPCODE_FUNC2:
+ FAIL_IF(sp < 2);
+ stack[sp - 2] = ops[pc].arg.func2(stack[sp - 2], stack[sp - 1]);
+ sp--;
+ break;
+ case OPCODE_FUNC3:
+ FAIL_IF(sp < 3);
+ stack[sp - 3] = ops[pc].arg.func3(stack[sp - 3], stack[sp - 2], stack[sp - 1]);
+ sp -= 2;
+ break;
+ case OPCODE_MIN:
+ FAIL_IF(sp < ops[pc].arg.ival);
+ for (int j = 1; j < ops[pc].arg.ival; j++, sp--) {
+ CLAMP_MAX(stack[sp - 2], stack[sp - 1]);
+ }
+ break;
+ case OPCODE_MAX:
+ FAIL_IF(sp < ops[pc].arg.ival);
+ for (int j = 1; j < ops[pc].arg.ival; j++, sp--) {
+ CLAMP_MIN(stack[sp - 2], stack[sp - 1]);
+ }
+ break;
+
+ /* Jumps */
+ case OPCODE_JMP:
+ pc += ops[pc].jmp_offset;
+ break;
+ case OPCODE_JMP_ELSE:
+ FAIL_IF(sp < 1);
+ if (!stack[--sp]) {
+ pc += ops[pc].jmp_offset;
+ }
+ break;
+ case OPCODE_JMP_OR:
+ case OPCODE_JMP_AND:
+ FAIL_IF(sp < 1);
+ if (!stack[sp - 1] == !(ops[pc].opcode == OPCODE_JMP_OR)) {
+ pc += ops[pc].jmp_offset;
+ }
+ else {
+ sp--;
+ }
+ break;
+
+ /* For chaining comparisons, i.e. "a < b < c" as "a < b and b < c" */
+ case OPCODE_CMP_CHAIN:
+ FAIL_IF(sp < 2);
+ /* If comparison fails, return 0 and jump to end. */
+ if (!ops[pc].arg.func2(stack[sp - 2], stack[sp - 1])) {
+ stack[sp - 2] = 0.0;
+ pc += ops[pc].jmp_offset;
+ }
+ /* Otherwise keep b on the stack and proceed. */
+ else {
+ stack[sp - 2] = stack[sp - 1];
+ }
+ sp--;
+ break;
+
+ default:
+ return EXPR_PYLIKE_FATAL_ERROR;
+ }
+ }
+
+ FAIL_IF(sp != 1 || pc != expr->ops.size());
+
+#undef FAIL_IF
+
+ *r_result = stack[0];
+
+ /* Detect floating point evaluation errors. */
+ int flags = fetestexcept(FE_DIVBYZERO | FE_INVALID);
+ if (flags) {
+ return (flags & FE_INVALID) ? EXPR_PYLIKE_MATH_ERROR : EXPR_PYLIKE_DIV_BY_ZERO;
+ }
+
+ return EXPR_PYLIKE_SUCCESS;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Built-In Operations
+ * \{ */
+
+static double op_negate(double arg)
+{
+ return -arg;
+}
+
+static double op_mul(double a, double b)
+{
+ return a * b;
+}
+
+static double op_div(double a, double b)
+{
+ return a / b;
+}
+
+static double op_add(double a, double b)
+{
+ return a + b;
+}
+
+static double op_sub(double a, double b)
+{
+ return a - b;
+}
+
+/* BUI: `**` / `^`, `//` and `%` (C fmod, as the kit's number input had). */
+static double op_pow(double a, double b)
+{
+ return pow(a, b);
+}
+
+static double op_floordiv(double a, double b)
+{
+ return floor(a / b);
+}
+
+static double op_mod(double a, double b)
+{
+ if (b == 0.0) {
+ return a / b; /* raise FE_DIVBYZERO like `/` */
+ }
+ return fmod(a, b);
+}
+
+static double op_radians(double arg)
+{
+ return arg * M_PI / 180.0;
+}
+
+static double op_degrees(double arg)
+{
+ return arg * 180.0 / M_PI;
+}
+
+static double op_log2(double a, double b)
+{
+ return log(a) / log(b);
+}
+
+static double op_lerp(double a, double b, double x)
+{
+ return a * (1.0 - x) + b * x;
+}
+
+static double op_clamp(double arg)
+{
+ CLAMP(arg, 0.0, 1.0);
+ return arg;
+}
+
+static double op_clamp3(double arg, double minv, double maxv)
+{
+ CLAMP(arg, minv, maxv);
+ return arg;
+}
+
+static double op_smoothstep(double a, double b, double x)
+{
+ double t = (x - a) / (b - a);
+ CLAMP(t, 0.0, 1.0);
+ return t * t * (3.0 - 2.0 * t);
+}
+
+static double op_not(double a)
+{
+ return a ? 0.0 : 1.0;
+}
+
+static double op_eq(double a, double b)
+{
+ return a == b ? 1.0 : 0.0;
+}
+
+static double op_ne(double a, double b)
+{
+ return a != b ? 1.0 : 0.0;
+}
+
+static double op_lt(double a, double b)
+{
+ return a < b ? 1.0 : 0.0;
+}
+
+static double op_le(double a, double b)
+{
+ return a <= b ? 1.0 : 0.0;
+}
+
+static double op_gt(double a, double b)
+{
+ return a > b ? 1.0 : 0.0;
+}
+
+static double op_ge(double a, double b)
+{
+ return a >= b ? 1.0 : 0.0;
+}
+
+struct BuiltinConstDef {
+ const char *name;
+ double value;
+};
+
+static BuiltinConstDef builtin_consts[] = {
+ /* BUI: `e` and `tau`. */
+ {"pi", M_PI},
+ {"e", M_E},
+ {"tau", 2.0 * M_PI},
+ {"True", 1.0},
+ {"False", 0.0},
+ {nullptr, 0.0}};
+
+struct BuiltinOpDef {
+ const char *name;
+ std::variant<UnaryOpFunc, BinaryOpFunc, TernaryOpFunc> funcptr;
+
+ /* Returns the required argument count of the given function call code. */
+ int arg_count()
+ {
+ if (std::holds_alternative<UnaryOpFunc>(funcptr)) {
+ return 1;
+ }
+ if (std::holds_alternative<BinaryOpFunc>(funcptr)) {
+ return 2;
+ }
+ if (std::holds_alternative<TernaryOpFunc>(funcptr)) {
+ return 3;
+ }
+
+ BLI_assert_msg(0, "unexpected function pointer");
+ return -1;
+ }
+};
+
+#ifdef _MSC_VER
+/* Prevent MSVC from inlining calls to ceil/floor so the table below can get a function pointer to
+ * them. */
+# pragma function(ceil)
+# pragma function(floor)
+#endif
+
+static BuiltinOpDef builtin_ops[] = {
+ {"radians", UnaryOpFunc(op_radians)},
+ {"degrees", UnaryOpFunc(op_degrees)},
+ {"abs", UnaryOpFunc(fabs)},
+ {"fabs", UnaryOpFunc(fabs)},
+ {"floor", UnaryOpFunc(floor)},
+ {"ceil", UnaryOpFunc(ceil)},
+ {"trunc", UnaryOpFunc(trunc)},
+ {"round", UnaryOpFunc(round)},
+ {"int", UnaryOpFunc(trunc)},
+ {"sin", UnaryOpFunc(sin)},
+ {"cos", UnaryOpFunc(cos)},
+ {"tan", UnaryOpFunc(tan)},
+ {"asin", UnaryOpFunc(asin)},
+ {"acos", UnaryOpFunc(acos)},
+ {"atan", UnaryOpFunc(atan)},
+ {"atan2", BinaryOpFunc(atan2)},
+ {"exp", UnaryOpFunc(exp)},
+ {"log", UnaryOpFunc(log)},
+ {"log", BinaryOpFunc(op_log2)},
+ {"sqrt", UnaryOpFunc(sqrt)},
+ {"pow", BinaryOpFunc(pow)},
+ {"fmod", BinaryOpFunc(fmod)},
+ {"lerp", TernaryOpFunc(op_lerp)},
+ {"clamp", UnaryOpFunc(op_clamp)},
+ {"clamp", TernaryOpFunc(op_clamp3)},
+ {"smoothstep", TernaryOpFunc(op_smoothstep)},
+ {nullptr},
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Expression Parser State
+ * \{ */
+
+#define MAKE_CHAR2(a, b) (((a) << 8) | (b))
+
+#define CHECK_ERROR(condition) \
+ if (!(condition)) { \
+ return false; \
+ } \
+ ((void)0)
+
+/* For simplicity simple token types are represented by their own character;
+ * these are special identifiers for multi-character tokens. */
+#define TOKEN_ID MAKE_CHAR2('I', 'D')
+#define TOKEN_NUMBER MAKE_CHAR2('0', '0')
+#define TOKEN_GE MAKE_CHAR2('>', '=')
+#define TOKEN_LE MAKE_CHAR2('<', '=')
+#define TOKEN_NE MAKE_CHAR2('!', '=')
+#define TOKEN_EQ MAKE_CHAR2('=', '=')
+#define TOKEN_AND MAKE_CHAR2('A', 'N')
+#define TOKEN_OR MAKE_CHAR2('O', 'R')
+#define TOKEN_NOT MAKE_CHAR2('N', 'O')
+#define TOKEN_IF MAKE_CHAR2('I', 'F')
+#define TOKEN_ELSE MAKE_CHAR2('E', 'L')
+/* BUI: `**` and `//`. */
+#define TOKEN_POW MAKE_CHAR2('*', '*')
+#define TOKEN_FLOORDIV MAKE_CHAR2('/', '/')
+
+static const char *token_eq_characters = "!=><";
+static const char *token_characters = "~`!@#$%^&*+-=/\\?:;<>(){}[]|.,\"'";
+
+struct KeywordTokenDef {
+ const char *name;
+ short token;
+};
+
+static KeywordTokenDef keyword_list[] = {
+ {"and", TOKEN_AND},
+ {"or", TOKEN_OR},
+ {"not", TOKEN_NOT},
+ {"if", TOKEN_IF},
+ {"else", TOKEN_ELSE},
+ {nullptr, TOKEN_ID},
+};
+
+struct ExprParseState {
+ int param_names_len = 0;
+ const char **param_names = nullptr;
+
+ /* Original expression */
+ const char *expr = nullptr;
+ const char *cur = nullptr;
+
+ /* Current token */
+ short token = 0;
+ Vector<char> tokenbuf;
+ double tokenval = 0.0;
+
+ /* Opcode buffer */
+ int last_jmp = 0;
+ Vector<ExprOp> ops;
+
+ /* Stack space requirement tracking */
+ int stack_ptr = 0;
+ int max_stack = 0;
+};
+
+/* Add one operation and track stack usage. */
+static ExprOp *parse_add_op(ExprParseState *state, eOpCode code, int stack_delta)
+{
+ /* track evaluation stack depth */
+ state->stack_ptr += stack_delta;
+ CLAMP_MIN(state->stack_ptr, 0);
+ CLAMP_MIN(state->max_stack, state->stack_ptr);
+
+ /* allocate the new instruction */
+ ExprOp op{code};
+ state->ops.append(op);
+ return &state->ops.last();
+}
+
+/* Add one jump operation and return an index for parse_set_jump. */
+static int parse_add_jump(ExprParseState *state, eOpCode code)
+{
+ parse_add_op(state, code, -1);
+ return state->last_jmp = state->ops.size();
+}
+
+/* Set the jump offset in a previously added jump operation. */
+static void parse_set_jump(ExprParseState *state, int jump)
+{
+ state->last_jmp = state->ops.size();
+ state->ops[jump - 1].jmp_offset = state->ops.size() - jump;
+}
+
+/* Add a function call operation, applying constant folding when possible. */
+static bool parse_add_func(ExprParseState *state,
+ std::variant<UnaryOpFunc, BinaryOpFunc, TernaryOpFunc> funcptr)
+{
+ ExprOp *prev_ops = state->ops.end();
+ int jmp_gap = state->ops.size() - state->last_jmp;
+
+ feclearexcept(FE_ALL_EXCEPT);
+
+ if (std::holds_alternative<UnaryOpFunc>(funcptr)) {
+ UnaryOpFunc func = std::get<UnaryOpFunc>(funcptr);
+
+ if (jmp_gap >= 1 && prev_ops[-1].opcode == OPCODE_CONST) {
+ /* volatile because some compilers overly aggressive optimize this call out.
+ * see D6012 for details. */
+ volatile double result = func(prev_ops[-1].arg.dval);
+
+ if (fetestexcept(FE_DIVBYZERO | FE_INVALID) == 0) {
+ prev_ops[-1].arg.dval = result;
+ return true;
+ }
+ }
+
+ parse_add_op(state, OPCODE_FUNC1, 0)->arg.func1 = func;
+ }
+ else if (std::holds_alternative<BinaryOpFunc>(funcptr)) {
+ BinaryOpFunc func = std::get<BinaryOpFunc>(funcptr);
+
+ if (jmp_gap >= 2 && prev_ops[-2].opcode == OPCODE_CONST && prev_ops[-1].opcode == OPCODE_CONST)
+ {
+ /* volatile because some compilers overly aggressive optimize this call out.
+ * see D6012 for details. */
+ volatile double result = func(prev_ops[-2].arg.dval, prev_ops[-1].arg.dval);
+
+ if (fetestexcept(FE_DIVBYZERO | FE_INVALID) == 0) {
+ prev_ops[-2].arg.dval = result;
+ state->ops.resize(state->ops.size() - 1);
+ state->stack_ptr--;
+ return true;
+ }
+ }
+
+ parse_add_op(state, OPCODE_FUNC2, -1)->arg.func2 = func;
+ }
+ else if (std::holds_alternative<TernaryOpFunc>(funcptr)) {
+ TernaryOpFunc func = std::get<TernaryOpFunc>(funcptr);
+
+ if (jmp_gap >= 3 && prev_ops[-3].opcode == OPCODE_CONST &&
+ prev_ops[-2].opcode == OPCODE_CONST && prev_ops[-1].opcode == OPCODE_CONST)
+ {
+ /* volatile because some compilers overly aggressive optimize this call out.
+ * see D6012 for details. */
+ volatile double result = func(
+ prev_ops[-3].arg.dval, prev_ops[-2].arg.dval, prev_ops[-1].arg.dval);
+
+ if (fetestexcept(FE_DIVBYZERO | FE_INVALID) == 0) {
+ prev_ops[-3].arg.dval = result;
+ state->ops.resize(state->ops.size() - 2);
+ state->stack_ptr -= 2;
+ return true;
+ }
+ }
+
+ parse_add_op(state, OPCODE_FUNC3, -2)->arg.func3 = func;
+ }
+ else {
+ BLI_assert(false);
+ return false;
+ }
+
+ return true;
+}
+
+/* Extract the next token from raw characters. */
+static bool parse_next_token(ExprParseState *state)
+{
+ /* Skip white-space. */
+ while (isspace(*state->cur)) {
+ state->cur++;
+ }
+
+ /* End of string. */
+ if (*state->cur == 0) {
+ state->token = 0;
+ return true;
+ }
+
+ /* Floating point numbers. */
+ if (isdigit(*state->cur) || (state->cur[0] == '.' && isdigit(state->cur[1]))) {
+ char *end, *out = state->tokenbuf.data();
+ bool is_float = false;
+
+ while (isdigit(*state->cur)) {
+ *out++ = *state->cur++;
+ }
+
+ if (*state->cur == '.') {
+ is_float = true;
+ *out++ = *state->cur++;
+
+ while (isdigit(*state->cur)) {
+ *out++ = *state->cur++;
+ }
+ }
+
+ if (ELEM(*state->cur, 'e', 'E')) {
+ is_float = true;
+ *out++ = *state->cur++;
+
+ if (ELEM(*state->cur, '+', '-')) {
+ *out++ = *state->cur++;
+ }
+
+ CHECK_ERROR(isdigit(*state->cur));
+
+ while (isdigit(*state->cur)) {
+ *out++ = *state->cur++;
+ }
+ }
+
+ *out = 0;
+
+ /* BUI: leading zeros are allowed ("05" is 5, as typed into number fields);
+ * Blender forbids C-style octal constants here. */
+ (void)is_float;
+
+ state->token = TOKEN_NUMBER;
+ state->tokenval = strtod(state->tokenbuf.data(), &end);
+ return (end == out);
+ }
+
+ /* BUI: `**` and `//`. */
+ if ((state->cur[0] == '*' && state->cur[1] == '*') ||
+ (state->cur[0] == '/' && state->cur[1] == '/'))
+ {
+ state->token = MAKE_CHAR2(state->cur[0], state->cur[1]);
+ state->cur += 2;
+ return true;
+ }
+
+ /* ?= tokens */
+ if (state->cur[1] == '=' && strchr(token_eq_characters, state->cur[0])) {
+ state->token = MAKE_CHAR2(state->cur[0], state->cur[1]);
+ state->cur += 2;
+ return true;
+ }
+
+ /* Special characters (single character tokens) */
+ if (strchr(token_characters, *state->cur)) {
+ state->token = *state->cur++;
+ return true;
+ }
+
+ /* Identifiers */
+ if (isalpha(*state->cur) || ELEM(*state->cur, '_')) {
+ char *out = state->tokenbuf.data();
+
+ while (isalnum(*state->cur) || ELEM(*state->cur, '_')) {
+ *out++ = *state->cur++;
+ }
+
+ *out = 0;
+
+ for (int i = 0; keyword_list[i].name; i++) {
+ if (STREQ(state->tokenbuf.data(), keyword_list[i].name)) {
+ state->token = keyword_list[i].token;
+ return true;
+ }
+ }
+
+ state->token = TOKEN_ID;
+ return true;
+ }
+
+ return false;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Recursive Descent Parser
+ * \{ */
+
+static bool parse_expr(ExprParseState *state);
+
+static int parse_function_args(ExprParseState *state)
+{
+ if (!parse_next_token(state) || state->token != '(' || !parse_next_token(state)) {
+ return -1;
+ }
+
+ int arg_count = 0;
+
+ for (;;) {
+ if (!parse_expr(state)) {
+ return -1;
+ }
+
+ arg_count++;
+
+ switch (state->token) {
+ case ',':
+ if (!parse_next_token(state)) {
+ return -1;
+ }
+ break;
+
+ case ')':
+ if (!parse_next_token(state)) {
+ return -1;
+ }
+ return arg_count;
+
+ default:
+ return -1;
+ }
+ }
+}
+
+static bool parse_unary(ExprParseState *state);
+
+/* BUI: Blender's parse_unary renamed; parse_unary below adds the power operator
+ * (binds tighter than a unary minus on its left: -2**2 = -4, right associative). */
+static bool parse_atom(ExprParseState *state)
+{
+ int i;
+
+ switch (state->token) {
+ case '+':
+ return parse_next_token(state) && parse_unary(state);
+
+ case '-':
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_negate);
+ return true;
+
+ case '(':
+ return parse_next_token(state) && parse_expr(state) && state->token == ')' &&
+ parse_next_token(state);
+
+ case TOKEN_NUMBER:
+ parse_add_op(state, OPCODE_CONST, 1)->arg.dval = state->tokenval;
+ return parse_next_token(state);
+
+ case TOKEN_ID:
+ /* Parameters: search in reverse order in case of duplicate names -
+ * the last one should win. */
+ for (i = state->param_names_len - 1; i >= 0; i--) {
+ if (STREQ(state->tokenbuf.data(), state->param_names[i])) {
+ parse_add_op(state, OPCODE_PARAMETER, 1)->arg.ival = i;
+ return parse_next_token(state);
+ }
+ }
+
+ /* Ordinary builtin constants. */
+ for (i = 0; builtin_consts[i].name; i++) {
+ if (STREQ(state->tokenbuf.data(), builtin_consts[i].name)) {
+ parse_add_op(state, OPCODE_CONST, 1)->arg.dval = builtin_consts[i].value;
+ return parse_next_token(state);
+ }
+ }
+
+ /* Ordinary builtin functions. */
+ for (i = 0; builtin_ops[i].name; i++) {
+ if (STREQ(state->tokenbuf.data(), builtin_ops[i].name)) {
+ int args = parse_function_args(state);
+
+ /* Search for other arg count versions if necessary. */
+ if (args != builtin_ops[i].arg_count()) {
+ for (int j = i + 1; builtin_ops[j].name; j++) {
+ if (builtin_ops[j].arg_count() == args &&
+ STREQ(builtin_ops[j].name, builtin_ops[i].name))
+ {
+ i = j;
+ break;
+ }
+ }
+ }
+
+ CHECK_ERROR(builtin_ops[i].name && builtin_ops[i].arg_count() == args);
+
+ return parse_add_func(state, builtin_ops[i].funcptr);
+ }
+ }
+
+ /* Specially supported functions. */
+ if (STREQ(state->tokenbuf.data(), "min")) {
+ int count = parse_function_args(state);
+ CHECK_ERROR(count > 0);
+
+ parse_add_op(state, OPCODE_MIN, 1 - count)->arg.ival = count;
+ return true;
+ }
+
+ if (STREQ(state->tokenbuf.data(), "max")) {
+ int count = parse_function_args(state);
+ CHECK_ERROR(count > 0);
+
+ parse_add_op(state, OPCODE_MAX, 1 - count)->arg.ival = count;
+ return true;
+ }
+
+ return false;
+
+ default:
+ return false;
+ }
+}
+
+/* BUI: power (`**`, `^`) over parse_atom. */
+static bool parse_unary(ExprParseState *state)
+{
+ if (ELEM(state->token, '+', '-')) {
+ return parse_atom(state);
+ }
+ CHECK_ERROR(parse_atom(state));
+ if (ELEM(state->token, TOKEN_POW, '^')) {
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_pow);
+ }
+ return true;
+}
+
+static bool parse_mul(ExprParseState *state)
+{
+ CHECK_ERROR(parse_unary(state));
+
+ for (;;) {
+ switch (state->token) {
+ case '*':
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_mul);
+ break;
+
+ case '/':
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_div);
+ break;
+
+ /* BUI: `//` and `%`. */
+ case TOKEN_FLOORDIV:
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_floordiv);
+ break;
+
+ case '%':
+ CHECK_ERROR(parse_next_token(state) && parse_unary(state));
+ parse_add_func(state, op_mod);
+ break;
+
+ default:
+ return true;
+ }
+ }
+}
+
+static bool parse_add(ExprParseState *state)
+{
+ CHECK_ERROR(parse_mul(state));
+
+ for (;;) {
+ switch (state->token) {
+ case '+':
+ CHECK_ERROR(parse_next_token(state) && parse_mul(state));
+ parse_add_func(state, op_add);
+ break;
+
+ case '-':
+ CHECK_ERROR(parse_next_token(state) && parse_mul(state));
+ parse_add_func(state, op_sub);
+ break;
+
+ default:
+ return true;
+ }
+ }
+}
+
+static BinaryOpFunc parse_get_cmp_func(short token)
+{
+ switch (token) {
+ case TOKEN_EQ:
+ return op_eq;
+ case TOKEN_NE:
+ return op_ne;
+ case '>':
+ return op_gt;
+ case TOKEN_GE:
+ return op_ge;
+ case '<':
+ return op_lt;
+ case TOKEN_LE:
+ return op_le;
+ default:
+ return nullptr;
+ }
+}
+
+static bool parse_cmp_chain(ExprParseState *state, BinaryOpFunc cur_func)
+{
+ BinaryOpFunc next_func = parse_get_cmp_func(state->token);
+
+ if (next_func) {
+ parse_add_op(state, OPCODE_CMP_CHAIN, -1)->arg.func2 = cur_func;
+ int jump = state->last_jmp = state->ops.size();
+
+ CHECK_ERROR(parse_next_token(state) && parse_add(state));
+ CHECK_ERROR(parse_cmp_chain(state, next_func));
+
+ parse_set_jump(state, jump);
+ }
+ else {
+ parse_add_func(state, cur_func);
+ }
+
+ return true;
+}
+
+static bool parse_cmp(ExprParseState *state)
+{
+ CHECK_ERROR(parse_add(state));
+
+ BinaryOpFunc func = parse_get_cmp_func(state->token);
+
+ if (func) {
+ CHECK_ERROR(parse_next_token(state) && parse_add(state));
+
+ return parse_cmp_chain(state, func);
+ }
+
+ return true;
+}
+
+static bool parse_not(ExprParseState *state)
+{
+ if (state->token == TOKEN_NOT) {
+ CHECK_ERROR(parse_next_token(state) && parse_not(state));
+ parse_add_func(state, op_not);
+ return true;
+ }
+
+ return parse_cmp(state);
+}
+
+static bool parse_and(ExprParseState *state)
+{
+ CHECK_ERROR(parse_not(state));
+
+ if (state->token == TOKEN_AND) {
+ int jump = parse_add_jump(state, OPCODE_JMP_AND);
+
+ CHECK_ERROR(parse_next_token(state) && parse_and(state));
+
+ parse_set_jump(state, jump);
+ }
+
+ return true;
+}
+
+static bool parse_or(ExprParseState *state)
+{
+ CHECK_ERROR(parse_and(state));
+
+ if (state->token == TOKEN_OR) {
+ int jump = parse_add_jump(state, OPCODE_JMP_OR);
+
+ CHECK_ERROR(parse_next_token(state) && parse_or(state));
+
+ parse_set_jump(state, jump);
+ }
+
+ return true;
+}
+
+static bool parse_expr(ExprParseState *state)
+{
+ /* Temporarily set the constant expression evaluation barrier */
+ int prev_last_jmp = state->last_jmp;
+ int start = state->last_jmp = state->ops.size();
+
+ CHECK_ERROR(parse_or(state));
+
+ if (state->token == TOKEN_IF) {
+ /* Ternary IF expression in python requires swapping the
+ * main body with condition, so stash the body opcodes. */
+ const int size = state->ops.size() - start;
+
+ Vector<ExprOp> body(size);
+ std::copy_n(state->ops.data() + start, size, body.data());
+
+ state->ops.resize(start);
+ state->last_jmp = start;
+ state->stack_ptr--;
+
+ /* Parse condition. */
+ if (!parse_next_token(state) || !parse_or(state) || state->token != TOKEN_ELSE ||
+ !parse_next_token(state))
+ {
+ return false;
+ }
+
+ int jmp_else = parse_add_jump(state, OPCODE_JMP_ELSE);
+
+ /* Add body back. */
+ const size_t body_offset = state->ops.size();
+ state->ops.resize(body_offset + size);
+ std::copy_n(body.data(), size, state->ops.data() + body_offset);
+ body.clear_and_shrink();
+
+ state->stack_ptr++;
+
+ int jmp_end = parse_add_jump(state, OPCODE_JMP);
+
+ /* Parse the `else` block. */
+ parse_set_jump(state, jmp_else);
+
+ CHECK_ERROR(parse_expr(state));
+
+ parse_set_jump(state, jmp_end);
+ }
+ /* If no actual jumps happened, restore previous barrier */
+ else if (state->last_jmp == start) {
+ state->last_jmp = prev_last_jmp;
+ }
+
+ return true;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Main Parsing Function
+ * \{ */
+
+ExprPyLike_Parsed *BLI_expr_pylike_parse(const char *expression,
+ const char **param_names,
+ int param_names_len)
+{
+ /* Prepare the parser state. */
+ ExprParseState state;
+
+ state.cur = state.expr = expression;
+
+ state.param_names_len = param_names_len;
+ state.param_names = param_names;
+
+ state.tokenbuf.resize(strlen(expression) + 1);
+
+ /* Parse the expression. */
+ ExprPyLike_Parsed *expr = MEM_new<ExprPyLike_Parsed>("ExprPyLike_Parsed(empty)");
+
+ if (parse_next_token(&state) && parse_expr(&state) && state.token == 0) {
+ BLI_assert(state.stack_ptr == 1);
+
+ expr->max_stack = state.max_stack;
+ expr->ops = std::move(state.ops);
+ }
+ else {
+ /* Always return a non-nullptr object so that parse failure can be cached. */
+ }
+
+ return expr;
+}
+
+/** \} */
+
+} // namespace blender
diff --git a/core/intern/guardedalloc.c b/core/intern/guardedalloc.c
index fdfce74..0cc3fda 100644
--- a/core/intern/guardedalloc.c
+++ b/core/intern/guardedalloc.c
@@ -121,6 +121,11 @@ void *MEM_new_zeroed(size_t size, const char *str)
void *MEM_new_uninitialized_aligned(size_t size, size_t alignment, const char *str)
{
+ /* malloc already aligns to 16 bytes; blocks from here are released with
+ * MEM_delete_void -> free(), which must not get a Windows _aligned_malloc block. */
+ if (alignment <= MEM_MIN_CPP_ALIGNMENT) {
+ return MEM_mallocN(size ? size : 1, str);
+ }
return MEM_mallocN_aligned(size, alignment, str);
}
diff --git a/core/intern/string_search.cc b/core/intern/string_search.cc
new file mode 100644
index 0000000..2b68ddf
--- /dev/null
+++ b/core/intern/string_search.cc
@@ -0,0 +1,618 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ */
+
+/* BUI: copied from blenlib/intern/string_search.cc for the kit's menu search
+ * and search fields (C API: BUI_string_search_* in kit/intern/blender/).
+ * BUI edits, marked "BUI:": scoring runs serially (no TBB). The vendored
+ * BLI_string.h / BLI_string_utf8.h declare C linkage for C++ callers. */
+#include "BLI_string.h"
+#include "BLI_string_utf8.h"
+
+#include "BLI_array.hh"
+#include "BLI_linear_allocator.hh"
+#include "BLI_multi_value_map.hh"
+#include "BLI_span.hh"
+#include "BLI_string.h"
+#include "BLI_string_ref.hh"
+#include "BLI_string_search.hh"
+#include "BLI_string_utf8.h"
+#include "BLI_string_utf8_symbols.h"
+/* BUI: no BLI_task.hh (TBB); see query_impl. */
+
+/* Right arrow, keep in sync with #UI_MENU_ARROW_SEP in `UI_interface_c.hh`. */
+#define UI_MENU_ARROW_SEP BLI_STR_UTF8_BLACK_RIGHT_POINTING_SMALL_TRIANGLE
+#define UI_MENU_ARROW_SEP_UNICODE 0x25b8
+
+namespace blender::string_search {
+
+static int64_t count_utf8_code_points(StringRef str)
+{
+ return int64_t(BLI_strnlen_utf8(str.data(), size_t(str.size())));
+}
+
+int damerau_levenshtein_distance(StringRef a, StringRef b)
+{
+ constexpr int deletion_cost = 1;
+ constexpr int insertion_cost = 1;
+ constexpr int substitution_cost = 1;
+ constexpr int transposition_cost = 1;
+
+ const int size_a = count_utf8_code_points(a);
+ const int size_b = count_utf8_code_points(b);
+
+ /* Instead of keeping the entire table in memory, only keep three rows. The algorithm only
+ * accesses these rows and nothing older.
+ * All three rows are usually allocated on the stack. At most a single heap allocation is done,
+ * if the reserved stack space is too small. */
+ const int row_length = size_b + 1;
+ Array<int, 64> rows(row_length * 3);
+
+ /* Store rows as spans so that it is cheap to swap them. */
+ MutableSpan v0{rows.data() + row_length * 0, row_length};
+ MutableSpan v1{rows.data() + row_length * 1, row_length};
+ MutableSpan v2{rows.data() + row_length * 2, row_length};
+
+ /* Only v1 needs to be initialized. */
+ for (const int i : IndexRange(row_length)) {
+ v1[i] = i * insertion_cost;
+ }
+
+ uint32_t prev_unicode_a;
+ size_t offset_a = 0;
+ for (const int i : IndexRange(size_a)) {
+ v2[0] = (i + 1) * deletion_cost;
+
+ const uint32_t unicode_a = BLI_str_utf8_as_unicode_step_safe(a.data(), a.size(), &offset_a);
+
+ uint32_t prev_unicode_b;
+ size_t offset_b = 0;
+ for (const int j : IndexRange(size_b)) {
+ const uint32_t unicode_b = BLI_str_utf8_as_unicode_step_safe(b.data(), b.size(), &offset_b);
+
+ /* Check how costly the different operations would be and pick the cheapest - the one with
+ * minimal cost. */
+ int new_cost = std::min({v1[j + 1] + deletion_cost,
+ v2[j] + insertion_cost,
+ v1[j] + (unicode_a != unicode_b) * substitution_cost});
+ if (i > 0 && j > 0) {
+ if (unicode_a == prev_unicode_b && prev_unicode_a == unicode_b) {
+ new_cost = std::min(new_cost, v0[j - 1] + transposition_cost);
+ }
+ }
+
+ v2[j + 1] = new_cost;
+ prev_unicode_b = unicode_b;
+ }
+
+ /* Swap the three rows, so that the next row can be computed. */
+ std::tie(v0, v1, v2) = std::tuple<MutableSpan<int>, MutableSpan<int>, MutableSpan<int>>(
+ v1, v2, v0);
+ prev_unicode_a = unicode_a;
+ }
+
+ return v1.last();
+}
+
+int get_fuzzy_match_errors(StringRef query, StringRef full)
+{
+ /* If it is a perfect partial match, return immediately. */
+ if (full.find(query) != StringRef::not_found) {
+ return 0;
+ }
+
+ const int query_size = count_utf8_code_points(query);
+ const int full_size = count_utf8_code_points(full);
+
+ /* If there is only a single character which is not in the full string, this is not a match. */
+ if (query_size == 1) {
+ return -1;
+ }
+ BLI_assert(query.size() >= 2);
+
+ /* Allow more errors when the size grows larger. */
+ const int max_errors = query_size <= 1 ? 0 : query_size / 8 + 1;
+
+ /* If the query is too large, this cannot be a match. */
+ if (query_size - full_size > max_errors) {
+ return -1;
+ }
+
+ const uint32_t query_first_unicode = BLI_str_utf8_as_unicode_safe(query.data());
+ const uint32_t query_second_unicode = BLI_str_utf8_as_unicode_safe(
+ query.data() + BLI_str_utf8_size_safe(query.data()));
+
+ const char *full_begin = full.begin();
+ const char *full_end = full.end();
+
+ const char *window_begin = full_begin;
+ const char *window_end = window_begin;
+ const int window_size = std::min(query_size + max_errors, full_size);
+ const int extra_chars = std::max(window_size - query_size, 0);
+ const int max_acceptable_distance = max_errors + extra_chars;
+
+ for (int i = 0; i < window_size; i++) {
+ window_end += BLI_str_utf8_size_safe(window_end);
+ }
+
+ while (true) {
+ StringRef window{window_begin, window_end};
+ const uint32_t window_begin_unicode = BLI_str_utf8_as_unicode_safe(window_begin);
+ int distance = 0;
+ /* Expect that the first or second character of the query is correct. This helps to avoid
+ * computing the more expensive distance function. */
+ if (ELEM(window_begin_unicode, query_first_unicode, query_second_unicode)) {
+ distance = damerau_levenshtein_distance(query, window);
+ if (distance <= max_acceptable_distance) {
+ return distance;
+ }
+ }
+ if (window_end == full_end) {
+ return -1;
+ }
+
+ /* When the distance is way too large, we can skip a couple of code points, because the
+ * distance can't possibly become as short as required. */
+ const int window_offset = std::max(1, distance / 2);
+ for (int i = 0; i < window_offset && window_end < full_end; i++) {
+ window_begin += BLI_str_utf8_size_safe(window_begin);
+ window_end += BLI_str_utf8_size_safe(window_end);
+ }
+ }
+}
+
+static constexpr int unused_word = -1;
+
+struct InitialsMatch {
+ Vector<int> matched_word_indices;
+
+ int count_main_group_matches(const SearchItem &item) const
+ {
+ int count = 0;
+ for (const int i : this->matched_word_indices) {
+ if (item.word_group_ids[i] == item.main_group_id) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ bool better_than(const InitialsMatch &other, const SearchItem &item) const
+ {
+ return this->count_main_group_matches(item) > other.count_main_group_matches(item);
+ }
+};
+
+/**
+ * Takes a query and tries to match it with the first characters of some words. For example, "msfv"
+ * matches "Mark Sharp from Vertices". Multiple letters of the beginning of a word can be matched
+ * as well. For example, "seboulo" matches "select boundary loop". The order of words is important.
+ * So "bose" does not match "select boundary". However, individual words can be skipped. For
+ * example, "rocc" matches "rotate edge ccw".
+ */
+static std::optional<InitialsMatch> match_word_initials(StringRef query,
+ const SearchItem &item,
+ const Span<int> word_match_map,
+ int start = 0)
+{
+ const Span<StringRef> words = item.normalized_words;
+ if (start >= words.size()) {
+ return std::nullopt;
+ }
+
+ InitialsMatch match;
+
+ size_t query_index = 0;
+ int word_index = start;
+ size_t char_index = 0;
+
+ int first_found_word_index = -1;
+
+ while (query_index < query.size()) {
+ const uint query_unicode = BLI_str_utf8_as_unicode_step_safe(
+ query.data(), query.size(), &query_index);
+ while (true) {
+ /* We are at the end of words, no complete match has been found yet. */
+ if (word_index >= words.size()) {
+ if (first_found_word_index >= 0) {
+ /* Try starting to match at another word. In some cases one can still find matches this
+ * way. */
+ return match_word_initials(query, item, word_match_map, first_found_word_index + 1);
+ }
+ return std::nullopt;
+ }
+
+ /* Skip words that the caller does not want us to use. */
+ if (word_match_map[word_index] != unused_word) {
+ word_index++;
+ BLI_assert(char_index == 0);
+ continue;
+ }
+
+ StringRef word = words[word_index];
+ /* Try to match the current character with the current word. */
+ if (int(char_index) < word.size()) {
+ const uint32_t char_unicode = BLI_str_utf8_as_unicode_step_safe(
+ word.data(), word.size(), &char_index);
+ if (query_unicode == char_unicode) {
+ match.matched_word_indices.append(word_index);
+ if (first_found_word_index == -1) {
+ first_found_word_index = word_index;
+ }
+ break;
+ }
+ }
+
+ /* Could not find a match in the current word, go to the beginning of the next word. */
+ word_index += 1;
+ char_index = 0;
+ }
+ }
+ /* Check if we can find a better match that starts at a later word. */
+ if (std::optional<InitialsMatch> sub_match = match_word_initials(
+ query, item, word_match_map, first_found_word_index + 1))
+ {
+ if (sub_match->better_than(match, item)) {
+ return sub_match;
+ }
+ }
+ return match;
+}
+
+/**
+ * The "best" is chosen with combination of word weights and word length.
+ */
+static int get_best_word_index_that_startswith(StringRef query,
+ const SearchItem &item,
+ Span<int> word_match_map,
+ Span<StringRef> remaining_query_words)
+{
+ /* If there is another word in the remaining full query that contains the current word, we have
+ * to pick the shortest word. If we pick a longer one, it can happen that the other query word
+ * does not have a match anymore. This can lead to a situation where a query does not match
+ * itself anymore.
+ *
+ * E.g. the full query `T > Test` wouldn't match itself anymore if `Test` has a higher weight.
+ * That's because the `T` would be matched with the `Test`, but then `Test` can't match `Test
+ * anymore because that's taken up already.
+ *
+ * If we don't have to pick the shortest match for correctness, pick the one with the largest
+ * weight instead.
+ */
+ bool use_shortest_match = false;
+ for (const StringRef other_word : remaining_query_words) {
+ if (other_word.startswith(query)) {
+ use_shortest_match = true;
+ break;
+ }
+ }
+
+ int best_word_size = INT32_MAX;
+ int best_word_index = -1;
+ bool best_word_in_main_group = false;
+ for (const int i : item.normalized_words.index_range()) {
+ if (word_match_map[i] != unused_word) {
+ continue;
+ }
+ StringRef word = item.normalized_words[i];
+ const bool word_in_main_group = item.word_group_ids[i] == item.main_group_id;
+ if (word.startswith(query)) {
+ bool found_new_best = false;
+ if (use_shortest_match) {
+ if (word.size() < best_word_size) {
+ found_new_best = true;
+ }
+ }
+ else {
+ if (!best_word_in_main_group) {
+ found_new_best = true;
+ }
+ }
+ if (found_new_best) {
+ best_word_index = i;
+ best_word_size = word.size();
+ best_word_in_main_group = word_in_main_group;
+ }
+ }
+ }
+ return best_word_index;
+}
+
+static int get_word_index_that_fuzzy_matches(StringRef query,
+ Span<StringRef> words,
+ Span<int> word_match_map,
+ int *r_error_count)
+{
+ for (const int i : words.index_range()) {
+ if (word_match_map[i] != unused_word) {
+ continue;
+ }
+ StringRef word = words[i];
+ const int error_count = get_fuzzy_match_errors(query, word);
+ if (error_count >= 0) {
+ *r_error_count = error_count;
+ return i;
+ }
+ }
+ return -1;
+}
+
+/**
+ * Checks how well the query matches a result. If it does not match, -1 is returned. A positive
+ * return value indicates how good the match is. The higher the value, the better the match.
+ */
+static std::optional<float> score_query_against_words(Span<StringRef> query_words,
+ const SearchItem &item)
+{
+ /* A mapping from #result_words to #query_words. It's mainly used to determine if a word has been
+ * matched already to avoid matching it again. */
+ Array<int, 64> word_match_map(item.normalized_words.size(), unused_word);
+
+ /* Start with some high score, because otherwise the final score might become negative. */
+ float total_match_score = item.is_deprecated ? 500 : 1000;
+
+ for (const int query_word_index : query_words.index_range()) {
+ const StringRef query_word = query_words[query_word_index];
+ {
+ /* Check if any result word begins with the query word. */
+ const int word_index = get_best_word_index_that_startswith(
+ query_word, item, word_match_map, query_words.drop_front(query_word_index + 1));
+ if (word_index >= 0) {
+ /* Give a match in a main group higher priority. */
+ const bool is_main_group = item.word_group_ids[word_index] == item.main_group_id;
+ total_match_score += is_main_group ? 10 : 9;
+ word_match_map[word_index] = query_word_index;
+ continue;
+ }
+ }
+ {
+ /* Try to match against word initials. */
+ if (std::optional<InitialsMatch> match = match_word_initials(
+ query_word, item, word_match_map))
+ {
+ /* If the all matched words are in the main group, give the match a higher priority. */
+ bool all_main_group_matches = match->count_main_group_matches(item) ==
+ match->matched_word_indices.size();
+ total_match_score += all_main_group_matches ? 4 : 3;
+ for (const int i : match->matched_word_indices) {
+ word_match_map[i] = query_word_index;
+ }
+ continue;
+ }
+ }
+ {
+ /* Fuzzy match against words. */
+ int error_count = 0;
+ const int word_index = get_word_index_that_fuzzy_matches(
+ query_word, item.normalized_words, word_match_map, &error_count);
+ if (word_index >= 0) {
+ total_match_score += 3 - error_count;
+ word_match_map[word_index] = query_word_index;
+ continue;
+ }
+ }
+
+ /* Couldn't match query word with anything. */
+ return std::nullopt;
+ }
+
+ {
+ /* Add penalty when query words are not in the correct order. */
+ Vector<int> match_indices;
+ for (const int index : word_match_map) {
+ if (index != unused_word) {
+ match_indices.append(index);
+ }
+ }
+ if (!match_indices.is_empty()) {
+ for (const int i : IndexRange(match_indices.size() - 1)) {
+ if (match_indices[i] > match_indices[i + 1]) {
+ total_match_score -= 1;
+ }
+ }
+ }
+ }
+
+ return total_match_score;
+}
+
+void extract_normalized_words(StringRef str,
+ LinearAllocator<> &allocator,
+ Vector<StringRef, 64> &r_words,
+ Vector<int, 64> &r_word_group_ids)
+{
+ const uint32_t unicode_space = uint32_t(' ');
+ const uint32_t unicode_dash = uint32_t('-');
+ const uint32_t unicode_underscore = uint32_t('_');
+ const uint32_t unicode_slash = uint32_t('/');
+ const uint32_t unicode_right_triangle = UI_MENU_ARROW_SEP_UNICODE;
+
+ BLI_assert(unicode_space == BLI_str_utf8_as_unicode_safe(" "));
+ BLI_assert(unicode_dash == BLI_str_utf8_as_unicode_safe("-"));
+ BLI_assert(unicode_underscore == BLI_str_utf8_as_unicode_safe("_"));
+ BLI_assert(unicode_slash == BLI_str_utf8_as_unicode_safe("/"));
+ BLI_assert(unicode_right_triangle == BLI_str_utf8_as_unicode_safe(UI_MENU_ARROW_SEP));
+
+ auto is_separator = [&](uint32_t unicode) {
+ return ELEM(unicode,
+ unicode_space,
+ unicode_dash,
+ unicode_underscore,
+ unicode_slash,
+ unicode_right_triangle);
+ };
+
+ Vector<int, 64> section_indices;
+
+ /* Make a copy of the string so that we can edit it. */
+ StringRef str_copy = allocator.copy_string(str);
+ char *mutable_copy = const_cast<char *>(str_copy.data());
+ const size_t str_size_in_bytes = size_t(str.size());
+ BLI_str_tolower_ascii(mutable_copy, str_size_in_bytes);
+
+ /* Iterate over all unicode code points to split individual words. */
+ int group_id = 0;
+ bool is_in_word = false;
+ size_t word_start = 0;
+ size_t offset = 0;
+ while (offset < str_size_in_bytes) {
+ size_t size = offset;
+ uint32_t unicode = BLI_str_utf8_as_unicode_step_safe(str.data(), str.size(), &size);
+ size -= offset;
+ if (is_separator(unicode)) {
+ if (is_in_word) {
+ const StringRef word = str_copy.substr(int(word_start), int(offset - word_start));
+ r_words.append(word);
+ r_word_group_ids.append(group_id);
+ is_in_word = false;
+ }
+ }
+ else {
+ if (!is_in_word) {
+ word_start = offset;
+ is_in_word = true;
+ }
+ }
+ if (unicode == unicode_right_triangle) {
+ group_id++;
+ }
+ offset += size;
+ }
+ /* If the last word is not followed by a separator, it has to be handled separately. */
+ if (is_in_word) {
+ const StringRef word = str_copy.drop_prefix(int(word_start));
+ r_words.append(word);
+ r_word_group_ids.append(group_id);
+ }
+}
+
+void StringSearchBase::add_impl(const StringRef str, void *user_data, const float weight)
+{
+ BLI_assert(BLI_str_utf8_invalid_byte(str.data(), str.size()) == -1);
+ Vector<StringRef, 64> words;
+ Vector<int, 64> word_group_ids;
+ string_search::extract_normalized_words(str, allocator_, words, word_group_ids);
+ const int recent_time = recent_cache_ ?
+ recent_cache_->logical_time_by_str.lookup_default(str, -1) :
+ -1;
+ int main_group_id = 0;
+ if (!word_group_ids.is_empty()) {
+ switch (main_words_heuristic_) {
+ case MainWordsHeuristic::FirstGroup: {
+ main_group_id = 0;
+ break;
+ }
+ case MainWordsHeuristic::LastGroup: {
+ main_group_id = word_group_ids.last();
+ break;
+ }
+ case MainWordsHeuristic::All: {
+ main_group_id = 0;
+ word_group_ids.fill(0);
+ break;
+ }
+ }
+ }
+
+ int main_group_length = 0;
+ for (const int i : words.index_range()) {
+ if (word_group_ids[i] == main_group_id) {
+ main_group_length += int(words[i].size());
+ }
+ }
+
+ /* Not checking for the "D" to avoid problems with upper/lower-case. */
+ const bool is_deprecated = str.find("eprecated") != StringRef::not_found;
+
+ items_.append({user_data,
+ allocator_.construct_array_copy(words.as_span()),
+ allocator_.construct_array_copy(word_group_ids.as_span()),
+ main_group_id,
+ main_group_length,
+ int(str.size()),
+ weight,
+ recent_time,
+ is_deprecated});
+}
+
+Vector<void *> StringSearchBase::query_impl(const StringRef query) const
+{
+ LinearAllocator<> allocator;
+ Vector<StringRef, 64> query_words;
+ /* This is just a dummy value that is not used for the query. */
+ Vector<int, 64> word_group_ids;
+ string_search::extract_normalized_words(query, allocator, query_words, word_group_ids);
+
+ /* Compute score of every result. */
+ Array<std::optional<float>> all_scores(items_.size());
+ /* BUI: serial loop (Blender: threading::parallel_for in chunks of 256). */
+ for (const int i : items_.index_range()) {
+ const SearchItem &item = items_[i];
+ const std::optional<float> score = string_search::score_query_against_words(query_words,
+ item);
+ all_scores[i] = score;
+ }
+ MultiValueMap<float, int> result_indices_by_score;
+ for (const int i : items_.index_range()) {
+ const std::optional<float> score = all_scores[i];
+ if (score.has_value()) {
+ result_indices_by_score.add(*score, i);
+ }
+ }
+
+ Vector<float> found_scores;
+ for (const float score : result_indices_by_score.keys()) {
+ found_scores.append(score);
+ }
+ std::ranges::sort(found_scores, std::greater<>());
+
+ /* Add results to output vector in correct order. First come the results with the best match
+ * score. Results with the same score are in the order they have been added to the search. */
+ Vector<int> sorted_result_indices;
+ for (const float score : found_scores) {
+ MutableSpan<int> indices = result_indices_by_score.lookup(score);
+ if (score == found_scores[0]) {
+ if (!query.is_empty()) {
+ /* Sort items with best score by length. Shorter items are more likely the ones you are
+ * looking for. This also ensures that exact matches will be at the top, even if the query
+ * is a sub-string of another item. */
+ std::ranges::sort(indices, [&](int a, int b) {
+ const SearchItem &item_a = items_[a];
+ const SearchItem &item_b = items_[b];
+ /* The length of the main group has priority over the total length. */
+ return item_a.main_group_length < item_b.main_group_length ||
+ (item_a.main_group_length == item_b.main_group_length &&
+ item_a.total_length < item_b.total_length);
+ });
+ /* Prefer items with larger weights. Use `stable_sort` so that if the weights are the same,
+ * the order won't be changed. */
+ std::stable_sort(indices.begin(), indices.end(), [&](int a, int b) {
+ return items_[a].weight > items_[b].weight;
+ });
+ }
+ /* If the query gets longer, it's less likely that accessing recent items is desired. Better
+ * always show the best match in this case. */
+ if (query.size() <= 1) {
+ /* Prefer items that have been selected recently. */
+ std::stable_sort(indices.begin(), indices.end(), [&](int a, int b) {
+ return items_[a].recent_time > items_[b].recent_time;
+ });
+ }
+ }
+ sorted_result_indices.extend(indices);
+ }
+
+ Vector<void *> sorted_data(sorted_result_indices.size());
+ for (const int i : sorted_result_indices.index_range()) {
+ const int result_index = sorted_result_indices[i];
+ const SearchItem &item = items_[result_index];
+ sorted_data[i] = item.user_data;
+ }
+ return sorted_data;
+}
+
+} // namespace blender::string_search
diff --git a/core/tests/test_core.c b/core/tests/test_core.c
index 554a8bc..87408f5 100644
--- a/core/tests/test_core.c
+++ b/core/tests/test_core.c
@@ -15,6 +15,7 @@
#include "BLI_mempool.h"
#include "BLI_string.h"
#include "BLI_string_utf8.h"
+#include "BUI_blender_c.h"
#include "MEM_guardedalloc.h"
static int failures = 0;
@@ -149,15 +150,75 @@ static void test_color(void)
static void test_strings(void)
{
- CHECK(BLI_strlen_utf8("héllo") == 6);
+ CHECK(BLI_strlen_utf8("héllo") == 5); /* code points (core builds with unsigned char, as Blender) */
CHECK(BLI_strnlen("abc", 10) == 3);
char buf[16];
BLI_snprintf(buf, sizeof(buf), "%d-%s", 42, "x");
CHECK(strcmp(buf, "42-x") == 0);
}
+static int expr_is(const char *s, double want)
+{
+ double v = -12345.0;
+ return BUI_expr_eval(s, NULL, NULL, 0, &v) && fabs(v - want) < 1e-9;
+}
+
+/* Blender's expr_pylike_eval.cc (core/intern), with the BUI additions. */
+static void test_expr(void)
+{
+ double v;
+ CHECK(expr_is("1/3 + 2**2", 1.0 / 3.0 + 4.0));
+ CHECK(expr_is("2^3", 8.0));
+ CHECK(expr_is("-2**2", -4.0));
+ CHECK(expr_is("2**-1", 0.5));
+ CHECK(expr_is("2**3**2", 512.0)); /* right associative */
+ CHECK(expr_is("7 // 2", 3.0));
+ CHECK(expr_is("7 % 4", 3.0));
+ CHECK(expr_is("2*pi", 2.0 * 3.14159265358979323846));
+ CHECK(expr_is("tau", 2.0 * 3.14159265358979323846));
+ CHECK(expr_is("e", 2.71828182845904523536));
+ CHECK(expr_is("sqrt(16) + max(1, 5, 3)", 9.0));
+ CHECK(expr_is("radians(180)", 3.14159265358979323846));
+ CHECK(expr_is("1 if 2 > 1 else 0", 1.0));
+ CHECK(expr_is("05", 5.0));
+ CHECK(expr_is(".5", 0.5));
+ CHECK(!BUI_expr_eval("1/0", NULL, NULL, 0, &v));
+ CHECK(!BUI_expr_eval("1 +", NULL, NULL, 0, &v));
+ CHECK(!BUI_expr_eval("foo(2)", NULL, NULL, 0, &v));
+ const char *names[] = {"x"};
+ const double vals[] = {3.0};
+ CHECK(BUI_expr_eval("x*x + 1", names, vals, 1, &v) && v == 10.0);
+}
+
+/* Blender's string_search.cc (core/intern). */
+static void test_string_search(void)
+{
+ static const char *items[] = {
+ "Add Cube", "Add Cylinder", "Delete Vertices", "Shade Smooth", "Subdivision Surface"};
+ BUIStringSearch *s = BUI_string_search_new(NULL, BUI_SEARCH_MAIN_ALL);
+ for (int i = 0; i < 5; i++) {
+ BUI_string_search_add(s, items[i], (void *)items[i], 0);
+ }
+ void *found[8];
+ /* word-initial matching: "ss" -> Shade Smooth / Subdivision Surface */
+ int n = BUI_string_search_query(s, "ss", found, 8);
+ CHECK(n >= 2);
+ CHECK(n >= 1 && (found[0] == items[3] || found[0] == items[4]));
+ /* typo tolerance: "cylnder" still finds "Add Cylinder" first */
+ n = BUI_string_search_query(s, "cylnder", found, 8);
+ CHECK(n >= 1 && found[0] == items[1]);
+ /* no match */
+ n = BUI_string_search_query(s, "zzzz", found, 8);
+ CHECK(n == 0);
+ BUI_string_search_free(s);
+ CHECK(BUI_string_search_fuzzy_errors("cylnder", "cylinder") == 1);
+ CHECK(BUI_string_search_fuzzy_errors("xyz", "cylinder") == -1);
+}
+
int main(void)
{
+ test_expr();
+ test_string_search();
test_listbase();
test_ghash();
test_dynstr();
diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt
index c765cc6..6602f5f 100644
--- a/kit/CMakeLists.txt
+++ b/kit/CMakeLists.txt
@@ -21,6 +21,10 @@ add_library(bui_kit STATIC
intern/kit_regions.c
intern/kit_nodes.c
intern/kit_custom.c
+ # Blender's UI sources copied and edited for the kit (C++; see blender/bk_blender.h)
+ intern/blender/interface_string_search.cc
+ intern/blender/interface_utils.cc
+ intern/blender/interface_undo.cc
extern/nanosvg/blender_nanosvg.c
extern/nanosvg/blender_raster.c
)
diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h
index d4f24c2..6c62518 100644
--- a/kit/include/BUI_kit.h
+++ b/kit/include/BUI_kit.h
@@ -536,9 +536,19 @@ void BK_draw_widget(BuiRaster *r, const BKWidgetDraw *w);
/* Width of `s` (len < 0: NUL-terminated) in the UI font at BK_scale(). */
float BK_text_width(const char *s, int len);
-/* Evaluate Blender-style number input ("2*pi", "1/3 + 2^2"). */
+/* Evaluate Blender-style number input ("2*pi", "1/3 + 2^2"): Blender's
+ * BLI_expr_pylike_eval (+ - * / // % ** ^, comparisons, and/or/not, x if c
+ * else y, pi e tau, min max sin cos sqrt atan2 floor ...). */
int BK_eval_number(const char *expr, double *r_value);
+/* Menu search ranks with Blender's string search (word initials, typos);
+ * items chosen from a search rank first for short queries (Blender's recent
+ * searches). On by default, kept in memory; load/save use one line per item. */
+void BK_recent_searches_enable(int enabled);
+void BK_recent_searches_clear(void);
+void BK_recent_searches_load(const char *path);
+void BK_recent_searches_save(const char *path);
+
#ifdef __cplusplus
}
#endif
diff --git a/kit/intern/blender/bk_blender.h b/kit/intern/blender/bk_blender.h
new file mode 100644
index 0000000..8468521
--- /dev/null
+++ b/kit/intern/blender/bk_blender.h
@@ -0,0 +1,34 @@
+/* C declarations for the Blender sources copied into kit/intern/blender/
+ * (C++ files edited for the kit; each keeps its Blender license header and
+ * marks its edits with "BUI:").
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* interface_string_search.cc: recent searches (ranked first for short queries).
+ * Public: BK_recent_searches_* in BUI_kit.h (declared here too for C linkage). */
+void BK_recent_searches_enable(int enabled);
+void BK_recent_searches_clear(void);
+void BK_recent_searches_load(const char *path);
+void BK_recent_searches_save(const char *path);
+void bk_search_recent_add(const char *chosen);
+const void *bk_search_recent_cache(void); /* blender::string_search::RecentCache or NULL */
+
+/* interface_undo.cc: the undo stack of an active text edit. */
+typedef struct BKTextUndo BKTextUndo;
+BKTextUndo *bk_textedit_undo_stack_create(void);
+void bk_textedit_undo_stack_destroy(BKTextUndo *stack);
+void bk_textedit_undo_push(BKTextUndo *stack, const char *text, int cursor_index);
+/* direction -1 undo, 1 redo; NULL when there is nothing to step to */
+const char *bk_textedit_undo(BKTextUndo *stack, int direction, int *r_cursor_index);
+
+/* interface_utils.cc: UI_calc_float_precision (display decimals for small values). */
+int bk_calc_float_precision(int prec, double value);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/kit/intern/blender/interface_string_search.cc b/kit/intern/blender/interface_string_search.cc
new file mode 100644
index 0000000..e27a728
--- /dev/null
+++ b/kit/intern/blender/interface_string_search.cc
@@ -0,0 +1,141 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/* BUI: copied from editors/interface/interface_string_search.cc: the recent
+ * searches cache that ranks recently chosen menu-search / search-field items
+ * first. BUI edits, marked "BUI:": no user preferences (U.flag) — a runtime
+ * switch instead; the file path is given by the caller (no BKE_appdir); plain
+ * std::fstream; C entry points at the end (bk_blender.h). */
+
+#include <algorithm>
+#include <fstream>
+#include <optional>
+#include <string>
+
+#include "BLI_map.hh"
+#include "BLI_string_search.hh"
+#include "BLI_vector.hh"
+
+#include "bk_blender.h"
+
+namespace blender::ui::string_search {
+
+using blender::string_search::RecentCache;
+
+/* BUI: replaces `U.flag & USER_FLAG_RECENT_SEARCHES_DISABLE`. */
+static bool recent_searches_disabled = false;
+
+struct RecentCacheStorage {
+ /**
+ * Is incremented every time a search item has been selected. This is used to keep track of the
+ * order of recent searches.
+ */
+ int logical_clock = 0;
+ RecentCache cache;
+};
+
+static RecentCacheStorage &get_recent_cache_storage()
+{
+ static RecentCacheStorage storage;
+ return storage;
+}
+
+void add_recent_search(const StringRef chosen_str)
+{
+ RecentCacheStorage &storage = get_recent_cache_storage();
+ storage.cache.logical_time_by_str.add_overwrite(chosen_str, storage.logical_clock);
+ storage.logical_clock++;
+}
+
+const RecentCache *get_recent_cache_or_null()
+{
+ if (recent_searches_disabled) {
+ return nullptr;
+ }
+ RecentCacheStorage &storage = get_recent_cache_storage();
+ return &storage.cache;
+}
+
+/* BUI: the path is the caller's (Blender: BKE_appdir user config + recent-searches.txt). */
+void write_recent_searches_file(const char *path)
+{
+ if (recent_searches_disabled || path == nullptr) {
+ return;
+ }
+
+ const RecentCacheStorage &storage = get_recent_cache_storage();
+ /* Avoid creating an empty file. */
+ if (storage.cache.logical_time_by_str.is_empty()) {
+ return;
+ }
+
+ Vector<std::pair<int, std::string>> values;
+ for (const auto item : storage.cache.logical_time_by_str.items()) {
+ values.append({item.value, item.key});
+ }
+ std::sort(values.begin(), values.end());
+
+ std::fstream file(path, std::ios::out);
+ for (const auto &item : values) {
+ file.write(item.second.data(), item.second.size());
+ file.write("\n", 1);
+ }
+}
+
+void read_recent_searches_file(const char *path)
+{
+ if (recent_searches_disabled || path == nullptr) {
+ return;
+ }
+
+ RecentCacheStorage &storage = get_recent_cache_storage();
+ storage.logical_clock = 0;
+ storage.cache.logical_time_by_str.clear();
+
+ std::fstream file(path, std::ios::in);
+ std::string line;
+ while (std::getline(file, line)) {
+ storage.cache.logical_time_by_str.add_overwrite(line, storage.logical_clock);
+ storage.logical_clock++;
+ }
+}
+
+} // namespace blender::ui::string_search
+
+/* BUI: C entry points for the kit. */
+using namespace blender::ui::string_search;
+
+void bk_search_recent_add(const char *chosen)
+{
+ if (chosen && !recent_searches_disabled) {
+ add_recent_search(blender::StringRef(chosen));
+ }
+}
+
+const void *bk_search_recent_cache(void)
+{
+ return get_recent_cache_or_null();
+}
+
+void BK_recent_searches_enable(int enabled)
+{
+ recent_searches_disabled = !enabled;
+}
+
+void BK_recent_searches_clear(void)
+{
+ RecentCacheStorage &storage = get_recent_cache_storage();
+ storage.logical_clock = 0;
+ storage.cache.logical_time_by_str.clear();
+}
+
+void BK_recent_searches_load(const char *path)
+{
+ read_recent_searches_file(path);
+}
+
+void BK_recent_searches_save(const char *path)
+{
+ write_recent_searches_file(path);
+}
diff --git a/kit/intern/blender/interface_undo.cc b/kit/intern/blender/interface_undo.cc
new file mode 100644
index 0000000..efbfc20
--- /dev/null
+++ b/kit/intern/blender/interface_undo.cc
@@ -0,0 +1,184 @@
+/* SPDX-FileCopyrightText: 2020 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup edinterface
+ *
+ * Undo stack to use for UI widgets that manage their own editing state.
+ */
+
+/* BUI: copied from editors/interface/interface_undo.cc: the undo stack of an
+ * active text edit (Ctrl+Z / Ctrl+Shift+Z while typing, kit_core.c bk_te_key).
+ * BUI edits, marked "BUI:": the states list is linked by hand (the kit's core
+ * ListBase API is C, ListBaseT is not vendored), states are plain malloc
+ * blocks, and C entry points are added at the end (bk_blender.h). */
+
+#include <cstdlib>
+#include <cstring>
+
+#include "bk_blender.h"
+
+namespace blender::ui {
+
+/* -------------------------------------------------------------------- */
+/** \name Text Field Undo Stack
+ * \{ */
+
+struct UndoStack_Text_State {
+ UndoStack_Text_State *next, *prev;
+ int cursor_index;
+ char text[1]; /* BUI: [1] (C++ has no zero-length arrays) */
+};
+
+/* BUI: a first/last pair instead of ListBaseT<UndoStack_Text_State>. */
+struct UndoStack_Text_States {
+ UndoStack_Text_State *first, *last;
+};
+
+struct UndoStack_Text {
+ UndoStack_Text_States states;
+ UndoStack_Text_State *current;
+};
+
+/* BUI: BLI_remlink / BLI_addtail for this list. */
+static void states_remlink(UndoStack_Text_States *lb, UndoStack_Text_State *state)
+{
+ if (state->next) {
+ state->next->prev = state->prev;
+ }
+ if (state->prev) {
+ state->prev->next = state->next;
+ }
+ if (lb->last == state) {
+ lb->last = state->prev;
+ }
+ if (lb->first == state) {
+ lb->first = state->next;
+ }
+}
+
+static void states_addtail(UndoStack_Text_States *lb, UndoStack_Text_State *state)
+{
+ state->next = nullptr;
+ state->prev = lb->last;
+ if (lb->last) {
+ lb->last->next = state;
+ }
+ if (lb->first == nullptr) {
+ lb->first = state;
+ }
+ lb->last = state;
+}
+
+static const char *textedit_undo_impl(UndoStack_Text *stack, int *r_cursor_index)
+{
+ /* Don't undo if no data has been pushed yet. */
+ if (stack->current == nullptr) {
+ return nullptr;
+ }
+
+ /* Travel backwards in the stack and copy information to the caller. */
+ if (stack->current->prev != nullptr) {
+ stack->current = stack->current->prev;
+
+ *r_cursor_index = stack->current->cursor_index;
+ return stack->current->text;
+ }
+ return nullptr;
+}
+
+static const char *textedit_redo_impl(UndoStack_Text *stack, int *r_cursor_index)
+{
+ /* Don't redo if no data has been pushed yet. */
+ if (stack->current == nullptr) {
+ return nullptr;
+ }
+
+ /* Only redo if new data has not been entered since the last undo. */
+ if (stack->current->next) {
+ stack->current = stack->current->next;
+
+ *r_cursor_index = stack->current->cursor_index;
+ return stack->current->text;
+ }
+ return nullptr;
+}
+
+const char *textedit_undo(UndoStack_Text *stack, int direction, int *r_cursor_index)
+{
+ if (direction < 0) {
+ return textedit_undo_impl(stack, r_cursor_index);
+ }
+ return textedit_redo_impl(stack, r_cursor_index);
+}
+
+void textedit_undo_push(UndoStack_Text *stack, const char *text, int cursor_index)
+{
+ /* Clear all redo actions from the current state. */
+ if (stack->current != nullptr) {
+ while (stack->current->next) {
+ UndoStack_Text_State *state = stack->current->next;
+ states_remlink(&stack->states, state);
+ free(state); /* BUI: free (Blender: MEM_delete) */
+ }
+ }
+
+ /* Create the new state. */
+ const int text_size = int(strlen(text)) + 1;
+ stack->current = static_cast<UndoStack_Text_State *>(
+ malloc(sizeof(UndoStack_Text_State) + text_size)); /* BUI: malloc */
+ stack->current->cursor_index = cursor_index;
+ memcpy(stack->current->text, text, text_size);
+ states_addtail(&stack->states, stack->current);
+}
+
+UndoStack_Text *textedit_undo_stack_create()
+{
+ UndoStack_Text *stack = static_cast<UndoStack_Text *>(calloc(1, sizeof(UndoStack_Text)));
+ stack->current = nullptr;
+ stack->states.first = stack->states.last = nullptr;
+
+ return stack;
+}
+
+void textedit_undo_stack_destroy(UndoStack_Text *stack)
+{
+ /* BUI: BLI_freelistN */
+ for (UndoStack_Text_State *state = stack->states.first; state;) {
+ UndoStack_Text_State *next = state->next;
+ free(state);
+ state = next;
+ }
+ free(stack);
+}
+
+/** \} */
+
+} // namespace blender::ui
+
+/* BUI: C entry points. */
+BKTextUndo *bk_textedit_undo_stack_create(void)
+{
+ return reinterpret_cast<BKTextUndo *>(blender::ui::textedit_undo_stack_create());
+}
+
+void bk_textedit_undo_stack_destroy(BKTextUndo *stack)
+{
+ if (stack) {
+ blender::ui::textedit_undo_stack_destroy(
+ reinterpret_cast<blender::ui::UndoStack_Text *>(stack));
+ }
+}
+
+void bk_textedit_undo_push(BKTextUndo *stack, const char *text, int cursor_index)
+{
+ blender::ui::textedit_undo_push(
+ reinterpret_cast<blender::ui::UndoStack_Text *>(stack), text, cursor_index);
+}
+
+const char *bk_textedit_undo(BKTextUndo *stack, int direction, int *r_cursor_index)
+{
+ return blender::ui::textedit_undo(
+ reinterpret_cast<blender::ui::UndoStack_Text *>(stack), direction, r_cursor_index);
+}
diff --git a/kit/intern/blender/interface_utils.cc b/kit/intern/blender/interface_utils.cc
new file mode 100644
index 0000000..e0ad667
--- /dev/null
+++ b/kit/intern/blender/interface_utils.cc
@@ -0,0 +1,88 @@
+/* SPDX-FileCopyrightText: 2009 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup edinterface
+ */
+
+/* BUI: an excerpt of editors/interface/interface_utils.cc — only
+ * calc_float_precision (UI_calc_float_precision), which number fields use for
+ * display so 0.00001 is not drawn as "0.000" (kit_widgets.c format_number).
+ * BUI edits, marked "BUI:": UI_PRECISION_FLOAT_MAX from UI_interface_c.hh is
+ * defined here, and a C entry point is added at the end. */
+
+#include <algorithm>
+#include <cmath>
+
+#include "BLI_assert.h"
+#include "BLI_utildefines.h"
+
+#include "bk_blender.h"
+
+/* BUI: from UI_interface_c.hh. */
+#define UI_PRECISION_FLOAT_MAX 6
+
+namespace blender::ui {
+
+/********************************** Misc **************************************/
+
+int calc_float_precision(int prec, double value)
+{
+ static const double pow10_neg[UI_PRECISION_FLOAT_MAX + 1] = {
+ 1e0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6};
+ static const double max_pow = 10000000.0; /* pow(10, UI_PRECISION_FLOAT_MAX) */
+
+ /* BUI: clamp first (Blender asserts; kit nodes take any "precision"). */
+ CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
+ BLI_assert(prec <= UI_PRECISION_FLOAT_MAX);
+ BLI_assert(fabs(pow10_neg[prec] - pow(10, -prec)) < 1e-16);
+
+ /* Check on the number of decimal places need to display the number,
+ * this is so 0.00001 is not displayed as 0.00,
+ * _but_, this is only for small values as 10.0001 will not get the same treatment.
+ */
+ value = fabs(value);
+ if ((value < pow10_neg[prec]) && (value > (1.0 / max_pow))) {
+ int value_i = int(lround(value * max_pow));
+ if (value_i != 0) {
+ const int prec_span = 3; /* show: 0.01001, 5 would allow 0.0100001 for eg. */
+ int test_prec;
+ int prec_min = -1;
+ int dec_flag = 0;
+ int i = UI_PRECISION_FLOAT_MAX;
+ while (i && value_i) {
+ if (value_i % 10) {
+ dec_flag |= 1 << i;
+ prec_min = i;
+ }
+ value_i /= 10;
+ i--;
+ }
+
+ /* even though its a small value, if the second last digit is not 0, use it */
+ test_prec = prec_min;
+
+ dec_flag = (dec_flag >> (prec_min + 1)) & ((1 << prec_span) - 1);
+
+ while (dec_flag) {
+ test_prec++;
+ dec_flag = dec_flag >> 1;
+ }
+
+ prec = std::max(test_prec, prec);
+ }
+ }
+
+ CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
+
+ return prec;
+}
+
+} // namespace blender::ui
+
+/* BUI: C entry point. */
+int bk_calc_float_precision(int prec, double value)
+{
+ return blender::ui::calc_float_precision(prec, value);
+}
diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c
index 6176027..a07816b 100644
--- a/kit/intern/kit_core.c
+++ b/kit/intern/kit_core.c
@@ -20,6 +20,8 @@
# include <windows.h>
#endif
+#include "BUI_blender_c.h"
+#include "blender/bk_blender.h"
#include "kit_intern.h"
/* Blender's UTF-8 cursor stepping (blenlib, linked from bui_core). */
@@ -1228,6 +1230,10 @@ const char *BK_get_str(BKNode *n, const char *key)
if (strcmp(key, "edit") == 0) {
return n->edit ? n->edit->text : "";
}
+ if (strcmp(key, "display") == 0) { /* number fields: the value text as drawn */
+ const char *s = bk_number_display(n);
+ return s ? s : "";
+ }
if (strcmp(key, "type") == 0) {
return n->cls->name;
}
@@ -1459,7 +1465,10 @@ void bk_forget(BKContext *ctx, BKNode *subtree)
undo_forget(ctx, subtree);
for (int i = ctx->nanim - 1; i >= 0; i--) {
if (is_within(ctx->anim[i], subtree)) {
- ctx->anim[i] = ctx->anim[--ctx->nanim];
+ const int last = --ctx->nanim;
+ ctx->anim[i] = ctx->anim[last];
+ ctx->anim_start[i] = ctx->anim_start[last];
+ ctx->anim_from[i] = ctx->anim_from[last];
}
}
for (int i = 0; i < ctx->nmulti; i++) {
@@ -2762,12 +2771,16 @@ BKTextEdit *bk_te_new(const char *text, bool select_all)
memcpy(te->text, text ? text : "", (size_t)te->len + 1);
te->caret = te->len;
te->anchor = select_all ? 0 : -1;
+ /* ui_textedit_begin: textedit_undo_stack_create + push of the initial string */
+ te->undo = bk_textedit_undo_stack_create();
+ bk_textedit_undo_push(te->undo, te->text, te->caret);
return te;
}
void bk_te_free(BKTextEdit *te)
{
if (te) {
+ bk_textedit_undo_stack_destroy(te->undo);
free(te->text);
free(te);
}
@@ -2842,7 +2855,43 @@ static int te_step(BKTextEdit *te, int pos, bool next, bool word)
return pos;
}
+static int te_key(BKTextEdit *te, BKContext *ctx, const char *text, const char *ks, int mods);
+
+/* Blender's ui_do_but_textedit undo: Ctrl+Z / Ctrl+Shift+Z (and Ctrl+Y) step
+ * the edit's own stack (interface_undo.cc); every other change is pushed. */
int bk_te_key(BKTextEdit *te, BKContext *ctx, const char *text, const char *ks, int mods)
+{
+ if ((mods & BK_CTRL) && !(mods & BK_ALT) && (bk_keysym_is(ks, "z") || bk_keysym_is(ks, "y"))) {
+ const bool is_redo = (mods & BK_SHIFT) || bk_keysym_is(ks, "y");
+ int undo_pos;
+ const char *undo_str = bk_textedit_undo(te->undo, is_redo ? 1 : -1, &undo_pos);
+ if (undo_str != NULL) {
+ te->len = (int)strlen(undo_str);
+ if (te->len + 1 > te->cap) {
+ te->cap = te->len + 64;
+ te->text = (char *)realloc(te->text, (size_t)te->cap);
+ }
+ memcpy(te->text, undo_str, (size_t)te->len + 1);
+ /* Set the cursor & clear selection. */
+ te->caret = BK_CLAMP(undo_pos, 0, te->len);
+ te->anchor = -1;
+ }
+ return TE_CHANGED;
+ }
+ char stack_buf[256];
+ char *before = te->len < (int)sizeof(stack_buf) ? stack_buf : (char *)malloc((size_t)te->len + 1);
+ memcpy(before, te->text, (size_t)te->len + 1);
+ const int res = te_key(te, ctx, text, ks, mods);
+ if (res == TE_CHANGED && strcmp(before, te->text) != 0) {
+ bk_textedit_undo_push(te->undo, te->text, te->caret);
+ }
+ if (before != stack_buf) {
+ free(before);
+ }
+ return res;
+}
+
+static int te_key(BKTextEdit *te, BKContext *ctx, const char *text, const char *ks, int mods)
{
const bool ctrl = mods & BK_CTRL, shift = mods & BK_SHIFT;
if (bk_keysym_is(ks, "ISO_Left_Tab")) { /* X11's Shift+Tab */
@@ -3019,191 +3068,12 @@ void bk_te_draw(BKTextEdit *te, const BKRect *rect, const uchar color[4])
/** \name Number expressions ("2*pi", "1/3+2^2")
* \{ */
-typedef struct Parser {
- const char *s;
- bool err;
-} Parser;
-
-static void skip_ws(Parser *p)
-{
- while (*p->s == ' ' || *p->s == '\t') {
- p->s++;
- }
-}
-
-static double parse_expr(Parser *p);
-
-static double parse_atom(Parser *p)
-{
- skip_ws(p);
- if (*p->s == '(') {
- p->s++;
- const double v = parse_expr(p);
- skip_ws(p);
- if (*p->s == ')') {
- p->s++;
- }
- else {
- p->err = true;
- }
- return v;
- }
- if (isalpha((uchar)*p->s)) {
- char name[16];
- int n = 0;
- while (isalnum((uchar)*p->s) && n < 15) {
- name[n++] = *p->s++;
- }
- name[n] = 0;
- if (strcmp(name, "pi") == 0) {
- return 3.14159265358979323846;
- }
- if (strcmp(name, "tau") == 0) {
- return 6.28318530717958647692;
- }
- if (strcmp(name, "e") == 0) {
- return 2.71828182845904523536;
- }
- /* functions */
- skip_ws(p);
- if (*p->s == '(') {
- const double a = parse_atom(p);
- if (strcmp(name, "sqrt") == 0) {
- return sqrt(a);
- }
- if (strcmp(name, "sin") == 0) {
- return sin(a);
- }
- if (strcmp(name, "cos") == 0) {
- return cos(a);
- }
- if (strcmp(name, "tan") == 0) {
- return tan(a);
- }
- if (strcmp(name, "abs") == 0) {
- return fabs(a);
- }
- if (strcmp(name, "radians") == 0) {
- return a * 3.14159265358979323846 / 180.0;
- }
- if (strcmp(name, "degrees") == 0) {
- return a * 180.0 / 3.14159265358979323846;
- }
- }
- p->err = true;
- return 0.0;
- }
- char *end;
- const double v = strtod(p->s, &end);
- if (end == p->s) {
- p->err = true;
- return 0.0;
- }
- p->s = end;
- return v;
-}
-
-static double parse_unary(Parser *p);
-
-static double parse_power(Parser *p)
-{
- const double base = parse_atom(p);
- skip_ws(p);
- if ((p->s[0] == '*' && p->s[1] == '*') || p->s[0] == '^') {
- p->s += p->s[0] == '^' ? 1 : 2;
- return pow(base, parse_unary(p)); /* right associative */
- }
- return base;
-}
-
-static double parse_unary(Parser *p)
-{
- skip_ws(p);
- if (*p->s == '-') {
- p->s++;
- return -parse_unary(p);
- }
- if (*p->s == '+') {
- p->s++;
- return parse_unary(p);
- }
- return parse_power(p);
-}
-
-static double parse_term(Parser *p)
-{
- double v = parse_unary(p);
- while (!p->err) {
- skip_ws(p);
- const char c = *p->s;
- if (c == '*' && p->s[1] != '*') {
- p->s++;
- v *= parse_unary(p);
- }
- else if (c == '/' && p->s[1] == '/') {
- p->s += 2;
- const double d = parse_unary(p);
- if (d == 0.0) {
- p->err = true;
- return 0.0;
- }
- v = floor(v / d);
- }
- else if (c == '/') {
- p->s++;
- const double d = parse_unary(p);
- if (d == 0.0) {
- p->err = true;
- return 0.0;
- }
- v /= d;
- }
- else if (c == '%') {
- p->s++;
- const double d = parse_unary(p);
- if (d == 0.0) {
- p->err = true;
- return 0.0;
- }
- v = fmod(v, d);
- }
- else {
- break;
- }
- }
- return v;
-}
-
-static double parse_expr(Parser *p)
-{
- double v = parse_term(p);
- while (!p->err) {
- skip_ws(p);
- if (*p->s == '+') {
- p->s++;
- v += parse_term(p);
- }
- else if (*p->s == '-') {
- p->s++;
- v -= parse_term(p);
- }
- else {
- break;
- }
- }
- return v;
-}
-
+/* Blender's BLI_expr_pylike_eval (core/intern/expr_pylike_eval.cc, through
+ * BUI_blender_c.h): what Blender uses for number fields when Python is off,
+ * with BUI's `**`/`^`, `//`, `%`, `e` and `tau`. */
int BK_eval_number(const char *expr, double *r_value)
{
- Parser p = {expr, false};
- const double v = parse_expr(&p);
- skip_ws(&p);
- if (p.err || *p.s != 0 || !isfinite(v)) {
- return 0;
- }
- *r_value = v;
- return 1;
+ return BUI_expr_eval(expr, NULL, NULL, 0, r_value);
}
/** \} */
@@ -3515,7 +3385,9 @@ static void undo_forget(BKContext *ctx, BKNode *subtree)
}
static int g_animations = 1;
-#define ANIM_SECONDS 0.12
+/* Blender's panel animation (interface_panel.cc): ANIMATION_TIME 0.30 s, eased
+ * by do_animate's `fac = min_ff(sqrtf(fac), 1.0f)` (fast start, slow end). */
+#define ANIMATION_TIME 0.30
void BK_set_animations(int enabled)
{
@@ -3534,15 +3406,22 @@ void bk_anim_start(BKNode *n)
n->anim = (n->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
return;
}
+ const double now = bk_time();
for (int i = 0; i < ctx->nanim; i++) {
if (ctx->anim[i] == n) {
- return; /* already running: it just reverses direction */
+ /* already running: reverse from where it is (Blender restarts its
+ * animation from the panels' current offsets) */
+ ctx->anim_start[i] = now;
+ ctx->anim_from[i] = n->anim;
+ return;
}
}
if (ctx->nanim < BK_MAX_ANIM) {
if (!ctx->nanim) {
- ctx->anim_t = bk_time();
+ ctx->anim_t = now;
}
+ ctx->anim_start[ctx->nanim] = now;
+ ctx->anim_from[ctx->nanim] = n->anim;
ctx->anim[ctx->nanim++] = n;
bk_ctx_request(ctx);
}
@@ -3554,19 +3433,19 @@ static void anim_step(BKContext *ctx)
return;
}
const double now = bk_time();
- const float step = (float)((now - ctx->anim_t) / ANIM_SECONDS);
ctx->anim_t = now;
for (int i = ctx->nanim - 1; i >= 0; i--) {
BKNode *n = ctx->anim[i];
const float target = (n->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
- if (n->anim < target) {
- n->anim = BK_MIN(target, n->anim + step);
- }
- else {
- n->anim = BK_MAX(target, n->anim - step);
- }
+ /* do_animate: fac = (now - starttime) / ANIMATION_TIME; fac = min(sqrt(fac), 1) */
+ float fac = (float)((now - ctx->anim_start[i]) / ANIMATION_TIME);
+ fac = BK_MIN(sqrtf(BK_MAX(fac, 0.0f)), 1.0f);
+ n->anim = fac >= 1.0f ? target : ctx->anim_from[i] + (target - ctx->anim_from[i]) * fac;
if (n->anim == target) {
- ctx->anim[i] = ctx->anim[--ctx->nanim];
+ const int last = --ctx->nanim;
+ ctx->anim[i] = ctx->anim[last];
+ ctx->anim_start[i] = ctx->anim_start[last];
+ ctx->anim_from[i] = ctx->anim_from[last];
}
}
g_gen++;
diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h
index e9b2f03..cbbca2b 100644
--- a/kit/intern/kit_intern.h
+++ b/kit/intern/kit_intern.h
@@ -187,6 +187,7 @@ typedef struct BKTextEdit {
int caret, anchor; /* byte offsets; anchor < 0 = no selection */
float scroll;
char mask[8]; /* shown instead of each character (password fields), "" = none */
+ struct BKTextUndo *undo; /* Blender's interface_undo.cc text stack (Ctrl+Z while typing) */
} BKTextEdit;
enum { TE_NONE = 0, TE_CHANGED, TE_CONFIRM, TE_CANCEL, TE_NEXT, TE_PREV };
@@ -504,6 +505,8 @@ struct BKContext {
int nmulti, multi_x0;
/* animations */
BKNode *anim[BK_MAX_ANIM];
+ double anim_start[BK_MAX_ANIM]; /* when each animation (re)started */
+ float anim_from[BK_MAX_ANIM]; /* its open fraction then */
int nanim;
double anim_t;
/* custom nodes */
@@ -532,6 +535,8 @@ bool bk_anim_running(const BKNode *n);
void bk_edit_next(BKNode *from, int dir);
int bk_textarea_set_text(BKNode *n, const char *s);
const char *bk_textarea_text(BKNode *n);
+/* The value text a number field / slider draws (static buffer; NULL for others). */
+const char *bk_number_display(BKNode *n);
void bk_ctx_dirty_rect(BKContext *ctx, BKRect r);
void bk_ctx_request(BKContext *ctx);
diff --git a/kit/intern/kit_menus.c b/kit/intern/kit_menus.c
index 35c1eff..56dc2a4 100644
--- a/kit/intern/kit_menus.c
+++ b/kit/intern/kit_menus.c
@@ -16,6 +16,8 @@
#include <stdlib.h>
#include <string.h>
+#include "BUI_blender_c.h"
+#include "blender/bk_blender.h"
#include "kit_intern.h"
static int u(void)
@@ -416,6 +418,10 @@ static void menu_pick(BKNode *n, int row)
void *data = items[row].data;
void *ref = items[row].ref;
BKNode *owner = menu_root(n)->parent;
+ if (MENU(menu_root(n))->query[0]) {
+ /* a menu-search result: remembered as a recent search (interface_string_search.cc) */
+ bk_search_recent_add(items[row].text);
+ }
bk_retain(ref);
BK_close_popups(ctx);
if (fn) {
@@ -451,18 +457,7 @@ static void menu_filter_walk(MenuData *m, const BKMenuSpec *items, int count, co
menu_filter_walk(m, it->sub, it->nsub, full, q, out, nout, cap);
continue;
}
- /* case-insensitive substring */
- bool hit = false;
- for (const char *s = it->text; *s && !hit; s++) {
- size_t k = 0;
- while (q[k] && s[k] && tolower((unsigned char)s[k]) == tolower((unsigned char)q[k])) {
- k++;
- }
- hit = q[k] == 0;
- }
- if (!hit) {
- continue;
- }
+ /* every leaf is a candidate; Blender's string search filters and ranks them */
if (*nout == *cap) {
*cap = *cap ? *cap * 2 : 16;
*out = (BKMenuSpec *)realloc(*out, sizeof(BKMenuSpec) * (size_t)*cap);
@@ -484,8 +479,38 @@ static void menu_filter(BKNode *n)
m->filtered = NULL;
m->nfiltered = 0;
if (m->query[0]) {
- int cap = 0;
- menu_filter_walk(m, m->all, m->nall, "", m->query, &m->filtered, &m->nfiltered, &cap);
+ /* Blender's menu search (interface_template_search_menu.cc): every leaf as
+ * "Menu ▸ Submenu ▸ Item", filtered and ranked by blenlib's
+ * string_search (word-initial matches, typo tolerance, recent items first),
+ * weighting the last group (the item itself). */
+ BKMenuSpec *all = NULL;
+ int nall = 0, cap = 0;
+ menu_filter_walk(m, m->all, m->nall, "", m->query, &all, &nall, &cap);
+ BUIStringSearch *search = BUI_string_search_new(bk_search_recent_cache(),
+ BUI_SEARCH_MAIN_LAST);
+ for (int i = 0; i < nall; i++) {
+ BUI_string_search_add(search, all[i].text, (void *)(intptr_t)(i + 1), 0);
+ }
+ void **found = (void **)malloc(sizeof(void *) * (size_t)(nall ? nall : 1));
+ const int nfound = BUI_string_search_query(search, m->query, found, nall);
+ BUI_string_search_free(search);
+ bool *used = (bool *)calloc((size_t)(nall ? nall : 1), sizeof(bool));
+ m->filtered = nfound ? (BKMenuSpec *)malloc(sizeof(BKMenuSpec) * (size_t)nfound) : NULL;
+ for (int k = 0; k < nfound && k < nall; k++) {
+ const int i = (int)(intptr_t)found[k] - 1;
+ m->filtered[m->nfiltered++] = all[i];
+ used[i] = true;
+ }
+ for (int i = 0; i < nall; i++) {
+ if (!used[i]) {
+ free((char *)all[i].text);
+ free((char *)all[i].shortcut);
+ bk_release(all[i].ref);
+ }
+ }
+ free(used);
+ free(found);
+ free(all);
}
n->hot = (m->query[0] && m->nfiltered) ? 0 : -1;
BKContext *ctx = bk_ctx(n);
diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.c
index a5376e9..416fa77 100644
--- a/kit/intern/kit_widgets.c
+++ b/kit/intern/kit_widgets.c
@@ -15,6 +15,7 @@
#include <stdlib.h>
#include <string.h>
+#include "blender/bk_blender.h"
#include "kit_intern.h"
/* -------------------------------------------------------------------- */
@@ -66,7 +67,10 @@ static void format_number(const BKNode *n, double v, char *buf, int size)
snprintf(buf, (size_t)size, "%d", (int)floor(v + 0.5));
}
else {
- snprintf(buf, (size_t)size, "%.*f", n->precision, v);
+ /* Blender's UI_calc_float_precision (blender/interface_utils.cc): more
+ * decimals for small values, so 0.00001 doesn't read "0.000" */
+ const int prec = n->precision > 6 ? n->precision : bk_calc_float_precision(n->precision, v);
+ snprintf(buf, (size_t)size, "%.*f", prec, v);
}
}
@@ -95,6 +99,16 @@ static void number_text(const BKNode *n, char *buf, int size)
}
}
+const char *bk_number_display(BKNode *n)
+{
+ static char buf[256];
+ if (n->cls != &bk_cls_number && n->cls != &bk_cls_slider) {
+ return NULL;
+ }
+ number_text(n, buf, sizeof(buf));
+ return buf;
+}
+
static const char *item_text(const BKNode *n, int i)
{
return (i >= 0 && i < n->items.n) ? n->items.v[i] : "";