darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Bake Darkly's version into the crate as the `DARKLY_VERSION` compile-time
/// env, read through `crate::VERSION`. The value is the latest git tag plus the
/// commit height since it (`git describe --tags --long`, e.g. `v0.3.0-1-gf0c3ea9`)
/// — the same v* tags the deploy pipeline (darkly-deploy/) releases from.
///
/// CANONICAL TWIN: frontend/vite.config.ts derives the frontend's version with
/// the identical command and the identical `"0.0.0-0-gunknown"` fallback. The
/// two build systems (Cargo vs. Vite) share no runtime, so this is a documented
/// DRY exception — if you change the command or fallback here, change it there.
///
/// Note: baking the commit SHA makes the crate's output non-deterministic across
/// commits (as is already true for the frontend bundle). Best-effort and never
/// panics — a tagless/git-less build just gets the fallback.
fn emit_darkly_version() {
    // No `--always`: on a tagless/shallow checkout we want this to FAIL so the
    // fallback kicks in, rather than emit a bare SHA that isn't `TAG-N-gSHA`.
    let version = Command::new("git")
        .args(["describe", "--tags", "--long"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "0.0.0-0-gunknown".to_string());

    println!("cargo:rustc-env=DARKLY_VERSION={version}");

    // Re-stamp when git state moves — best-effort and footgun-free: emit a hint
    // ONLY for a path that exists, because a hint pointing at a missing file
    // makes cargo treat it as perpetually-changed (rebuild every time). These
    // hints only reduce dev staleness; release correctness comes from the
    // deploy pipeline's fresh clone-at-tag, not from here. Tag-at-HEAD and
    // `git gc` repacks are imperfectly covered by design.
    let git_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../.git");
    let mut candidates = vec![
        git_dir.join("HEAD"),
        git_dir.join("packed-refs"),
        git_dir.join("refs/tags"),
    ];
    // If HEAD is a symref (`ref: refs/heads/x`), watch the loose branch ref too.
    if let Ok(head) = fs::read_to_string(git_dir.join("HEAD")) {
        if let Some(r) = head.trim().strip_prefix("ref: ") {
            candidates.push(git_dir.join(r));
        }
    }
    for path in candidates {
        if path.exists() {
            println!("cargo:rerun-if-changed={}", path.display());
        }
    }
}

fn main() {
    emit_darkly_version();

    let src = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("src");

    generate_grouped_registry(
        &src.join("engine/protocol/handlers"),
        "crate::engine::protocol::RequestRegistration",
    );

    generate_registry(&src.join("gpu/veils"), "crate::gpu::veil::VeilRegistration");

    generate_registry(&src.join("gpu/voids"), "crate::gpu::void::VoidRegistration");

    generate_registry(
        &src.join("gpu/filters"),
        "crate::gpu::filter::FilterPipelineRegistration",
    );

    generate_registry(&src.join("tools"), "crate::tool::ToolRegistration");

    generate_registry(
        &src.join("brush/nodes"),
        "crate::brush::BrushNodeRegistration",
    );

    generate_registry(
        &src.join("brush/stabilizers"),
        "crate::brush::stabilizer::StabilizerRegistration",
    );

    generate_registry(
        &src.join("config/sections"),
        "crate::config::schema::SchemaSection",
    );

    generate_registry(
        &src.join("document/filters"),
        "crate::document::filter::FilterEntityRegistration",
    );

    generate_registry(
        &src.join("document/layer_kinds"),
        "crate::document::layer_kind::LayerKindRegistration",
    );

    generate_registry(
        &src.join("gpu/blend_modes"),
        "crate::gpu::blend_mode::BlendModeRegistration",
    );

    generate_yaml_presets(&PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("presets"));

    generate_builtin_brushes(
        &PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("brushes"),
    );

    generate_texture_registry(
        &PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("resources/textures"),
    );
}

/// Scan a directory for .rs module files (excluding mod.rs) and generate
/// a mod.rs that re-exports all modules and provides a `registrations()`
/// function collecting each module's `register()` return value.
///
/// Convention: each module must export
///   `pub fn register() -> {registration_type}`
///
/// This is the Rust equivalent of Python's __init__.py auto-discovery:
/// drop a new .rs file in the directory, it gets picked up automatically.
fn generate_registry(dir: &Path, registration_type: &str) {
    let mut modules = Vec::new();

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "rs") {
                let stem = path.file_stem().unwrap().to_str().unwrap().to_string();
                if stem != "mod" {
                    modules.push(stem);
                }
            }
        }
    }

    modules.sort();

    // Extract just the struct name from the full path for use in fn signature.
    // e.g. "crate::gpu::filter::FilterPipelineRegistration" -> "FilterPipelineRegistration"
    let type_name = registration_type.rsplit("::").next().unwrap();

    let mut code = String::new();
    code.push_str("// @generated by build.rs — do not edit manually.\n");
    code.push_str("// To add a new module, create a .rs file in this directory\n");
    code.push_str(&format!(
        "// that exports `pub fn register() -> {registration_type}`.\n\n"
    ));

    for m in &modules {
        code.push_str(&format!("pub mod {m};\n"));
    }

    code.push_str(&format!("\nuse {registration_type};\n\n"));
    // Skip rustfmt on the generated body — layout varies across rustfmt
    // versions (single-element `vec![]` collapses on newer versions),
    // which would otherwise make CI's fmt check depend on the toolchain.
    code.push_str("#[rustfmt::skip]\n");
    code.push_str(&format!("pub fn registrations() -> Vec<{type_name}> {{\n"));
    code.push_str("    vec![\n");
    for m in &modules {
        code.push_str(&format!("        {m}::register(),\n"));
    }
    code.push_str("    ]\n");
    code.push_str("}\n");

    let mod_path = dir.join("mod.rs");
    let existing = fs::read_to_string(&mod_path).unwrap_or_default();
    if existing != code {
        fs::write(&mod_path, code).unwrap();
    }

    println!("cargo:rerun-if-changed={}", dir.display());
}

/// Like [`generate_registry`], but each module exports
///   `pub fn registrations() -> Vec<{registration_type}>`
/// (a *group* of registrations) rather than a single `register()`. The
/// generated `mod.rs` flattens every module's group into one aggregate
/// `registrations()`. Used by the request protocol, where related request
/// kinds are grouped per domain file (e.g. `layers.rs`, `selection.rs`)
/// instead of one file per kind.
fn generate_grouped_registry(dir: &Path, registration_type: &str) {
    let mut modules = Vec::new();

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "rs") {
                let stem = path.file_stem().unwrap().to_str().unwrap().to_string();
                if stem != "mod" {
                    modules.push(stem);
                }
            }
        }
    }

    modules.sort();

    let type_name = registration_type.rsplit("::").next().unwrap();

    let mut code = String::new();
    code.push_str("// @generated by build.rs — do not edit manually.\n");
    code.push_str("// To add request kinds, create or edit a domain .rs file in this\n");
    code.push_str(&format!(
        "// directory that exports `pub fn registrations() -> Vec<{registration_type}>`.\n\n"
    ));

    for m in &modules {
        code.push_str(&format!("pub mod {m};\n"));
    }

    code.push_str(&format!("\nuse {registration_type};\n\n"));
    code.push_str("#[rustfmt::skip]\n");
    code.push_str(&format!("pub fn registrations() -> Vec<{type_name}> {{\n"));
    code.push_str("    let mut all = Vec::new();\n");
    for m in &modules {
        code.push_str(&format!("    all.extend({m}::registrations());\n"));
    }
    code.push_str("    all\n");
    code.push_str("}\n");

    let mod_path = dir.join("mod.rs");
    let existing = fs::read_to_string(&mod_path).unwrap_or_default();
    if existing != code {
        fs::write(&mod_path, code).unwrap();
    }

    println!("cargo:rerun-if-changed={}", dir.display());
}

/// Scan `presets/*.yaml` and emit a generated Rust module to `OUT_DIR` with
/// one `include_str!` per YAML file plus a `defaults()` constant and an
/// `overlays()` function returning the editor-flavored overlays in
/// alphabetical order. `defaults.yaml` is required; the build panics if
/// it's missing. Every other `.yaml` becomes an equal-status overlay whose
/// display name is the file stem (Title Case).
fn generate_yaml_presets(dir: &Path) {
    let mut defaults_path: Option<PathBuf> = None;
    let mut overlays: Vec<(String, PathBuf)> = Vec::new();

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.extension().is_some_and(|e| e == "yaml" || e == "yml") {
                continue;
            }
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            if stem == "defaults" {
                defaults_path = Some(path);
            } else if !stem.is_empty() {
                overlays.push((stem, path));
            }
        }
    }

    let defaults_path =
        defaults_path.unwrap_or_else(|| panic!("presets/defaults.yaml is required"));

    // Display-name comes from the YAML's `name:` field; fall back to a
    // titlecased file stem if the YAML doesn't set one. Order alphabetically
    // (by stem) so no editor is privileged.
    overlays.sort_by(|a, b| a.0.cmp(&b.0));

    let mut display_names: Vec<(String, String)> = Vec::new();
    for (stem, path) in &overlays {
        let yaml = fs::read_to_string(path).unwrap_or_default();
        let name = parse_yaml_display_name(&yaml).unwrap_or_else(|| titlecase(stem));
        display_names.push((stem.clone(), name));
    }

    let mut code = String::new();
    code.push_str("// @generated by build.rs — do not edit manually.\n");
    code.push_str(
        "// To add a new editor overlay, drop `<name>.yaml` in `crates/darkly/presets/`.\n\n",
    );

    code.push_str(&format!(
        "pub const DEFAULTS_YAML: &str = include_str!({:?});\n\n",
        defaults_path.display().to_string()
    ));

    for (stem, path) in &overlays {
        code.push_str(&format!(
            "const {}_YAML: &str = include_str!({:?});\n",
            stem.to_uppercase().replace('-', "_"),
            path.display().to_string()
        ));
    }
    code.push('\n');

    // Equal-status overlay list: (display_name, yaml_source).
    code.push_str("pub const OVERLAYS: &[(&str, &str)] = &[\n");
    for (stem, name) in &display_names {
        code.push_str(&format!(
            "    ({:?}, {}_YAML),\n",
            name,
            stem.to_uppercase().replace('-', "_")
        ));
    }
    code.push_str("];\n\n");

    // BASE_SETTINGS_OPTIONS feeds the `app.baseSettings` enum schema.
    code.push_str("pub const BASE_SETTINGS_OPTIONS: &[(&str, &str)] = &[\n");
    for (_, name) in &display_names {
        code.push_str(&format!("    ({:?}, {:?}),\n", name, name));
    }
    code.push_str("];\n");

    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let out_path = PathBuf::from(out_dir).join("presets_gen.rs");
    fs::write(&out_path, code).unwrap();

    println!("cargo:rerun-if-changed={}", dir.display());
}

/// Pull the `name:` field out of a YAML preset file. Lightweight — we don't
/// want a full YAML parser in build.rs, and the field's expected to be a
/// top-level scalar on its own line.
fn parse_yaml_display_name(yaml: &str) -> Option<String> {
    for line in yaml.lines() {
        let trimmed = line.trim_start();
        if let Some(rest) = trimmed.strip_prefix("name:") {
            let v = rest.trim();
            // Strip quotes if the value is quoted.
            let v = v.trim_matches('"').trim_matches('\'');
            if !v.is_empty() {
                return Some(v.to_string());
            }
        }
    }
    None
}

fn titlecase(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().chain(chars).collect(),
        None => String::new(),
    }
}

/// Scan `brushes/*.yaml` and emit a generated module to `OUT_DIR` with
/// one `include_str!` per YAML file plus a `BUILTIN_BRUSHES_YAML`
/// constant listing each `(filename, yaml_source)` pair. Built-in
/// brushes are loaded by `crate::brush::builtin_brushes::all()` at
/// engine startup — adding a new one is "drop a `.yaml` file in the
/// directory" with no other code touched.
fn generate_builtin_brushes(dir: &Path) {
    let mut brushes: Vec<(String, PathBuf)> = Vec::new();
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.extension().is_some_and(|e| e == "yaml" || e == "yml") {
                continue;
            }
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            if stem.is_empty() {
                continue;
            }
            brushes.push((stem, path));
        }
    }
    brushes.sort_by(|a, b| a.0.cmp(&b.0));

    let mut code = String::new();
    code.push_str("// @generated by build.rs — do not edit manually.\n");
    code.push_str("// To add a new built-in brush, drop `<name>.yaml` in\n");
    code.push_str("// `crates/darkly/brushes/`. It is loaded automatically.\n\n");

    for (stem, path) in &brushes {
        code.push_str(&format!(
            "const {}_YAML: &str = include_str!({:?});\n",
            stem.to_uppercase().replace('-', "_"),
            path.display().to_string()
        ));
    }
    code.push('\n');

    code.push_str("pub const BUILTIN_BRUSHES_YAML: &[(&str, &str)] = &[\n");
    for (stem, _) in &brushes {
        let filename = format!("{stem}.yaml");
        code.push_str(&format!(
            "    ({:?}, {}_YAML),\n",
            filename,
            stem.to_uppercase().replace('-', "_"),
        ));
    }
    code.push_str("];\n");

    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let out_path = PathBuf::from(out_dir).join("builtin_brushes_gen.rs");
    fs::write(&out_path, code).unwrap();

    println!("cargo:rerun-if-changed={}", dir.display());
}

/// Scan `resources/textures/*.{jpg,jpeg,png,webp}` and emit a generated
/// Rust constant to `OUT_DIR` so [`crate::gpu::texture_registry`] can
/// register each image at engine init by its file basename (sans
/// extension). Mirrors the "drop a file in, it shows up" pattern that
/// `generate_registry` provides for code modules and that
/// `generate_yaml_presets` provides for editor overlays.
///
/// Dotfiles and non-image extensions are skipped — Krita autosaves
/// (`.foo.png-autosave.kra`) won't get registered as textures.
fn generate_texture_registry(dir: &Path) {
    let mut textures: Vec<(String, PathBuf)> = Vec::new();

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            // Skip dotfiles (`.foo.png-autosave.kra`, etc).
            if stem.is_empty() || stem.starts_with('.') {
                continue;
            }
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .map(|e| e.to_ascii_lowercase())
                .unwrap_or_default();
            if !matches!(ext.as_str(), "jpg" | "jpeg" | "png" | "webp") {
                continue;
            }
            textures.push((stem, path));
        }
    }

    // Stable order so the generated file is deterministic across builds.
    textures.sort_by(|a, b| a.0.cmp(&b.0));

    let mut code = String::new();
    code.push_str("// @generated by build.rs — do not edit manually.\n");
    code.push_str("// To add a new built-in texture, drop an image into\n");
    code.push_str("// `crates/darkly/resources/textures/`. It is registered\n");
    code.push_str("// under its file basename (sans extension).\n\n");
    // Emit paths relative to `CARGO_MANIFEST_DIR` so the generated
    // file is portable across checkouts — no local absolute paths
    // baked in. `include_bytes!` resolves `concat!(env!(...), "...")`
    // at compile time against whatever machine is building.
    code.push_str("pub const BUILTIN_TEXTURES: &[(&str, &[u8])] = &[\n");
    for (stem, path) in &textures {
        let file_name = path
            .file_name()
            .and_then(|s| s.to_str())
            .expect("texture path must have a file name");
        let rel = format!("/resources/textures/{file_name}");
        code.push_str(&format!(
            "    ({stem:?}, include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {rel:?}))),\n"
        ));
    }
    code.push_str("];\n");

    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let out_path = PathBuf::from(out_dir).join("textures_gen.rs");
    fs::write(&out_path, code).unwrap();

    println!("cargo:rerun-if-changed={}", dir.display());
}