# HCIE-Rust v3 — Teknik Referans ## Build Sırası ``` Katman 1: DATA - crates/hcie-protocol - crates/hcie-color Katman 2: MOTOR - crates/hcie-blend - crates/hcie-history - crates/hcie-brush-engine - crates/hcie-draw - crates/hcie-composite - crates/hcie-filter - crates/hcie-selection - crates/hcie-text - crates/hcie-vector - crates/hcie-tile - crates/hcie-io Katman 3: DOCUMENT - crates/hcie-document Katman 4: ENGINE API - crates/hcie-engine-api (staticlib + rlib) Katman 5: AI / VISION - crates/hcie-ai - crates/hcie-vision Katman 6: GUI (Açık Katman) - hcie-egui-app/crates/hcie-gui-egui/ (egui native uygulama) ``` ## Katman 1: DATA (Kilitli) ### hcie-protocol - Sadece struct, enum, const tanımları. - Logic yok. Method yok (getter/setter hariç). - `serde::{Serialize, Deserialize}` tüm tiplerde. ```rust pub struct Layer { ... } pub enum BlendMode { ... } pub enum VectorShape { ... } pub enum LayerType { ... } pub enum LayerData { ... } ``` ### hcie-color - Sadece pure fonksiyonlar. - No state, no heap allocation (runtime'ta). ```rust pub fn gamma_encode(linear: f32) -> f32; pub fn gamma_decode(srgb: f32) -> f32; pub fn srgb_to_linear(rgb: [u8; 3]) -> [f32; 3]; pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32); pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32); ``` ## Katman 2: MOTOR (Kilitli) ### hcie-blend - `blend_pixels(dst, src, mode, opacity)` — tek fonksiyon, tüm modlar. - 30+ match arm. Her mode ayrı inline helper. - `hcie-protocol::BlendMode` ve `hcie-color` bağımlılığı. ### hcie-history - `UndoableAction` trait'i. - `HistoryManager` generic struct'ı. - Closure-tabanlı. Tip-independent. - NO C FFI. ```rust pub trait UndoableAction: Send { fn undo(&mut self); fn redo(&mut self); fn description(&self) -> String; } ``` ### hcie-brush-engine - Procedural brush tip üretimi. - Pressure curve mapping. - Spacing + scatter + jitter matematiği. - Output: brush stamp (alpha mask olarak). ### hcie-draw - Rasterize: line, circle, brush stroke, flood fill. - `hcie-blend` ile piksel yazma. - `hcie-brush-engine` ile stamp sampling. ### hcie-composite - Layer'ları birleştirip RGBA output. - Tüm blend modları destekler. - Output: `Vec` (RGBA, premultiplied veya straight, belgelenmeli). ### hcie-filter - Her filter ayrı fonksiyon. - Box Blur, Gaussian Blur, Motion Blur, Mosaic, Oil Paint, Crystallize, Pinch, Twirl, Unsharp Mask, Brightness/Contrast, HSL, Border. - Input/output: `&[u8]` and `&mut [u8]` with known w/h. ### hcie-selection - Mask oluşturma: rect, ellipse, lasso, polygon. - Ops: grow, shrink, feather, invert. - Output: `Vec` mask 0-255. ### hcie-text - `fontdue` ile glyph rasterization. - Layout: left, center, right alignment. - Output: positioned glyphs + alpha mask'lar. ### hcie-vector - VectorShape render (stroke + fill). - Edit handle'ları (8 nokta + rotate). - Stroke path rasterization. ### hcie-tile - Sparse tile-based layer storage. - 256x256 sabit boyutlu tile yapısı (`TILE_SIZE = 256`). - `TiledLayer` ve `Tile` struct'ları ile sadece görünür bölgeleri bellekte tutarak heap allocation minimize edilir. - Verimli byte-tabanlı custom serde serialization/deserialization desteği. ### hcie-io - PNG, JPG, WebP, BMP, GIF → `hcie-protocol::Layer` - PSD import (layers with blend mode) - KRA import (zip-based, merged image) - HCIE native save/load (serde + bincode/ron) ## Katman 3: DOCUMENT (Kilitli) ### hcie-document - `Document` struct: layers list, active_layer, canvas dims, zoom, dirty - `HistoryManager>` (tip-independent, closure-based) - `add_layer()`, `delete_layer()`, `undo()`, `redo()`, `mark_dirty()`, `is_modified()` - Layer hierarchy (id/parent_id for groups) - Dirty tracking: composite_dirty, dirty_bounds per layer, global dirty flag ## Katman 4: ENGINE API (Kilitli) ### hcie-engine-api ```rust pub struct Engine { /* opaque */ } impl Engine { pub fn new(w: u32, h: u32) -> Self; pub fn add_layer(&mut self, name: &str) -> u64; pub fn delete_layer(&mut self, id: u64); pub fn set_active_layer(&mut self, id: u64); pub fn rename_layer(&mut self, id: u64, name: &str); pub fn set_layer_opacity(&mut self, id: u64, opacity: f32); pub fn set_layer_visible(&mut self, id: u64, visible: bool); pub fn set_layer_blend_mode(&mut self, id: u64, mode: BlendMode); pub fn undo(&mut self) -> bool; // returns success pub fn redo(&mut self) -> bool; // returns success pub fn can_undo(&self) -> bool; pub fn can_redo(&self) -> bool; pub fn history_len(&self) -> usize; pub fn history_current(&self) -> i32; pub fn history_description(&self, idx: usize) -> String; pub fn jump_to_history(&mut self, idx: i32); pub fn set_brush_size(&mut self, size: f32); pub fn set_brush_opacity(&mut self, opacity: f32); pub fn set_brush_color(&mut self, rgba: [u8; 4]); pub fn set_brush_style(&mut self, style: BrushStyle); pub fn draw_stroke(&mut self, points: &[(f32, f32, f32)]); // (x,y,pressure) pub fn draw_line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32); pub fn draw_rect(&mut self, x1: f32, y1: f32, x2: f32, y2: f32); pub fn draw_ellipse(&mut self, cx: f32, cy: f32, rx: f32, ry: f32); pub fn flood_fill(&mut self, x: u32, y: u32, color: [u8; 4]); pub fn create_selection_rect(&mut self, x1: u32, y1: u32, x2: u32, y2: u32); pub fn create_selection_ellipse(&mut self, cx: u32, cy: u32, rx: u32, ry: u32); pub fn selection_grow(&mut self, px: u32); pub fn selection_shrink(&mut self, px: u32); pub fn selection_feather(&mut self, radius: f32); pub fn selection_invert(&mut self); pub fn selection_clear(&mut self); pub fn get_selection_mask(&self) -> Option<&[u8]>; pub fn crop(&mut self, x: u32, y: u32, w: u32, h: u32); pub fn resize_canvas(&mut self, w: u32, h: u32); pub fn rotate_layer(&mut self, id: u64, degrees: f32); pub fn apply_filter(&mut self, filter_id: &str, params: serde_json::Value); pub fn add_text_layer(&mut self, text: &str, font: &str, size: f32, x: f32, y: f32, color: [u8; 4]); pub fn add_vector_shape(&mut self, shape: VectorShape); pub fn modify_vector_shape(&mut self, layer_id: u64, shape_idx: usize, handle: VectorEditHandle, dx: f32, dy: f32); pub fn set_vector_shape_color(&mut self, layer_id: u64, shape_idx: usize, color: [u8; 4]); pub fn set_vector_shape_opacity(&mut self, layer_id: u64, shape_idx: usize, opacity: f32); pub fn delete_vector_shape(&mut self, layer_id: u64, shape_idx: usize); pub fn open_image(&mut self, path: &std::path::Path) -> Result<(), String>; pub fn save_as(&mut self, path: &std::path::Path, format: &str) -> Result<(), String>; pub fn save_native(&mut self, path: &std::path::Path) -> Result<(), String>; pub fn export_layer(&mut self, layer_id: u64, path: &std::path::Path, format: &str) -> Result<(), String>; pub fn set_zoom(&mut self, zoom: f32); pub fn get_zoom(&self) -> f32; pub fn get_canvas_size(&self) -> (u32, u32); pub fn get_layer_count(&self) -> usize; pub fn get_layer_info(&self, id: u64) -> Option; pub fn get_active_layer_id(&self) -> u64; pub fn get_all_layer_ids(&self) -> Vec; pub fn get_layer_pixels(&self, id: u64) -> Option<&[u8]>; pub fn get_composite_pixels(&mut self) -> Vec; // Render + return RGBA pub fn get_preview_thumbnail(&self, id: u64, max_dim: u32) -> Vec; // Small thumbnail pub fn is_modified(&self) -> bool; pub fn set_modified(&mut self, modified: bool); pub fn tab_label(&self) -> String; // Batch AI actions pub fn execute_ai_actions(&mut self, actions: serde_json::Value) -> Result; } #[derive(Clone, Debug)] pub struct LayerInfo { pub id: u64, pub name: String, pub layer_type: LayerType, pub width: u32, pub height: u32, pub visible: bool, pub opacity: f32, pub blend_mode: BlendMode, pub locked: bool, pub parent_id: Option, pub clipping_mask: bool, pub collapsed: bool, pub has_vector_shapes: bool, pub shape_count: usize, } ``` ## Katman 5: AI / VISION (Kilitli) ### hcie-ai - Ollama `/api/chat` client - LMStudio client - Smart Select (SAM): segmentation model call - Inpaint: ComfyUI inpaint node - Object Removal: mask-based generation - `hcie-engine-api::Engine` passthrough (sadece API çağrıları) ### hcie-vision - ComfyUI pipeline runner - Background Removal (RMBG) - Procedural Texture Generation - Sky Replacement - AI Scoring / Live Drawing Review - `hcie-engine-api::Engine` passthrough ## Katman 6: GUI (Açık — AI Burada Çalışır) ### hcie-gui-egui (Ana Uygulama) - **Binary Entry & Core Orchestration** (`main.rs`, `app/mod.rs`): Runs `eframe::run_native` with custom borderless decorations, sets up event-loop shortcuts, manages global keyboard/clipboard states, and maintains an opaque reference to `hcie-engine-api::Engine`. - **Canvas Rendering Engine** (`canvas.rs`): Draws pixel-precise canvas displays with robust zoom, pan, rotation, and captures tablet pressure curves during brush operations. - **Event Messaging System** (`event_bus.rs`): Decouples components by dispatching high-level interactive signals (e.g. layers selection updates, file dialog completions). - **Layout Solver System** (`app/layout_solver.rs`): Advanced layout constraint solver for `egui_dock`: - **Symmetrical Dock Trees**: Symmetrical dual-column utility panels on both sides of the screen. Left columns host Tools/Filters & Brushes; right columns host Layers/Properties & Color/History/AI. - **Stable Phase (Measurement)**: Dynamically measures actual rendered column widths when layout is stable to preserve user-adjusted splitter dragging states. - **Resize Phase (Enforcement)**: Enforces pixel widths by computing precise horizontal splits recursively when a container resize triggers, ensuring dynamic canvas adjustments. - **Docking Panels Registry** (`app/dock.rs`, `app/panels.rs`, etc.): Modular panel drawing controllers (Brushes Panel, Colors Panel, Geometry Panel, History, Toolbox). - **Dynamic File Decoders** (`app/custom_loaders.rs`, `app/custom_loaders_kra_v2.rs`): Specialized parser models for layered formats like Krita (.kra). - **Automation Framework** (`plugin.rs`, `plugins/`): Modular host environment for system diagnostic logging plugins and custom scripts. - **Internationalization & Manifest** (`i18n.rs`, `manifest.rs`): Built-in multi-language translation lookups and pricing tier feature manifests. **Sürükleme Stratejisi (İkili Mod):** 1. PRIMARY: `invoke('window_start_drag')` → GTK native drag (X11'de çalışır, Wayland/GTK4'de xdg-shell move request ile çalışabilir) 2. FALLBACK: Manual pointer-based drag → `outerPosition()` + `setPosition()` PhysicalPosition→LogicalPosition dönüşümü ile (HiDPI düzeltmesi) **Detay:** `WAYLAND_WINDOW_FIX.md` ### hcie-gui-adapter (Bridge) - **Dynamic Schema UI Binder**: Bridges public engine APIs with standard egui elements by reading declarative layout structures (`ModulePanel` and `WidgetDescription`) from `hcie-protocol` and mapping them dynamically into standard control nodes. - **Unified Change Dispatcher**: Listens for state modifications in sliders, color pickers, checkboxes, button triggers, and dropdowns, then broadcasts the updates using a generic JSON-serialized callback. - **Key API Bindings**: ```rust pub fn render_module_panel(ui: &mut egui::Ui, panel: &ModulePanel, on_change: &mut impl FnMut(&str, serde_json::Value)); pub fn render_widget(ui: &mut egui::Ui, widget: &WidgetDescription, on_change: &mut impl FnMut(&str, serde_json::Value)); pub fn get_widget_value(ui: &egui::Ui, id: &str) -> Option; pub fn set_widget_value(ui: &egui::Ui, id: &str, value: T); ``` ### hcie-module-filters - Blur, Sharpen, B-C, HSL, Mosaic, Oil Paint, Crystallize, Pinch, Twirl, USM, Border - Slider'lar, dropdown'lar - Apply → `EngineCommand::ApplyFilter` ### hcie-module-ai-chat - Chat panel - AI query input - Response display - Action buttons (Smart Select, Inpaint, Remove) - Execute → `EngineCommand::ExecuteAiActions` ### hcie-module-script - Scripting ve otomasyon paneli. - DSL tabanlı veya parametrik şablonları (templates) yürütme motoru. - Kullanıcı komut dizilerini kaydetme ve çalıştırma arayüzü. ### hcie-module-ai-script - Yapay zeka destekli kod/script oluşturma ve yürütme paneli. - AI chat modülü ile script yürütücü arasındaki köprü görevi. ## Event Flow (GUI → Engine) ``` User clicks Canvas → hcie-gui-egui mouse event → Engine::draw_stroke(points) [hcie-engine-api call] → hcie-document layer modification [internal] → hcie-draw pixel rasterization [internal] → hcie-blend pixel compositing [internal] → hcie-composite full render [internal] → back to GUI: trigger repaint → GUI requests Engine::get_composite_pixels() → display ``` ## Render Flow (GUI Loop) Each frame: 1. GUI collects all panel commands (sliders moved, buttons clicked) 2. GUI sends all `EngineCommand` to `engine.execute_batch(commands)` 3. Engine processes internally (document state, dirty layers, history) 4. If `dirty`: engine composite happens → RGBA output buffer 5. GUI reads `engine.get_composite_pixels()` → uploads to `egui::TextureHandle` 6. GUI draws texture in canvas widget ## Kilitli Dosya Listesi (AI yazamaz) ``` crates/hcie-protocol/src/*.rs crates/hcie-color/src/*.rs crates/hcie-blend/src/*.rs crates/hcie-history/src/*.rs crates/hcie-brush-engine/src/*.rs crates/hcie-draw/src/*.rs crates/hcie-composite/src/*.rs crates/hcie-filter/src/*.rs crates/hcie-selection/src/*.rs crates/hcie-text/src/*.rs crates/hcie-vector/src/*.rs crates/hcie-tile/src/*.rs crates/hcie-io/src/*.rs crates/hcie-document/src/*.rs crates/hcie-engine-api/src/*.rs crates/hcie-ai/src/*.rs crates/hcie-vision/src/*.rs ``` ## Açık Dosya Listesi (AI yazar) ``` hcie-egui-app/crates/hcie-gui-egui/src/*.rs hcie-egui-app/crates/egui-panel-adapter/src/*.rs hcie-egui-app/crates/egui-panel-filters/src/*.rs hcie-egui-app/crates/egui-panel-ai-chat/src/*.rs hcie-egui-app/crates/egui-panel-script/src/*.rs hcie-egui-app/crates/egui-panel-ai-script/src/*.rs ``` ## AI Session Limits - Max 5 files modified per session - Max 200 lines written per new file - If compile fails, revert to last known good state, do NOT patch incrementally - All UI changes must include `trace_ui!(name, ui)` and `trace_event!(event)` conditionally - After any UI change, verify coordinates via terminal output before marking complete ## Coding Protocol (v3) 1. Prefer creating new .rs files over modifying existing ones; minimize changes to existing GUI files. 2. NEVER add egui dependency to engine crates 3. ONLY create new files in GUI and module crates 4. Engine API changes require explicit user approval (unlock protocol) 5. New feature = new .rs file + maybe new module crate with Cargo.toml 6. After writing code, run `cargo check` and `cargo test` before saying "done"