HCIE-Rust v3.05 is a pixel-grade image editor built around an atomic project split that prevents automated agents from corrupting the engine while still allowing them to iterate on the graphical user interface. The active native GUI is the **Iced** workspace (`hcie-iced-app/`). The `hcie-egui-app/` workspace is legacy/frozen — do not modify it for new features.
1.**No direct GUI-to-engine bypass.** The GUI may not depend on or import `hcie-protocol`, `hcie-blend`, `hcie-document`, or any other engine crate directly. Use `hcie-engine-api` only.
2.**Engine API is the single entry point.** All engine operations go through `hcie-engine-api`. AI agents may not read or modify internal engine code.
3.**New feature = new file.** Prefer adding new files over editing existing ones; minimize changes to existing files.
4.**Engine library type.**`hcie-engine-api` is built as `crate-type = ["rlib", "staticlib"]`. The GUI links the `.a` / `.rlib` artifacts.
5.**Lock mechanism.** Engine crates are locked with `chmod 444` / directory `555` and owned by the `hcie-guard` user after build. Agents work only in the GUI layer.
The engine optimizations below directly determine brush performance on 4K / multi-layer documents. Removing, disabling, or bypassing these mechanisms as a "temporary workaround" is forbidden. Before touching them, verify benefit by running:
```bash
cargo test -p hcie-engine-api --test visual_regression
cargo test -p hcie-engine-api --test performance_stroke_4k -- --nocapture
```
| Mechanism | Location | What it does | Why it is protected |
| `active_stroke_mask` pooling | `hcie-engine-api/src/lib.rs` | Keeps an approximately 8MB mask buffer alive between strokes. | Re-allocating the mask per stroke causes allocation pauses during continuous painting. |
| `composite_scratch` pooling | `hcie-engine-api/src/lib.rs` | Keeps an approximately 33MB composite scratch buffer alive between strokes. | Allocating and freeing the composite buffer on every `render_composite_region` call is expensive. |
| `below_cache` + `below_cache_dirty` | `hcie-engine-api/src/lib.rs` | Composites all layers below the active layer once at stroke start and reuses the result while the lower layers remain unchanged. | Re-compositing all layers on every stroke event costs milliseconds per event on 4K canvases. |
| Conditional `effects_dirty` set | `hcie-engine-api/src/lib.rs` | Triggers the effects pass only for layers that actually have effects or styles. | Avoids unnecessary 33MB buffer clones and repeated `apply_layer_effects` calls on unaffected layers. |
| Tile cache over-clear removal | `hcie-engine-api/src/lib.rs` | Does not clear `tile_layers` and re-tile all layers on opacity / visibility / blend / parent / move changes when layer pixels themselves did not change. | Keeps the tile cache valid and avoids redundant dense-to-tile copies. |
| Small-region sequential compositing | `hcie-composite/src/tiled.rs` | Uses a sequential loop instead of `par_chunks_exact_mut` for small dirty regions. | Rayon thread spawn overhead dominates the work when the dirty region is small. |
| Effects cache reuse | `hcie-composite/src/tiled.rs` | Skips `apply_layer_effects` when `layer.effects_cache` is already populated. | Prevents re-running the full effect pipeline on every partial composite. |
| Incremental tile update | `hcie-tile/src/lib.rs` | Updates only the tiles that intersect the dirty rectangle and writes only the changed sub-rectangle when a tile already exists. | Avoids throwing away the whole 33MB dense-to-tile copy on every small dirty region. |
| Vector stroke anti-aliasing density | `hcie-vector/src/lib.rs` | Keeps circle-overlap density high enough along vector strokes and ellipses so shapes do not look jagged/pixelated. | Reducing step counts makes circles, stars, polygons and rounded rectangles visibly tırtıklı. |
| `iced::widget::Shader` partial upload | `hcie-iced-gui` (`shader_canvas.rs`) | Keeps persistent `wgpu::Texture` on GPU, updating only dirty tile bounds (8KB vs 33MB) via `queue.write_texture()`. | Crucial for keeping 4K document panning, zooming, and drawing at 100+ FPS; going back to `ImageHandle::from_rgba` drops frame rate to 1 FPS. |
| `RefCell` dirty bounds accumulator | `hcie-iced-gui` (`app.rs`, `canvas/mod.rs`) | Unions dirty bounds of all Elm event loop updates in the frame and consumes/resets them inside `view()`. | Prevents frame-drop race conditions where multi-event frames throw away dirty regions, causing missing tile gaps. |
| Viewport widget boundary mapping | `hcie-iced-gui` (`shader_canvas.rs`) | Sets custom wgpu render viewport matching the absolute layout bounds of the canvas widget. | Aligning wgpu NDC coordinates to layout coordinates is the only way drawing coordinates match mouse/pen position. |
| Nearest-Neighbor sampler filtering | `hcie-iced-gui` (`shader_canvas.rs`) | Sets magnification and minification filter modes to `wgpu::FilterMode::Nearest` on the GPU texture sampler. | Prevents linear interpolation sub-pixel sampling seams (black/transparent border lines) between 256x256 tiles. |
Two mechanisms together fix the recurring "default first document canvas is invisible until the tab title is clicked" bug. Removing either half makes the regression come back.
| Mechanism | Location | What it does | Why it is protected |
| Initial document active tab | `hcie-egui-app/crates/hcie-gui-egui/src/app/mod.rs` (`HcieApp::new`) | Sets `Document(0)` as the active dock tab on startup so egui_dock calls the canvas widget's `ui()` on the first frame. | Without this, the canvas widget is skipped and the composite texture is never created until the user clicks the tab title. |
| Extra repaint after new texture | `hcie-egui-app/crates/hcie-gui-egui/src/canvas/mod.rs` | Requests multiple repaints after `render_composition` creates a brand-new texture, because egui uploads GPU textures asynchronously. | A single repaint often leaves the canvas blank on the first frame; the second/third frame actually displays the texture. |
| `DrawingFinished` does NOT clear dirty flags | `hcie-egui-app/crates/hcie-gui-egui/src/app/mod.rs` | Leaves engine dirty flags intact so `render_composition` can upload the result on the next frame. | Calling `clear_dirty_flags()` inside `DrawingFinished` races with the next render pass and makes newly drawn vector shapes disappear. |
**AI AGENT WARNING:** Do not remove, shorten, or "optimize away" the startup active-tab setting, the egui multi-frame repaint requests, the `DrawingFinished` no-op, OR any of the `hcie-iced-gui` GPU-acceleration optimizations (RefCell union accumulator, viewport boundary mapping, Nearest filtering, or partial uploads). These look like minor details but they are the only things keeping the first canvas visible and Iced running smoothly at 100+ FPS. Every past removal has re-introduced regressions. If a change you are making touches any of these places, stop and verify with an actual app launch.
If a new feature conflicts with one of these mechanisms, extend the existing API by adding a new function or file rather than bypassing or duplicating the protected code.
## GUI Workspace Architecture (CRITICAL — AI Search Scope)
Only one GUI workspace exists: `hcie-iced-app/`. The GUI crates are `hcie-iced-gui/` and `iced-panel-*/`. The `hcie-egui-app/` workspace is legacy and frozen.
2. Then scan sibling engine crates (`../hcie-*/`).
3. Follow the `Cargo.toml` dependency chain; if a dependency lives in another workspace, scan that workspace too.
4. If a symbol name appears in two different modules (for example, `plugins/`), examine both.
## Error Isolation
Every crate can be built independently. A crash or failure in one crate does not cascade to the others. The GUI does not see engine code changes until the engine static library is rebuilt.
## Locked Files (agents may not write here)
-`hcie-protocol/src/*.rs`
-`hcie-color/src/*.rs`
-`hcie-blend/src/*.rs`
-`hcie-history/src/*.rs`
-`hcie-brush-engine/src/*.rs`
-`hcie-draw/src/*.rs`
-`hcie-composite/src/*.rs`
-`hcie-filter/src/*.rs`
-`hcie-selection/src/*.rs`
-`hcie-text/src/*.rs`
-`hcie-vector/src/*.rs`
-`hcie-tile/src/*.rs`
-`hcie-io/src/*.rs`
-`hcie-document/src/*.rs`
-`hcie-engine-api/src/*.rs`
-`hcie-ai/src/*.rs`
-`hcie-vision/src/*.rs`
-`hcie-fx/src/*.rs`
-`hcie-psd/src/*.rs`
-`hcie-kra/src/*.rs`
-`hcie-native/src/*.rs`
Use `unlock.sh <crate>` to temporarily open a crate, make the required change, then `lock.sh <crate>` to lock it again.
- **egui event:** `egui::Event::Screenshot { image, .. }` — delivers `egui::ColorImage` on next frame
- **image crate:** `image::save_buffer()` — writes raw RGBA bytes to PNG
---
# DOCUMENTATION
## Comprehensive Documentation Guidelines
For every function, method, struct, module, and file within the scope of work, add a detailed docstring/comment block at the very beginning. All documentation must be written in clear, professional English.
Each block must include:
* **Purpose:** A clear explanation of what this specific section, module, or function does.
* **Logic & Workflow:** The underlying operational logic, algorithm, or step-by-step mechanism it uses to achieve its goal.
* **Arguments & Returns (for functions/methods):** Explicit descriptions of input parameters (types and purposes) and return values.
* **Side Effects / Dependencies (if any):** Any global state changes, I/O operations, or external system dependencies.
# DEBUGGING
Only apply while debugging operations.
## Role and Objective
Analyze the provided code and improve it by adding detailed documentation and strategic debug logging.
## Strategic Debug Logging Guidelines
To accelerate root-cause analysis and system observability, insert comprehensive debug logs throughout the codebase.
* **Placement:** Place logs at critical execution boundaries:
* Entry and exit points of major functions (logging input parameters and final return values).
* Inside conditional branches (`if` / `else`) to track the exact execution path.
* Immediately before and after complex calculations, external API calls, or database operations.
* Inside catch/except blocks to capture full error contexts and stack traces.
* **Log Level:** Use the appropriate `DEBUG` or `TRACE` log level so these messages do not clutter production environments but can be fully enabled during troubleshooting.
* **Contextual Data:** Ensure log messages include relevant runtime data variables, identifiers, or state structures (serialized safely) to provide actionable context for debugging.
---
# Execution Output Requirements
* Preserve all existing business logic; do not alter the functionality of the code.
* Maintain the established code formatting style, indentation, and naming conventions of the source file.
* Return the fully updated code enclosed in appropriate markdown code fences.