### SPAIRS Example: Default Key Sorting Source: https://github.com/darktable-org/lua-scripts/wiki/spairs Demonstrates basic usage of spairs to iterate over a table sorted by its keys. ```lua HighScore = { Robin = 8, Jon = 10, Max = 11 } -- basic usage, just sort by the keys for k,v in spairs(HighScore) do print(k,v) end ``` -------------------------------- ### executable_path_widget Source: https://github.com/darktable-org/lua-scripts/wiki/executable_path_widget Creates a widget to get executable path preferences. It takes a table of executable names and builds a set of file selector widgets to get the path to each executable. The resulting widgets are wrapped in a box widget and returned. ```APIDOC ## executable_path_widget ### Description Creates a widget to get executable path preferences. It takes a table of executable names and builds a set of file selector widgets to get the path to each executable. The resulting widgets are wrapped in a box widget and returned. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **executables** (_table_) - A table of strings that are executable names. ### Return Value - **widget** (_widget_) - A widget containing a file selector widget for each executable. ``` -------------------------------- ### Clone Lua Scripts for Snap Packages Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md Use this command to clone the Lua scripts repository into the snap installation directory. Ensure git is installed. ```bash cd ~/snap/darktable/current git clone https://github.com/darktable-org/lua-scripts.git lua ``` -------------------------------- ### Example of Splitting a Path String Source: https://github.com/darktable-org/lua-scripts/wiki/split Illustrates the practical application of the split function by dividing a file path string using '/' as the separator. The expected output is a table containing the individual components of the path. ```lua split("/a/long/path/name/to/a/file.txt", "/") ``` -------------------------------- ### Example Usage of check_min_api_version Source: https://github.com/darktable-org/lua-scripts/wiki/check_min_api_version Checks if the API version is at least '5.0.0'. If not, an error is thrown. ```lua check_min_api_version("5.0.0") ``` -------------------------------- ### Clone Lua Scripts for Flatpak Packages Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md Use this command to clone the Lua scripts repository into the Flatpak configuration directory. Ensure git is installed. ```bash cd ~/.var/app/org.darktable.Darktable/config/darktable git clone https://github.com/darktable-org/lua-scripts.git lua ``` -------------------------------- ### Clone Lua Scripts for Windows Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md Use this command in a command prompt to clone the Lua scripts repository into the Windows local app data directory. Ensure git is installed. ```bash cd %LOCALAPPDATA%\darktable git clone https://github.com/darktable-org/lua-scripts.git lua ``` -------------------------------- ### Execute OS Command and Get Result Source: https://github.com/darktable-org/lua-scripts/wiki/external_command Use this function to pass a command string to the operating system for execution. It returns a number indicating success or failure. ```lua local dsys = require "lib/dtutils.system" local result = dsys.external_command(command) ``` -------------------------------- ### Update Lua Scripts for Snap Packages Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md Navigate to the Lua scripts directory within the snap installation and pull the latest changes using git. ```bash cd ~/snap/darktable/current/lua git pull ``` -------------------------------- ### Clone Lua Scripts for Linux and MacOS Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md Use this command to clone the Lua scripts repository into the standard configuration directory for Linux and macOS. Ensure git is installed. ```bash cd ~/.config/darktable/ git clone https://github.com/darktable-org/lua-scripts.git lua ``` -------------------------------- ### Enable Script Manager for Snap Packages Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md This command creates or overwrites the luarc file to enable the script manager for snap installations. Ensure the directory exists. ```bash echo 'require "tools/script_manager"' > ~/snap/darktable/current/luarc ``` -------------------------------- ### Update and Debug Lua Scripts Source: https://context7.com/darktable-org/lua-scripts/llms.txt Update all installed Lua scripts by pulling from the repository and run darktable with Lua logging enabled for debugging purposes. ```bash # Update all scripts cd ~/.config/darktable/lua && git pull # Debug — run darktable with Lua logging darktable -d lua # Linux /Applications/darktable.app/Contents/MacOS/darktable -d lua # macOS "C:\Program Files\darktable\bin\darktable" -d lua > log.txt # Windows ``` -------------------------------- ### Get or Set Log Output Engine Source: https://github.com/darktable-org/lua-scripts/wiki/engine Use this function to retrieve the current output engine for a specific log level or to set a new output engine. If no function is provided, the current engine is returned. Ensure the log level is one of the predefined constants. ```lua local log = require "lib/dtutils.log" result = log.engine(level, ...) ``` -------------------------------- ### SPAIRS Example: Custom Score Sorting (Descending) Source: https://github.com/darktable-org/lua-scripts/wiki/spairs Demonstrates using a custom comparison function with spairs to sort table entries by score in descending order. ```lua HighScore = { Robin = 8, Jon = 10, Max = 11 } -- this uses an custom sorting function ordering by score descending for k,v in spairs(HighScore, function(t,a,b) return t[b] < t[a] end) do print(k,v) end ``` -------------------------------- ### Enable Script Manager for Flatpak Packages Source: https://github.com/darktable-org/lua-scripts/blob/master/README.md This command creates or overwrites the luarc file to enable the script manager for Flatpak installations. Ensure the directory exists. ```bash echo 'require "tools/script_manager"' > ~/.var/app/org.darktable.Darktable/config/darktable/luarc ``` -------------------------------- ### Get Executable Path Preference in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/get_executable_path_preference Use this function to retrieve the configured path for an executable. Ensure the executable name is provided as a string without extensions. ```lua local df = require "lib/dtutils.file" local result = df.get_executable_path_preference(executable) ``` -------------------------------- ### Create Directory with Path Source: https://github.com/darktable-org/lua-scripts/wiki/mkdir Use this function to create a directory at the specified path. Parent directories will be created if they don't exist. The function returns the path of the created directory. ```lua local df = require "lib/dtutils.file" df.mkdir(path) ``` -------------------------------- ### log.engine Source: https://github.com/darktable-org/lua-scripts/wiki/engine Gets or sets the output engine for a specified log level. If no function is provided, it returns the current engine. ```APIDOC ## log.engine ### Description Gets or sets the output engine for a specified log level. If no function is provided, it returns the current engine. ### Parameters #### Path Parameters - **level** (table) - Required - The log level to get or set the engine for. Possible values include log.debug, log.info, log.warn, log.error, log.success, log.always, log.screen, log.critical. - **...** (function) - Optional - The output function to set as the engine. Possible values include dt.print, dt.print_error, dt.print_log, print. If not provided, the current engine for the specified log level is returned. ### Return Value - **result** (function) - The current output engine for the specified log level. ``` -------------------------------- ### mkdir Source: https://github.com/darktable-org/lua-scripts/wiki/file Creates directories if they do not already exist. ```APIDOC ## mkdir ### Description Creates the directory(ies) if they do not already exist. ### Usage ```lua local df = require "lib/dtutils.file" df.mkdir(directory_path) ``` ### Parameters #### Path Parameters - **directory_path** (string) - Required - The path of the directory to create. ``` -------------------------------- ### Creating and Removing Directories with dtutils.file Source: https://context7.com/darktable-org/lua-scripts/llms.txt Utility functions for creating a new directory or removing an existing empty directory. ```lua local df = require "lib/dtutils.file" -- 7. Create / remove directories df.mkdir("/home/user/new_folder") df.rmdir("/home/user/old_folder") ``` -------------------------------- ### Get Filename Basename in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/get_basename Use this function to retrieve the filename without its path or extension. It requires importing the dtutils.file module. ```lua local df = require "lib/dtutils.file" local result = df.get_basename(filepath) ``` -------------------------------- ### Finding Executable Binaries with dtutils.file Source: https://context7.com/darktable-org/lua-scripts/llms.txt This utility searches for an executable binary, checking preferences, the system's PATH, and performing a full OS search. It returns the sanitized path or false if not found. Use this before attempting to execute external commands. ```lua local df = require "lib/dtutils.file" -- 3. Find an executable (checks prefs, PATH, then full OS search) -- Returns sanitized path string, or false if not found local gimp = df.check_if_bin_exists("gimp") if gimp then dtsys.external_command(gimp .. " " .. df.sanitize_filename(img_path)) else dt.print("GIMP not found. Install it or set path in executable_manager.") end ``` -------------------------------- ### Create Executable Path Widget Source: https://github.com/darktable-org/lua-scripts/wiki/executable_path_widget Use this snippet to create a widget that allows users to select paths for specified executables. Ensure the 'dtutils.file' module is required. ```lua local df = require "lib/dtutils.file" local widget = df.executable_path_widget(executables) ``` -------------------------------- ### Get Filename from Filepath in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/get_filename Use this function to strip the directory path and retrieve only the filename and its extension. It requires importing the dtutils.file module. ```lua local df = require "lib/dtutils.file" local result = df.get_filename(filepath) ``` -------------------------------- ### Using dtutils.log for Multi-level Logging Source: https://context7.com/darktable-org/lua-scripts/llms.txt This snippet demonstrates how to initialize and use the dtutils.log library for various logging levels. It covers setting log levels, emitting messages, and handling scoped log-level changes. Ensure the library is required before use. ```lua local log = require "lib/dtutils.log" -- Read/set the current log level local saved = log.log_level() -- returns current level table log.log_level(log.debug) -- enable all messages down to debug -- Emit messages at different levels log.msg(log.debug, "entering export loop") log.msg(log.info, "processing image:", img.filename) log.msg(log.warn, "executable not in PATH, using preference") log.msg(log.error, "file not found:", filepath) log.msg(log.success, "exported", count, "images successfully") log.msg(log.screen, "Export complete!") -- appears in darktable's on-screen message area log.msg(log.critical,"Fatal: cannot open database") -- goes to stdout/stderr console -- In a callback, name cannot be auto-detected; include a tag manually: local function my_callback(event, image) log.msg(log.debug, "my_callback: image id =", image.id) end -- Scoped log-level change for a noisy code section local old_level = log.log_level() log.log_level(log.warn) -- suppress debug/info inside library calls local result = some_library_function() log.log_level(old_level) -- restore -- Inspect caller info (used internally) local info_str = log.caller(3) -- e.g. "myscript.lua: export_images: 47:" ``` -------------------------------- ### Get Directory Path from File Path Source: https://github.com/darktable-org/lua-scripts/wiki/get_path Use this function to obtain the directory portion of a file path. It requires importing the dtutils.file module. ```lua local df = require "lib/dtutils.file" local result = df.get_path(filepath) ``` -------------------------------- ### launch_default_app Source: https://github.com/darktable-org/lua-scripts/wiki/launch_default_app Opens a specified file in the default application associated with its file type on the user's system. ```APIDOC ## launch_default_app ### Description Allows opening a file in the application that is assigned as default for that filetype in the user's system. ### Method Signature dsys.launch_default_app(path) ### Parameters #### Path Parameters - **path** (string) - Required - A file path to be opened. ``` -------------------------------- ### mkdir Source: https://github.com/darktable-org/lua-scripts/wiki/mkdir Creates the specified directory path, including parent directories if they don't exist. ```APIDOC ## mkdir ### Description Creates the specified directory path, including parent directories if they don't exist. ### Method ```lua df.mkdir(path) ``` ### Parameters #### Path Parameters - **path** (string) - Required - A directory path to create. ### Return Value - **path** (string) - The created directory path. ``` -------------------------------- ### Register and Read Preferences Source: https://context7.com/darktable-org/lua-scripts/llms.txt This script shows how to register persistent preferences of various types (string, bool, integer, float, file, directory, enum) and then read them back using the Preferences API. ```lua local dt = require "darktable" -- Register preferences of every supported type dt.preferences.register("my_script", "output_dir", "directory", "Output directory", "Where exported files are saved", "") dt.preferences.register("my_script", "quality", "integer", "JPEG quality", "Export quality (1-100)", 90, 1, 100) dt.preferences.register("my_script", "sharpen", "bool", "Sharpen on export", "Apply output sharpening", false) dt.preferences.register("my_script", "format", "enum", "Export format", "File format for export", "JPEG", "JPEG", "TIFF", "PNG") dt.preferences.register("my_script", "suffix", "string", "Filename suffix", "Appended to exported filenames", "_edited") -- Read preferences back local out_dir = dt.preferences.read("my_script", "output_dir", "directory") local quality = dt.preferences.read("my_script", "quality", "integer") local sharpen = dt.preferences.read("my_script", "sharpen", "bool") local fmt = dt.preferences.read("my_script", "format", "enum") local suffix = dt.preferences.read("my_script", "suffix", "string") dt.print_log(string.format("Exporting to %s as %s at quality %d", out_dir, fmt, quality)) ``` -------------------------------- ### Execute OS Commands with dtutils.system Source: https://context7.com/darktable-org/lua-scripts/llms.txt Wraps OS command execution in a cross-platform way. On Linux/macOS it calls `dt.control.execute()`, while on Windows it writes a temporary `.bat` file to work around quoting limitations. ```lua local dtsys = require "lib/dtutils.system" local df = require "lib/dtutils.file" -- 1. Execute an external command (cross-platform) local exiftool = df.check_if_bin_exists("exiftool") if exiftool then local result = dtsys.external_command( exiftool .. " -b -JpgFromRaw " .. df.sanitize_filename("/home/user/photos/shot.cr2") .. " > " .. df.sanitize_filename("/tmp/shot.jpg") ) if result == 0 then dt.print_log("JPEG extracted successfully") else dt.print("exiftool failed with code: " .. tostring(result)) end end ``` ```lua -- 2. Windows-only: directly call the batch-file wrapper -- (Usually called indirectly via external_command on Windows) if dt.configuration.running_os == "windows" then local rc = dtsys.windows_command('"C:\\Program Files\\gimp\\bin\\gimp-2.10.exe" "C:\\photos\\shot.tif"') end ``` -------------------------------- ### Import and Use dtutils.split Function Source: https://github.com/darktable-org/lua-scripts/wiki/split Demonstrates how to import the dtutils library and use the split function to divide a string. The 'str' argument is the string to split, and 'pat' is the pattern used as a delimiter. ```lua local du = require "lib/dtutils" local result = du.split(str, pat) ``` -------------------------------- ### check_if_bin_exists Source: https://github.com/darktable-org/lua-scripts/wiki/check_if_bin_exists Checks if a specified executable binary exists on the system. It first looks for a registered preference, then verifies the file's presence. On Linux, it uses the 'which' command if no preference is set. Returns the sanitized path if found, otherwise returns false. ```APIDOC ## check_if_bin_exists ### Description Checks to see if the specified binary exists. It first checks if a preference for the binary has been registered and uses that if found. The presence of the file is verified, then quoted and returned. If no preference is specified and the operating system is linux then the which command is used to check for a binary in the path. If found that path is returned. If no binary is found, false is returned. ### Parameters #### Path Parameters - **bin** (string) - Required - The binary to check for. ### Return Value - **result** (string | false) - The sanitized path of the binary, or false if not found. ``` -------------------------------- ### Get Filetype from Filepath Source: https://github.com/darktable-org/lua-scripts/wiki/get_filetype Import the `dtutils.file` module and use the `get_filetype` function to extract the filetype from a provided filepath string. The function returns the filetype as a string. ```lua local df = require "lib/dtutils.file" local result = df.get_filetype(filepath) ``` -------------------------------- ### prequire Source: https://github.com/darktable-org/lua-scripts/wiki/dtutils A safe and protected version of Lua's `require` function. ```APIDOC ## prequire ### Description A protected Lua require function that handles errors gracefully. ### Parameters #### Arguments * `package_name` (string) - The name of the package to require. ### Returns * `object` or `nil` - The loaded module if successful, otherwise nil. ### Usage ```lua local module = du.prequire('module_name') ``` ``` -------------------------------- ### check_os Source: https://github.com/darktable-org/lua-scripts/wiki/dtutils Verifies that the current operating system is supported by the script. ```APIDOC ## check_os ### Description Checks that the operating system is supported. ### Usage ```lua du.check_os() ``` ``` -------------------------------- ### Copying Files with dtutils.file Source: https://context7.com/darktable-org/lua-scripts/llms.txt Copies a file from a source path to a destination path. Returns true on success, or nil on failure. ```lua local df = require "lib/dtutils.file" -- 5. Copy a file local ok = df.file_copy("/tmp/export.jpg", "/home/user/archive/export.jpg") -- ok == true on success, nil on failure ``` -------------------------------- ### Get Current Log Level Source: https://github.com/darktable-org/lua-scripts/wiki/log_level Call log.log_level() without arguments to retrieve the current logging level. The return value will be one of log.debug, log.info, log.warn, log.error, or log.success. ```lua log.log_level() ``` -------------------------------- ### log.log_level Source: https://github.com/darktable-org/lua-scripts/wiki/log_level Gets or sets the logging level. When called with no arguments, it returns the current log level. When called with a log level constant (e.g., log.info), it sets the log level and returns the new level. ```APIDOC ## log.log_level ### Description Gets or sets the logging level. When called with no arguments, it returns the current log level. When called with a log level constant (e.g., log.info), it sets the log level and returns the new level. All log levels greater than or equal in value will be enabled, and any levels of lesser value will be disabled. ### Method Lua Function Call ### Parameters #### Arguments - **log_level_constant** (log.debug | log.info | log.warn | log.error | log.success) - Optional - The desired log level to set. If not provided, the current log level is returned. ### Return Value - **result** (log.debug | log.info | log.warn | log.error | log.success) - The current or newly set log level. ### Example ```lua -- Get current log level local current_level = log.log_level() -- Set log level to info local new_level = log.log_level(log.info) ``` ``` -------------------------------- ### Get Caller Information in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/caller Use this function to retrieve the name and line number of the calling routine. Provide a numerical level to specify how many stack frames to ascend. Returns 'callback: ' if the caller cannot be identified. ```lua local log = require "lib/dtutils.log" result = log.caller(level) ``` -------------------------------- ### executable_path_widget Source: https://github.com/darktable-org/lua-scripts/wiki/file Creates a widget for selecting an executable path in preferences. ```APIDOC ## executable_path_widget ### Description Creates a widget to get executable path preferences. ### Usage ```lua local df = require "lib/dtutils.file" df.executable_path_widget(preference_name) ``` ### Parameters #### Path Parameters - **preference_name** (string) - Required - The name of the preference to associate with the widget. ``` -------------------------------- ### Require and Use check_min_api_version Source: https://github.com/darktable-org/lua-scripts/wiki/check_min_api_version Requires the dtutils library and calls check_min_api_version with the minimum API version and script name. ```lua local du = require "lib/dtutils" local result = du.check_min_api_version(min_api, script_name) ``` -------------------------------- ### Open File in Default Application (Lua) Source: https://github.com/darktable-org/lua-scripts/wiki/launch_default_app Use this function to open a specified file using the system's default application for that file type. Ensure the 'dtutils.file' library is required. ```lua local dsys = require "lib/dtutils.file" result = dsys.launch_default_app(path) ``` -------------------------------- ### Enable Info Logging Source: https://github.com/darktable-org/lua-scripts/wiki/log Enable info level logging to capture informational messages. This can be used to track the general flow of the script. ```lua log.log_level(info) ``` -------------------------------- ### Basic MSG Log Message Usage Source: https://github.com/darktable-org/lua-scripts/wiki/msg Import the log module and call log.msg with a level and the message string(s). The level determines the type and visibility of the message. ```lua local log = require "lib/log" log.msg(level, ...) ``` -------------------------------- ### Check if Binary Exists in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/check_if_bin_exists Use this function to check if a binary is available. It first checks for registered preferences and then uses the 'which' command on Linux if no preference is found. Returns the sanitized path or false. ```lua local df = require "lib/dtutils.file" local result = df.check_if_bin_exists(bin) ``` -------------------------------- ### Safe Module Loading and Iteration with dtutils Source: https://context7.com/darktable-org/lua-scripts/llms.txt Employ `prequire` for safe module loading, returning success status and the module or an error message. `spairs` provides sorted iteration over table elements, with custom sorting options available. ```lua local dt = require "darktable" local du = require "lib/dtutils" -- 6. Protected require: returns (true, module) or (false, errmsg) local ok, df = du.prequire("lib/dtutils.file") if not ok then dt.print("Failed to load dtutils.file: " .. df) end -- 7. Sorted pairs iterator local scores = { Alice = 95, Bob = 87, Carol = 92 } for name, score in du.spairs(scores) do dt.print_log(name .. " = " .. score) end -- Output (alphabetical): Alice=95 Bob=87 Carol=92 -- Custom sort (descending by score) for name, score in du.spairs(scores, function(t, a, b) return t[b] < t[a] end) do dt.print_log(name .. " = " .. score) end ``` -------------------------------- ### dtutils - Core Utility Library Source: https://context7.com/darktable-org/lua-scripts/llms.txt The top-level `dtutils` library offers API version checking, string splitting/joining, safe require, sorted iteration, OS detection, image look-up, UUID generation, and deprecation warnings. Load it with `require "lib/dtutils"`. ```APIDOC ## dtutils - Core Utility Library ### Description The `dtutils` library provides essential utilities for Darktable Lua scripts, including version checking, string manipulation, safe module loading, OS detection, image look-up, UUID generation, and deprecation warnings. ### Usage Load the library using `require "lib/dtutils"`. ### Functions 1. **`du.check_min_api_version(version, script_name)`** Enforces a minimum Lua API version. Stops loading if the condition is not met. - `version` (string): The minimum required API version. - `script_name` (string): The name of the script for error messages. 2. **`du.check_max_api_version(version, script_name)`** Enforces a maximum Lua API version. Stops loading if the API was removed. - `version` (string): The maximum allowed API version. - `script_name` (string): The name of the script for error messages. 3. **`du.compare_api_versions(v1, v2)`** Compares two semver-style version strings. - `v1` (string): The first version string. - `v2` (string): The second version string. - Returns: `1` if v1 > v2, `-1` if v1 < v2, `0` if equal. 4. **`du.split(str, pattern)`** Splits a string on a separator pattern. - `str` (string): The string to split. - `pattern` (string): The separator pattern. - Returns: A table of string parts. 5. **`du.join(tbl, separator)`** Joins a table of strings with a separator. - `tbl` (table): The table of strings to join. - `separator` (string): The separator to use. - Returns: The joined string. 6. **`du.prequire(module_name)`** Protected require: safely loads a module. - `module_name` (string): The name of the module to require. - Returns: `(true, module)` on success, `(false, errmsg)` on failure. 7. **`du.spairs(tbl, order_func)`** Provides a sorted pairs iterator for a table. - `tbl` (table): The table to iterate over. - `order_func` (function, optional): A custom sorting function. - Returns: An iterator yielding key-value pairs in sorted order. 8. **`du.check_os(supported_os_list)`** Checks if the current operating system is in the provided list. - `supported_os_list` (table): A table of supported OS names (e.g., {"linux", "macos"}). - Returns: `true` if the OS is supported, `false` otherwise. 9. **`du.find_image_by_id(image_id)`** Looks up an image in the database by its integer ID. - `image_id` (number): The integer ID of the image. - Returns: The image object if found, otherwise `nil`. 10. **`du.gen_uuid(case)`** Generates a UUID string. - `case` (string, optional): "lower" or "upper" for the case of the UUID. Defaults to lower. - Returns: A UUID string. 11. **`du.deprecated(script_path, deprecation_info)`** Emits a deprecation warning. - `script_path` (string): The path or name of the deprecated script. - `deprecation_info` (string): Information about the deprecation (e.g., release version). ``` -------------------------------- ### OS Check, Image Lookup, UUID Generation, and Deprecation Warnings in dtutils Source: https://context7.com/darktable-org/lua-scripts/llms.txt Verify OS compatibility using `check_os`. `find_image_by_id` retrieves image data, `gen_uuid` creates unique identifiers, and `deprecated` emits warnings for outdated functions. ```lua local dt = require "darktable" local du = require "lib/dtutils" -- 8. Check current OS against a list of supported systems if not du.check_os({ "linux", "macos" }) then dt.print("This script only runs on Linux and macOS") return end -- 9. Look up an image in the database by its integer ID local img = du.find_image_by_id(42) if img then dt.print_log("Found: " .. tostring(img)) end -- 10. Generate a UUID string local uuid_lower = du.gen_uuid("lower") -- "3f2504e0-4f89-4a3b-a5c7-..." local uuid_upper = du.gen_uuid("upper") -- "3F2504E0-4F89-4A3B-A5C7-"... -- 11. Emit a deprecation warning du.deprecated("contrib/old_script", "darktable release 5.0") -- Prints: WARNING: contrib/old_script is deprecated and will be removed in darktable release 5.0 ``` -------------------------------- ### Require DTUTILS.SYSTEM Library Source: https://github.com/darktable-org/lua-scripts/wiki/system Include the DTUTILS.SYSTEM library in your Lua script to access its system utility functions. This is the standard way to import the library. ```lua local dtsys = require "lib/dtutils.system" ``` -------------------------------- ### Moving Files with dtutils.file Source: https://context7.com/darktable-org/lua-scripts/llms.txt Moves a file from a source path to a destination path. Returns true on success, or nil on failure. ```lua local df = require "lib/dtutils.file" -- 6. Move a file local ok = df.file_move("/tmp/export.jpg", "/home/user/archive/export.jpg") ``` -------------------------------- ### Import and Use log_level Function Source: https://github.com/darktable-org/lua-scripts/wiki/log_level Import the log module and call the log_level function. If no arguments are provided, it returns the current log level. Otherwise, it sets the log level. ```lua local log = require "lib/log" local result = log.log_level(...) ``` -------------------------------- ### Load Lua Module Safely with prequire Source: https://github.com/darktable-org/lua-scripts/wiki/prequire Use prequire to load a Lua module. It returns a status and the loaded library or an error message. The module name should not include the '.lua' extension. ```lua local du = require "lib/dtutils" local status, lib = du.prequire(req_name) ``` ```lua local status, lib = prequire("lib/dtutils.file") ``` -------------------------------- ### Managing Executable Path Preferences with dtutils.file Source: https://context7.com/darktable-org/lua-scripts/llms.txt Set and retrieve custom paths for executables. This is useful for ensuring your script can find specific tools regardless of their system-wide location. ```lua local df = require "lib/dtutils.file" -- 4. Manage stored executable path preferences df.set_executable_path_preference("ffmpeg", "/usr/local/bin/ffmpeg") local ffmpeg_path = df.get_executable_path_preference("ffmpeg") -- Returns: "/usr/local/bin/ffmpeg" ``` -------------------------------- ### API Version Checks and String Utilities in dtutils Source: https://context7.com/darktable-org/lua-scripts/llms.txt Use `check_min_api_version` and `check_max_api_version` to enforce compatibility. `split` and `join` provide string manipulation, while `compare_api_versions` aids in version comparisons. ```lua local dt = require "darktable" local du = require "lib/dtutils" -- 1. Enforce a minimum Lua API version (stops loading if not met) du.check_min_api_version("7.0.0", "my_script") -- 2. Enforce a maximum Lua API version (stops loading if API was removed) du.check_max_api_version("9.0.0", "my_script") -- 3. Compare two semver-style version strings -- Returns: 1 if v1 > v2, -1 if v1 < v2, 0 if equal local cmp = du.compare_api_versions("5.0.0", "5.1.0") -- cmp == -1 -- 4. Split a string on a separator pattern local parts = du.split("/home/user/photos/shot.cr2", "/") -- parts == { "home", "user", "photos", "shot.cr2" } -- 5. Join a table of strings with a separator local path = du.join({ "home", "user", "photos" }, "/") -- path == "home/user/photos" ``` -------------------------------- ### Split Filepath Utility Source: https://github.com/darktable-org/lua-scripts/wiki/split_filepath Use this function to break down a file path string into its directory, filename, base name, and extension. Requires importing the dtutils.file module. ```lua local df = require "lib/dtutils.file" local result = df.split_filepath(filepath) ``` -------------------------------- ### Register Darktable Events and Shortcuts Source: https://context7.com/darktable-org/lua-scripts/llms.txt Register custom event listeners for image import and define keyboard shortcuts. Includes adding GUI actions and cleanup functions. ```lua local dt = require "darktable" -- Trigger on every image imported into the database dt.register_event("my_script", "post-import-image", function(event, image) dt.print_log("Imported: " .. image.filename) -- Auto-tag newly imported images local tag = dt.tags.create("auto-imported") dt.tags.attach(tag, image) end ) -- Register a keyboard shortcut (assignable in Preferences > Shortcuts > Lua) dt.register_event("my_script", "shortcut", function(event, shortcut) local images = dt.gui.action_images dt.print(string.format(_("Processing %d images"), #images)) for _, img in ipairs(images) do dt.print_log("shortcut fired on: " .. img.filename) end end, _("run my script on selection") ) -- Add a button to the lighttable 'selected images' panel dt.gui.libs.image.register_action( "my_script", _("process selected"), function(event, images) for _, img in ipairs(images) do dt.print_log("panel button: " .. img.filename) end end, _("run my script processing on selected images") ) -- Clean up events when the script is unloaded local function destroy() dt.destroy_event("my_script", "shortcut") dt.destroy_event("my_script", "post-import-image") dt.gui.libs.image.destroy_action("my_script") end ``` -------------------------------- ### dtutils.system — OS command execution Source: https://context7.com/darktable-org/lua-scripts/llms.txt Provides cross-platform OS command execution, wrapping native commands or using temporary batch files on Windows to handle quoting limitations. ```APIDOC ## `dtutils.system` — OS command execution ### Description Wraps OS command execution in a cross-platform way. On Linux/macOS, it calls `dt.control.execute()`. On Windows, it writes a temporary `.bat` file to work around quoting limitations. ### Functions - **`external_command(command_string)`**: Executes an external command string in a cross-platform manner. - **`windows_command(command_string)`**: (Windows-only) Directly calls the batch-file wrapper. Usually called indirectly via `external_command` on Windows. ### Example Usage ```lua local dtsys = require "lib/dtutils.system" local df = require "lib/dtutils.file" -- Execute an external command (cross-platform) local exiftool = df.check_if_bin_exists("exiftool") if exiftool then local result = dtsys.external_command( exiftool .. " -b -JpgFromRaw " .. df.sanitize_filename("/home/user/photos/shot.cr2") .. " > " .. df.sanitize_filename("/tmp/shot.jpg") ) if result == 0 then dt.print_log("JPEG extracted successfully") else dt.print("exiftool failed with code: " .. tostring(result)) end end -- Windows-only: directly call the batch-file wrapper if dt.configuration.running_os == "windows" then local rc = dtsys.windows_command('"C:\\Program Files\\gimp\\bin\\gimp-2.10.exe" "C:\\photos\\shot.tif"') end ``` ``` -------------------------------- ### Check Operating System Support in Lua Source: https://github.com/darktable-org/lua-scripts/wiki/check_os Use this function to ensure a script runs only on supported operating systems. It requires the dtutils library. ```lua local du = require "lib/dtutils" local result = du.check_os(operating_systems) ``` ```lua local du = require "lib/dtutils" if du.check_os({"windows"}) then -- run the script else dt.print("Script