⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
imgui-ui-ux-engineering
Proactively design, improve, or review high-quality Dear ImGui tools, C++ editor panels, game-development interfaces, debugging dashboards, visualization screens, and desktop workflows. Use when Dear ImGui is named or supplied code contains direct evidence such as `ImGui::`, `imgui.h`, `ImGuiContext`, or ImGui backend symbols. For an unlabelled C++ editor/tooling request, use only when the user explicitly asks whether Dear ImGui is suitable; otherwise keep framework choice open. Do not trigger f
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
Dear ImGui UI/UX Engineering
Created and maintained by muhosekerci.
A production-oriented, portable Agent Skill for designing, reviewing, and hardening Dear ImGui tools, editor panels, debugging dashboards, asset browsers, visualization screens, and desktop workflows.
The package follows the Agent Skills open standard and is designed for skills-compatible CLI agents. Codex is one supported client, not a requirement or the defining platform.
This skill treats UI improvement as an engineering problem, not a cosmetic reskin. It combines information architecture, interaction design, immediate-mode state ownership, stable widget identity, keyboard navigation, DPI handling, performance, and regression validation in one reusable workflow.
What it helps with
| Area | Coverage |
|---|---|
| Workspace design | Dockspace shells, command bars, navigation, central work areas, inspectors, logs, and status bars |
| UI/UX review | Prioritized findings with evidence, impact, correction, and verification |
| Component engineering | Tables, asset browsers, inspectors, command palettes, modals, toasts, empty states, and custom draw-list controls |
| Immediate-mode correctness | Stable IDs, state ownership, focus transfer, input capture, and balanced scope stacks |
| Large datasets | Filtered/sorted index views, ImGuiTableSortSpecs, and ImGuiListClipper |
| Design systems | Centralized spacing, typography, semantic colors, interaction states, and contrast checks |
| DPI and fonts | Non-cumulative metric scaling and explicit FontScaleDpi ownership |
| Compatibility | Dear ImGui 1.92+, optional docking, official tag/master compilation, and vendored-header checks |
| Quality gates | Static scope checking, C++ template compilation, contrast validation, and 15 semantic regression cases |
Agent and CLI compatibility
This repository uses the portable SKILL.md directory format defined by the
Agent Skills specification. It does not depend on one
model provider or one CLI.
| Client | Support path |
|---|---|
| Antigravity CLI | Native Agent Skills support through .agents/skills and the /skills browser |
| Claude Code | Native Agent Skills support through .claude/skills |
| GitHub Copilot CLI | Native Agent Skills support through .agents/skills, .copilot/skills, or copilot skill add |
| OpenCode | Native discovery through .agents/skills, .opencode/skills, and compatible paths |
| Codex | Skill-directory installation using the same SKILL.md package |
| Other skills-compatible agents | Install the complete repository in the client's configured skills directory |
Clients that do not yet implement Agent Skills can still load SKILL.md as reusable project
instructions, but automatic discovery and activation depend on that client's capabilities.
When the skill activates
The skill is intended for requests that:
- explicitly mention Dear ImGui;
- include direct evidence such as
ImGui::,imgui.h,ImGuiContext, or backend symbols; - ask whether Dear ImGui is suitable for an otherwise unlabelled C++ tooling interface.
It keeps framework choice open when a generic C++ UI request provides no Dear ImGui evidence. It also stays out of tasks that explicitly select another framework such as Qt, GTK, WPF, wxWidgets, JUCE, or Slate.
Quick start
Install with Skills CLI (recommended)
Install the skill with one command:
npx skills add muhosekerci/imgui-ui-ux-engineering
The Skills CLI detects supported coding agents and installs the skill into the appropriate location. This gives the same repository package to compatible clients such as Claude Code, Codex, Antigravity CLI, GitHub Copilot CLI, OpenCode, Cursor, and other Agent Skills clients.
Manual universal installation (.agents/skills)
The shared .agents/skills location is recognized by multiple compatible clients,
including Antigravity CLI, GitHub Copilot CLI, and OpenCode.
Windows PowerShell
git clone https://github.com/muhosekerci/imgui-ui-ux-engineering.git `
(Join-Path $HOME ".agents\skills\imgui-ui-ux-engineering")
macOS or Linux
git clone https://github.com/muhosekerci/imgui-ui-ux-engineering.git \
"$HOME/.agents/skills/imgui-ui-ux-engineering"
Client-specific installation
| Client | Installation |
|---|---|
| Antigravity CLI | Use the Skills CLI command above, or clone into a workspace's .agents/skills/imgui-ui-ux-engineering |
| GitHub Copilot CLI | copilot skill add https://github.com/muhosekerci/imgui-ui-ux-engineering |
| Claude Code | Clone into ~/.claude/skills/imgui-ui-ux-engineering |
| OpenCode | Clone into ~/.config/opencode/skills/imgui-ui-ux-engineering or use ~/.agents/skills |
| Codex | Clone into ${CODEX_HOME:-$HOME/.codex}/skills/imgui-ui-ux-engineering |
| Other compatible CLIs | Point the client's skill installer at this repository, or clone it into that client's Agent Skills directory |
Reload or restart the client after installation if it does not support live skill discovery.
Antigravity CLI provides /skills to browse loaded local and global skills; GitHub Copilot
CLI provides /skills reload in an active session.
Update an existing installation
npx skills check
npx skills update
For a manually cloned installation, update it with:
git -C "$HOME/.agents/skills/imgui-ui-ux-engineering" pull
Use the skill
Skills-compatible agents can activate the skill automatically from the task description. You can also name it explicitly using the syntax supported by your client:
Use the imgui-ui-ux-engineering skill to review this asset browser for ID
collisions, keyboard focus bugs, DPI problems, and performance bottlenecks.
Review this asset browser for ID collisions, keyboard focus bugs, DPI
problems, and performance bottlenecks using imgui-ui-ux-engineering.
Design a Dear ImGui editor for 20,000 assets with filtering, sorting,
single selection, a property inspector, and a collapsible activity log.
Review this ImGui C++ panel and return Critical / High / Medium / Low
findings with fixes and verification steps.
Discoverability and sharing
If this project helps your workflow, star the repository and share the direct link:
https://github.com/muhosekerci/imgui-ui-ux-engineering
Good places to introduce the skill include:
- the
agent-skillsandcodex-skillsGitHub topics; - Agent Skills directories and client showcases;
- Awesome GitHub Copilot and Awesome Codex Skills through contributions;
- the Dear ImGui Discussions community;
- communities for Claude Code, Antigravity CLI, GitHub Copilot, Codex, OpenCode, and Dear ImGui;
- developer posts on DEV Community, Hashnode, LinkedIn, X, or a Show HN submission;
- C++ game-tooling, engine-development, editor-tooling, and technical-art communities.
When sharing, include one screenshot or short GIF, three example prompts, the 30/30 semantic eval result, and the one-command installation s
// HOW IT'S BUILT
// FILES
16 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md15 KBca3de3823cedupstream ↗
--- name: imgui-ui-ux-engineering description: Proactively design, improve, or review high-quality Dear ImGui tools, C++ editor panels, game-development interfaces, debugging dashboards, visualization screens, and desktop workflows. Use when Dear ImGui is named or supplied code contains direct evidence such as `ImGui::`, `imgui.h`, `ImGuiContext`, or ImGui backend symbols. For an unlabelled C++ editor/tooling request, use only when the user explicitly asks whether Dear ImGui is suitable; otherwise keep framework choice open. Do not trigger for a task that explicitly names another UI framework such as Qt, GTK, WPF, wxWidgets, JUCE, or Slate. Cover UI architecture, information hierarchy, dockspace layouts, design systems, custom components, UX states, keyboard/gamepad interaction, DPI/fonts, performance, and code quality. license: MIT compatibility: Portable Agent Skills open-standard package. Works with skills-compatible CLI agents; bundled validation requires Python 3.9+, and complete C++ gates require Git, network access, and a C++17 compiler. metadata: author: muhosekerci version: "1.0.0" repository: "https://github.com/muhosekerci/imgui-ui-ux-engineering" keywords: "agent-skills, dear-imgui, imgui, ui-ux, cpp, editor-tools, game-development, code-review, accessibility, dpi, performance" --- # Dear ImGui UI/UX Engineering ## Purpose and boundaries Build **professional tool interfaces** with Dear ImGui. Design around the immediate-mode model: application data remains the single source of truth, while UI code reflects the current model and dispatches user intent back to it. Dear ImGui is especially well suited to content-creation tools, editor and game tooling, debugging panels, operations screens, and real-time visualizations. Explicitly assess suitability when a consumer product needs complete accessibility support, RTL text, or complex text shaping. [1] [2] Do not treat a review as a cosmetic reskin. Improve functional hierarchy, interaction cost, error recovery, information density, technical correctness, and visual consistency together. ## Classify the request Match the request to one primary workflow. If Dear ImGui is neither named nor evidenced in supplied code, do not assume it is the framework; offer a framework-selection assessment only when explicitly asked. Make reasonable assumptions when missing information does not materially change the solution; ask only for a critical ambiguity. | Request | Primary deliverable | Start by determining | |---|---|---| | New tool or editor | Information architecture, workspace shell, design system, production-oriented C++ | User role, top three tasks, target platform | | Existing UI improvement | Audit, redesign proposal, focused code changes | Screenshot or code, hierarchy issues, missing states | | Component design | Behavioral contract, state matrix, ImGui implementation | Data, actions, empty/error state, keyboard behavior | | Theme or visual identity | Design tokens, palette, typography, theme code | Task density, brand constraints, contrast requirements | | Code review | Prioritized findings and safe fixes | IDs, stack balance, state ownership, input, clipping, DPI, performance | ## Required workflow 1. **Extract the context.** Identify the user, principal tasks, data scale, display sizes, input devices, density preference, and destructive actions. 2. **Create the hierarchy.** Keep the primary action visible and close to its task; place contextual actions near the selected object or inspector; move rare settings into menus or disclosure controls. Define selected, empty, loading, error, unauthorized, and completed states for every view. 3. **Select the workspace shell.** When appropriate, use a command bar, left navigation or asset pane, central work area, right inspector, bottom log/progress surface, and status bar. Persist docking and window layout only when personalization provides real value. Verify that the chosen Dear ImGui branch/version supports any docking API. [2] 4. **Build the design system.** Centralize spacing, radii, borders, typography, surface layers, and semantic colors. Start from `templates/imgui_design_system.h.in`, then adapt it to the product and density requirements. 5. **Build components around tasks.** Prefer built-in widgets, the table API, and standard interactions. Use custom draw-list code only when a distinctive behavior or visual treatment is genuinely required. Design normal, hovered, active, selected, focused, disabled, loading, and error states. 6. **Design interaction.** Validate keyboard and, when relevant, gamepad navigation, focus, shortcuts, cancellation, and undo. Always forward raw input to Dear ImGui; use `io.WantCaptureMouse`, `io.WantCaptureKeyboard`, and `io.WantTextInput` to decide whether the underlying application also receives it. [2] 7. **Perform the technical audit.** Check identity collisions, `Push`/`Pop` and `Begin`/`End` balance, frame-local allocations, clipping of large lists, DPI handling, contrast, and version-specific APIs. 8. **Validate tasks, not just pixels.** Test narrow and wide panels, long text, no data, hundreds of records, failed work, and keyboard-only operation. Verify alignment, action feedback, and recovery paths. ## Workspace composition Use the following as an adaptable composition system, not a rigid pixel template. | Region | Purpose | Implementation guidance | |---|---|---| | Command bar | Frequent global actions, search, workspace switching | Keep the action count low; move secondary commands into menus or a command palette. | | Navigation or asset pane | Hierarchy, collection, scene, files, filters | Provide search, collapsible groups, visible selection, and small counts. | | Central work area | Canvas, table, timeline, chart, or main editor | Allocate the greatest area and contrast here; remove nonessential chrome. | | Inspector | Selected-object properties and contextual actions | Group fields by mental model; offer live preview and a safe reset action. | | Supporting surface | Log, performance, job queue, issue list | Make it dismissible or collapsible when it is not needed. | | Status bar | Connection, selection, process, coordinate, or performance state | Keep it concise, live, and actionable. | ### Density and hierarchy Choose the density from task frequency and data scale, then express priority with surface elevation, typography, whitespace, color, and placement. Never make color the only carrier of meaning. For detailed density guidance and component contracts, read `references/design-playbook.md`. [5] ## Choose the right component | Component | Use it for | Avoid using it for | |---|---|---| | Table or asset browser | Sortable, filterable, multi-column data | Rendering thousands of records as cards | | Inspector | Editable properties of the selected object | Unrelated global settings | | Metric card | A small number of critical KPIs and trends | Every number on the screen | | Command palette | Many commands and expert keyboard workflows | Hiding a core action from the main UI | | Modal | Confirmation or a short focused decision | A long-lived editor or comprehensive form | | Toast | Brief success feedback and undo affordance | The only presentation of a critical error | | Empty state | First use or an empty filter result | Leaving the user in an unexplained blank panel | Read `references/design-playbook.md` when detailed layout patterns, component contracts, state copy, or a review rubric is needed. Read `references/worked-example.md` before writing a review or before/after proposal when a concrete output model would improve consistency. ## Dear ImGui implementation rules ### State, identity, and structure Keep the application model as the **single source of truth**. Store UI state only when it is presentation-specific, such as an open pane, temporary filter text, or drag preview. For pointer-backed display fields, either enforce and document a non-null model invariant or route every UI read through a null-safe display adapter; never rely on an implicit nullable-string convention. Guarantee unique IDs for repeated widgets. Use `##` to add an invisible suffix, `PushID()`/`PopID()` with a stable object key for loops and dynamic collections, and `###` to keep an ID stable while a visible label changes. Repeating labels in the same scope creates collisions. [2] Balance every `Push*` with the matching `Pop*` and every `Begin*` with the corresponding `End*`. Follow each API's contract; for example, do not skip a required `End()` merely because a window is currently collapsed. ### Layout and large data Use fixed pixel coordinates only as a last resort. Compose layouts with `BeginTable`, child regions, available width, flexible columns, and spacing tokens. Align inspector labels and inputs in two columns, then test the narrowest supported panel. For large collections, build a filtered stable-ID view and render visible rows with `ImGuiListClipper`. Process `ImGuiTableSortSpecs` when exposing sortable columns; a `Sortable` flag without actual model ordering is an incomplete interaction. Provide sort direction, active-filter summary, visible selection, and a meaningful empty result. ### Theme, typography, and DPI Centralize measurements. Derive padding, spacing, and radii from a small scale. Separate layers with `WindowBg`, `ChildBg`, `PopupBg`, and borders rather than assigning an arbitrary tone to every panel. Target a minimum **4.5:1** contrast ratio for normal text and **3:1** for large text. [4] Choose an appropriate font if the default is not readable at the tool's intended size. Select exactly one owner for `FontScaleDpi`: use the template's host-managed policy with a host-provided scale, or select its Dear-ImGui-managed policy when the docking branch's `io.ConfigDpiScaleFonts` automatically updates it as monitor DPI changes. Continue to reset the style and apply `ScaleAllSizes()` for size/padding scaling when the content scale changes. Confirm target version and backend capabilities before relying on newer APIs. [3] ### Keyboard, gamepad, and accessibility Enable `ImGuiConfigFlags_NavEnableKeyboard` and, when needed, `ImGuiConfigFlags_NavEnableGamepad`. Test Tab/Shift+Tab traversal, visible focus, Escape cancellation, Enter confirmation, and critical application shortcuts. Move default keyboard focus only when an explicit navigation or programmatic-selection request requires it; do not reassert focus for a selected row every frame. Clearly report Dear ImGui's built-in accessibility and complete internationalization limitations rather than presenting a theme change as a complete solution. [1] Make focus, hover, and selection visually distinct. Use a tooltip to supplement an ambiguous icon or abbreviation, not to explain a required task. When a control is disabled, expose the reason briefly. ## Custom drawing and component contract Before writing custom draw-list code, first determine whether a composition of built-in widgets, tables, selectables, trees, popups, and child regions satisfies the need. For every custom control: 1. Define the visible boundary and hit area in the same coordinate model. 2. Generate a unique ID and specify normal, hover, active, selected, focused, disabled, loading, and error behavior. 3. Define click, drag, cancellation, and no-data behavior in writing. 4. Respect clipping; generate only visible geometry for large data; minimize persistent per-frame allocation. 5. Draw colors, spacing, and fonts from central tokens; never embed arbitrary visual constants in a component. 6. Visually verify narrow/wide panels, low/high DPI, and every interaction state. ## Deliverable contract | Deliverable | Must include | |---|---| | Design proposal | User/task list, screen regions, priority hierarchy, state matrix, interaction notes, implementation order | | C++ implementation | Theme tokens, component functions, ID strategy, state ownership, empty/error states, version assumptions | | Redesign | Before/after issue table, proposed structure, measurable improvement goal, targeted changes | | Code review | `Critical / High / Medium / Low` priority, evidence, impact, fix, and verification step | Use `templates/imgui_panel_skeleton.cpp.in` for a dockspace-oriented workspace shell and `templates/imgui_design_system.h.in` for a centralized token system. Read `references/version-notes.md` before copying version-sensitive code into a vendored or pinned Dear ImGui project. When reviewing or generating C++ source, run `scripts/check_imgui_cpp.py <source...>` to catch common direct `Begin`/`End` and `Push`/`Pop` balance mistakes; treat it as a narrow static guard, not a replacement for compilation or runtime testing. For automated structural, semantic, contrast, static-checker, and compile regression checks, run `python3 scripts/run_quality_suite.py`; every normal run fetches temporary official `v1.92.0` and `master` sources and compiles the templates against both. The bundled semantic reference responses must score 30/30; pass `--semantic-responses RESPONSES.json` to gate target-model outputs against the same contracts. To validate a product fork, additionally supply `--imgui-dir /path/to/vendored/imgui`. Use `--skip-official-revisions` only for an explicitly offline diagnostic run; it is not a release gate. Use `evals/quality-suite.md` and `evals/failure-mode-regressions.md` only when revising or regression-testing this skill; the latter tests concrete state, scope, focus, and DPI failures rather than generic output quality. ## Release quality gate - Does the primary task have an obvious, visible, nearby entry point? - Are selected, hovered, focused, disabled, error, loading, and empty states distinguishable? - Is the primary action clearly separate from secondary and destructive actions? - Are shortcuts, focus flow, Escape/cancel, and input capture correct? - Do tables/lists work with large data, filtering, sorting, selection, and empty results? - Are widget IDs unique and `Push`/`Pop`, `Begin`/`End` calls balanced? - Do nullable model values render safely, and does default focus move only after an explicit request? - Have contrast, font legibility, DPI, narrow panels, and long content been tested? - Have clipping, avoidable allocations, and profiling been considered? - Has `scripts/run_quality_suite.py` passed against each supported vendored Dear ImGui header revision? - Are accessibility and internationalization limitations explicit where relevant? ## References [1] [Dear ImGui official repository](https://github.com/ocornut/imgui) [2] [Dear ImGui FAQ: paradigm, IDs, input capture, navigation, and docking](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) [3] [Dear ImGui: fonts, DPI scaling, and icons](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) [4] [W3C WCAG 2.2: Understanding Contrast (Minimum)](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) [5] [Nielsen Norman Group: 10 usability heuristics](https://www.nngroup.com/articles/ten-usability-heuristics/)README.md15 KB07395418cacaupstream ↗
# Dear ImGui UI/UX Engineering     [](https://github.com/muhosekerci) Created and maintained by **[muhosekerci](https://github.com/muhosekerci)**. A production-oriented, portable **Agent Skill** for designing, reviewing, and hardening **Dear ImGui** tools, editor panels, debugging dashboards, asset browsers, visualization screens, and desktop workflows. The package follows the [Agent Skills open standard](https://agentskills.io/specification) and is designed for skills-compatible CLI agents. Codex is one supported client, not a requirement or the defining platform. This skill treats UI improvement as an engineering problem, not a cosmetic reskin. It combines information architecture, interaction design, immediate-mode state ownership, stable widget identity, keyboard navigation, DPI handling, performance, and regression validation in one reusable workflow. ## What it helps with | Area | Coverage | |---|---| | Workspace design | Dockspace shells, command bars, navigation, central work areas, inspectors, logs, and status bars | | UI/UX review | Prioritized findings with evidence, impact, correction, and verification | | Component engineering | Tables, asset browsers, inspectors, command palettes, modals, toasts, empty states, and custom draw-list controls | | Immediate-mode correctness | Stable IDs, state ownership, focus transfer, input capture, and balanced scope stacks | | Large datasets | Filtered/sorted index views, `ImGuiTableSortSpecs`, and `ImGuiListClipper` | | Design systems | Centralized spacing, typography, semantic colors, interaction states, and contrast checks | | DPI and fonts | Non-cumulative metric scaling and explicit `FontScaleDpi` ownership | | Compatibility | Dear ImGui 1.92+, optional docking, official tag/master compilation, and vendored-header checks | | Quality gates | Static scope checking, C++ template compilation, contrast validation, and 15 semantic regression cases | ## Agent and CLI compatibility This repository uses the portable `SKILL.md` directory format defined by the [Agent Skills specification](https://agentskills.io/specification). It does not depend on one model provider or one CLI. | Client | Support path | |---|---| | [Antigravity CLI](https://antigravity.google/docs/skills) | Native Agent Skills support through `.agents/skills` and the `/skills` browser | | [Claude Code](https://code.claude.com/docs/en/skills) | Native Agent Skills support through `.claude/skills` | | [GitHub Copilot CLI](https://docs.github.com/en/copilot/concepts/agents/about-agent-skills) | Native Agent Skills support through `.agents/skills`, `.copilot/skills`, or `copilot skill add` | | [OpenCode](https://opencode.ai/docs/skills) | Native discovery through `.agents/skills`, `.opencode/skills`, and compatible paths | | Codex | Skill-directory installation using the same `SKILL.md` package | | Other skills-compatible agents | Install the complete repository in the client's configured skills directory | Clients that do not yet implement Agent Skills can still load `SKILL.md` as reusable project instructions, but automatic discovery and activation depend on that client's capabilities. ## When the skill activates The skill is intended for requests that: - explicitly mention Dear ImGui; - include direct evidence such as `ImGui::`, `imgui.h`, `ImGuiContext`, or backend symbols; - ask whether Dear ImGui is suitable for an otherwise unlabelled C++ tooling interface. It keeps framework choice open when a generic C++ UI request provides no Dear ImGui evidence. It also stays out of tasks that explicitly select another framework such as Qt, GTK, WPF, wxWidgets, JUCE, or Slate. ## Quick start ### Install with Skills CLI (recommended) Install the skill with one command: ```bash npx skills add muhosekerci/imgui-ui-ux-engineering ``` The Skills CLI detects supported coding agents and installs the skill into the appropriate location. This gives the same repository package to compatible clients such as Claude Code, Codex, Antigravity CLI, GitHub Copilot CLI, OpenCode, Cursor, and other Agent Skills clients. ### Manual universal installation (`.agents/skills`) The shared `.agents/skills` location is recognized by multiple compatible clients, including Antigravity CLI, GitHub Copilot CLI, and OpenCode. #### Windows PowerShell ```powershell git clone https://github.com/muhosekerci/imgui-ui-ux-engineering.git ` (Join-Path $HOME ".agents\skills\imgui-ui-ux-engineering") ``` #### macOS or Linux ```bash git clone https://github.com/muhosekerci/imgui-ui-ux-engineering.git \ "$HOME/.agents/skills/imgui-ui-ux-engineering" ``` ### Client-specific installation | Client | Installation | |---|---| | Antigravity CLI | Use the Skills CLI command above, or clone into a workspace's `.agents/skills/imgui-ui-ux-engineering` | | GitHub Copilot CLI | `copilot skill add https://github.com/muhosekerci/imgui-ui-ux-engineering` | | Claude Code | Clone into `~/.claude/skills/imgui-ui-ux-engineering` | | OpenCode | Clone into `~/.config/opencode/skills/imgui-ui-ux-engineering` or use `~/.agents/skills` | | Codex | Clone into `${CODEX_HOME:-$HOME/.codex}/skills/imgui-ui-ux-engineering` | | Other compatible CLIs | Point the client's skill installer at this repository, or clone it into that client's Agent Skills directory | Reload or restart the client after installation if it does not support live skill discovery. Antigravity CLI provides `/skills` to browse loaded local and global skills; GitHub Copilot CLI provides `/skills reload` in an active session. ### Update an existing installation ```bash npx skills check npx skills update ``` For a manually cloned installation, update it with: ```bash git -C "$HOME/.agents/skills/imgui-ui-ux-engineering" pull ``` ### Use the skill Skills-compatible agents can activate the skill automatically from the task description. You can also name it explicitly using the syntax supported by your client: ```text Use the imgui-ui-ux-engineering skill to review this asset browser for ID collisions, keyboard focus bugs, DPI problems, and performance bottlenecks. ``` ```text Review this asset browser for ID collisions, keyboard focus bugs, DPI problems, and performance bottlenecks using imgui-ui-ux-engineering. ``` ```text Design a Dear ImGui editor for 20,000 assets with filtering, sorting, single selection, a property inspector, and a collapsible activity log. ``` ```text Review this ImGui C++ panel and return Critical / High / Medium / Low findings with fixes and verification steps. ``` ## Discoverability and sharing If this project helps your workflow, star the repository and share the direct link: ```text https://github.com/muhosekerci/imgui-ui-ux-engineering ``` Good places to introduce the skill include: - the [`agent-skills`](https://github.com/topics/agent-skills) and [`codex-skills`](https://github.com/topics/codex-skills) GitHub topics; - Agent Skills directories and client showcases; - [Awesome GitHub Copilot](https://github.com/github/awesome-copilot) and [Awesome Codex Skills](https://github.com/ComposioHQ/awesome-codex-skills) through contributions; - the [Dear ImGui Discussions](https://github.com/ocornut/imgui/discussions) community; - communities for Claude Code, Antigravity CLI, GitHub Copilot, Codex, OpenCode, and Dear ImGui; - developer posts on DEV Community, Hashnode, LinkedIn, X, or a Show HN submission; - C++ game-tooling, engine-development, editor-tooling, and technical-art communities. When sharing, include one screenshot or short GIF, three example prompts, the 30/30 semantic eval result, and the one-command installation snippet above. This makes the purpose and value of the skill understandable without requiring readers to inspect the repository first. ## Expected deliverables Depending on the task, the skill returns: - user and primary-task definitions; - workspace regions and priority hierarchy; - selected, empty, loading, error, disabled, and completed states; - interaction and keyboard-navigation behavior; - centralized theme and spacing tokens; - production-oriented C++ implementation guidance; - stable-ID and state-ownership strategy; - version and docking assumptions; - prioritized review findings; - concrete verification steps. ## Included templates ### `templates/imgui_design_system.h.in` A centralized Dear ImGui theme with: - semantic surface, content, accent, success, warning, and danger colors; - filled-button states that maintain at least 4.5:1 text contrast; - spacing, padding, radius, border, and density tokens; - host-managed and Dear-ImGui-managed font DPI policies; - non-cumulative `ScaleAllSizes()` handling; - reusable primary and destructive button helpers. ### `templates/imgui_panel_skeleton.cpp.in` A workspace starter demonstrating: - optional guarded docking; - a sortable and filterable asset table; - stable model IDs and null-safe display strings; - a filtered/sorted derived index view; - `ImGuiListClipper` for large collections; - one-shot programmatic keyboard focus, including off-screen rows; - inspector, activity-log, metrics, empty, and locked states. ## Repository structure ```text . ├── SKILL.md ├── README.md ├── agents/ │ └── openai.yaml # Optional Codex/OpenAI adapter metadata ├── evals/ │ ├── quality-suite.md │ ├── failure-mode-regressions.md │ ├── semantic-cases.json │ └── fixtures/ │ ├── balanced_scopes.cpp │ ├── unbalanced_push_id.cpp │ └── reference-responses.json ├── references/ │ ├── design-playbook.md │ ├── version-notes.md │ └── worked-example.md ├── scripts/ │ ├── check_imgui_cpp.py │ ├── run_semantic_suite.py │ └── run_quality_suite.py └── templates/ ├── imgui_design_system.h.in └── imgui_panel_skeleton.cpp.in ``` ## Quality gates ### Complete release gate ```bash python scripts/run_quality_suite.py ``` The complete gate: 1. validates required package files and unfinished markers; 2. verifies portable Agent Skills frontmatter and naming constraints; 3. checks the `SKILL.md` size guard; 4. verifies theme contrast; 5. runs the ImGui scope checker against valid and intentionally invalid fixtures; 6. scores all semantic reference cases at a required **30/30**; 7. downloads temporary official Dear ImGui `v1.92.0` and `master` sources; 8. compiles the templates against both with C++17 and warnings as errors. ### Offline diagnostic gate ```bash python scripts/run_quality_suite.py --skip-official-revisions ``` This runs structural, semantic, contrast, and static checks without downloading official Dear ImGui revisions. It is useful for fast local feedback, but it is not the release gate. ### Validate a vendored Dear ImGui revision ```bash python scripts/run_quality_suite.py --imgui-dir /path/to/vendored/imgui ``` The supplied directory must contain `imgui.h`. The command can be repeated with multiple `--imgui-dir` arguments. ### Check project C++ files directly ```bash python scripts/check_imgui_cpp.py path/to/panel.cpp path/to/widgets.h ``` The checker detects common direct `Begin`/`End` and `Push`/`Pop` mistakes. It is deliberately narrow and should be used alongside compilation and Dear ImGui runtime debug tools. ## Semantic evaluation The package contains ten standard cases (`E01`-`E10`) and five incident-style failure cases (`F01`-`F05`). The release contract requires: - standard score: **20/20**; - failure-mode score: **10/10**; - combined score: **30/30**; - no zero-score case and no fatal unsafe recommendation. Run the bundled reference responses: ```bash python scripts/run_semantic_suite.py ``` To grade target-model output, create a JSON object containing all 15 response IDs: ```json { "E01": "Response for E01", "E02": "Response for E02", "F05": "Response for F05" } ``` The real file must contain every ID from `E01` through `E10` and `F01` through `F05` exactly once. Then run: ```bash python scripts/run_quality_suite.py --semantic-responses responses.json ``` ## Design principles 1. **Application data is the source of truth.** Persist only presentation-specific UI state. 2. **Every repeated widget has a stable unique ID.** Never rely on visible text alone. 3. **Derived views do not mutate the source model.** Filtering and sorting operate on indices. 4. **Focus moves only after explicit navigation intent.** Pointer selection does not steal it. 5. **Large collections are clipped.** Rendering cost should scale with visible rows. 6. **Theme values are semantic and centralized.** Color is never the only status signal. 7. **DPI has one font-scale owner.** Metric scaling is reset and applied non-cumulatively. 8. **Version-sensitive APIs are verified against real headers.** Numeric versions do not prove docking support. 9. **Tasks are validated, not only screenshots.** Empty, error, narrow, long-content, and keyboard-only states matter. ## Requirements - Python 3.9 or newer; - Git for fetching official Dear ImGui revisions; - `g++` or another `c++` executable with C++17 support for compile gates; - network access for the complete official-revision gate. The generated C++ templates require Dear ImGui **1.92.0 or newer**. Docking remains optional and is guarded with `IMGUI_HAS_DOCK`. ## Important limitations Dear ImGui is particularly effective for game tools, editors, debugging interfaces, and real-time technical workflows. Before choosing it for a consumer-facing application, assess requirements for complete screen-reader integration, RTL text, complex text shaping, and platform-native accessibility behavior. Custom draw-list controls also require more work than built-in widgets: define their ID, hit area, interaction states, keyboard path, cancellation behavior, clipping, and semantic representation before implementation. ## License Released under the [MIT License](LICENSE). Copyright (c) 2026 [muhosekerci](https://github.com/muhosekerci). ## References - [Dear ImGui repository](https://github.com/ocornut/imgui) - [Dear ImGui FAQ](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) - [Dear ImGui fonts and DPI documentation](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) - [Dear ImGui docking wiki](https://github.com/ocornut/imgui/wiki/Docking) - [WCAG 2.2 contrast guidance](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) ## Contributing When changing behavior: 1. update the relevant guidance or template; 2. add or revise a semantic regression case; 3. run the offline gate during development; 4. run the complete release gate before publishing; 5. verify against the product's vendored Dear ImGui headers when available. ## Author **muhosekerci** — creator and maintainer of Dear ImGui UI/UX Engineering. - GitHub: [github.com/muhosekerci](https://github.com/muhosekerci)scripts/check_imgui_cpp.py7.1 KB91912d82a273upstream ↗
#!/usr/bin/env python3 """Check common Dear ImGui scope-stack balance mistakes in C++ source files. This is a lightweight static guard, not a C++ parser. It ignores comments and string literals, detects missing direct ImGui::End* calls, and tracks Push/Pop calls for ID, font, style-color, and style-var stacks. It intentionally tolerates extra lexical End* calls because the standard conditional Begin/End idiom contains mutually exclusive End() paths. Run it alongside compilation and tests. """ from __future__ import annotations import argparse import re import sys from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import DefaultDict @dataclass(frozen=True) class Call: name: str line: int argument: str # Capture the remainder of a statement after the opening parenthesis. This intentionally # tolerates nested constructor/function calls such as PushStyleColor(..., ImVec4(...)). CALL_RE = re.compile( r"\bImGui::(?P<name>" r"Begin(?:[A-Za-z0-9_]*)|End(?:[A-Za-z0-9_]*)|" r"Push(?:ID|Font|StyleColor|StyleVar)|Pop(?:ID|Font|StyleColor|StyleVar)" r")\s*\((?P<argument>[^\n;{}]*)" ) def mask_comments_and_literals(source: str) -> str: """Replace comments and literals with spaces while preserving newlines.""" output: list[str] = [] i = 0 state = "code" while i < len(source): char = source[i] next_char = source[i + 1] if i + 1 < len(source) else "" if state == "code": if char == "/" and next_char == "/": output.extend((" ", " ")) i += 2 state = "line_comment" continue if char == "/" and next_char == "*": output.extend((" ", " ")) i += 2 state = "block_comment" continue if char == '"': output.append(" ") i += 1 state = "string" continue if char == "'": output.append(" ") i += 1 state = "character" continue output.append(char) i += 1 continue if state == "line_comment": output.append("\n" if char == "\n" else " ") if char == "\n": state = "code" i += 1 continue if state == "block_comment": if char == "*" and next_char == "/": output.extend((" ", " ")) i += 2 state = "code" else: output.append("\n" if char == "\n" else " ") i += 1 continue # Handle C++ string/character literals and escaped delimiters. if char == "\\" and i + 1 < len(source): output.append(" ") output.append("\n" if source[i + 1] == "\n" else " ") i += 2 continue if (state == "string" and char == '"') or (state == "character" and char == "'"): output.append(" ") i += 1 state = "code" continue output.append("\n" if char == "\n" else " ") i += 1 return "".join(output) def collect_calls(source: str) -> list[Call]: masked = mask_comments_and_literals(source) calls: list[Call] = [] for match in CALL_RE.finditer(masked): line = masked.count("\n", 0, match.start()) + 1 calls.append(Call(match.group("name"), line, match.group("argument").strip())) return calls def pop_count(call: Call) -> int: if call.name in {"PopStyleColor", "PopStyleVar"}: numeric = re.match(r"(\d+)", call.argument) return int(numeric.group(1)) if numeric else 1 return 1 def check_scope_pairs(calls: list[Call]) -> list[str]: begins: DefaultDict[str, list[int]] = defaultdict(list) ends: DefaultDict[str, list[int]] = defaultdict(list) for call in calls: if call.name.startswith("Begin"): begins[call.name[5:]].append(call.line) elif call.name.startswith("End"): ends[call.name[3:]].append(call.line) errors: list[str] = [] for suffix in sorted(set(begins) | set(ends)): opened = begins[suffix] closed = ends[suffix] # A conditional window commonly uses both an early End()+return branch and a # normal End() branch. Static lexical counting therefore cannot treat extra End* # calls as an error without false positives. Missing End* calls remain actionable. if len(opened) > len(closed): label = f"Begin{suffix}" if suffix else "Begin" end_label = f"End{suffix}" if suffix else "End" errors.append( f"{label}/{end_label}: {len(opened)} begin call(s) at lines {opened}; " f"only {len(closed)} end call(s) at lines {closed}." ) return errors def check_stack_pairs(calls: list[Call]) -> list[str]: mapping = { "PushID": "ID", "PopID": "ID", "PushFont": "Font", "PopFont": "Font", "PushStyleColor": "StyleColor", "PopStyleColor": "StyleColor", "PushStyleVar": "StyleVar", "PopStyleVar": "StyleVar", } depth: DefaultDict[str, int] = defaultdict(int) errors: list[str] = [] for call in calls: kind = mapping.get(call.name) if kind is None: continue if call.name.startswith("Push"): depth[kind] += 1 continue amount = pop_count(call) if amount > depth[kind]: errors.append( f"{call.name} at line {call.line} pops {amount} {kind} scope(s), " f"but only {depth[kind]} are open." ) depth[kind] = 0 else: depth[kind] -= amount for kind, remaining in sorted(depth.items()): if remaining: errors.append(f"{kind} stack has {remaining} unclosed Push call(s).") return errors def check_file(path: Path) -> list[str]: try: source = path.read_text(encoding="utf-8") except OSError as error: return [f"Could not read {path}: {error}"] calls = collect_calls(source) return check_scope_pairs(calls) + check_stack_pairs(calls) def main() -> int: parser = argparse.ArgumentParser( description="Detect common direct Dear ImGui Begin/End and Push/Pop balance errors." ) parser.add_argument("sources", nargs="+", type=Path, help="C++ source or header files to inspect") parser.add_argument("--quiet", action="store_true", help="Print only errors") args = parser.parse_args() all_errors: list[str] = [] for path in args.sources: errors = check_file(path) if errors: for error in errors: all_errors.append(f"{path}: {error}") elif not args.quiet: print(f"PASS {path}: common Dear ImGui scope stacks are balanced.") if all_errors: for error in all_errors: print(f"FAIL {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())scripts/run_quality_suite.py15 KB238352805f08upstream ↗
#!/usr/bin/env python3 """Run structural, semantic, static-checker, and compile regression gates for this skill. Usage: python3 scripts/run_quality_suite.py python3 scripts/run_quality_suite.py --imgui-dir /path/to/vendored/imgui python3 scripts/run_quality_suite.py --semantic-responses /path/to/responses.json Every normal run fetches temporary official Dear ImGui v1.92.0 and master sources, then compiles the bundled templates against both. --imgui-dir adds a product fork or pinned revision. The harness never executes generated C++ binaries. Use --skip-official-revisions only for an explicitly offline structural/static-checker run; it is not a release gate. """ from __future__ import annotations import argparse import math import re import shutil import subprocess import sys import tempfile import time from pathlib import Path SKILL_DIR = Path(__file__).resolve().parents[1] CHECKER = SKILL_DIR / "scripts" / "check_imgui_cpp.py" PANEL_TEMPLATE = SKILL_DIR / "templates" / "imgui_panel_skeleton.cpp.in" THEME_TEMPLATE = SKILL_DIR / "templates" / "imgui_design_system.h.in" BALANCED_FIXTURE = SKILL_DIR / "evals" / "fixtures" / "balanced_scopes.cpp" UNBALANCED_FIXTURE = SKILL_DIR / "evals" / "fixtures" / "unbalanced_push_id.cpp" QUALITY_SUITE = SKILL_DIR / "evals" / "quality-suite.md" FAILURE_MODE_REGRESSIONS = SKILL_DIR / "evals" / "failure-mode-regressions.md" SEMANTIC_CASES = SKILL_DIR / "evals" / "semantic-cases.json" SEMANTIC_RESPONSES = SKILL_DIR / "evals" / "fixtures" / "reference-responses.json" SEMANTIC_RUNNER = SKILL_DIR / "scripts" / "run_semantic_suite.py" REQUIRED_FILES = ( SKILL_DIR / "LICENSE", SKILL_DIR / "README.md", SKILL_DIR / "SKILL.md", SKILL_DIR / "agents" / "openai.yaml", SKILL_DIR / "references" / "design-playbook.md", SKILL_DIR / "references" / "version-notes.md", SKILL_DIR / "references" / "worked-example.md", QUALITY_SUITE, FAILURE_MODE_REGRESSIONS, SEMANTIC_CASES, SEMANTIC_RESPONSES, SEMANTIC_RUNNER, CHECKER, PANEL_TEMPLATE, THEME_TEMPLATE, BALANCED_FIXTURE, UNBALANCED_FIXTURE, ) # Keep this matrix small and evidence-backed. It checks the documented baseline and # the maintained mainline API surface without placing cloned sources in the skill package. OFFICIAL_IMGUI_REVISIONS = ("v1.92.0", "master") OFFICIAL_IMGUI_REPOSITORY = "https://github.com/ocornut/imgui.git" def run(command: list[str], label: str, expect_success: bool = True) -> bool: completed = subprocess.run(command, text=True, capture_output=True, check=False) actual_success = completed.returncode == 0 passed = actual_success == expect_success print(f"{'PASS' if passed else 'FAIL'} {label}") if completed.stdout.strip(): print(completed.stdout.strip()) if completed.stderr.strip(): stream = sys.stdout if passed and not expect_success else sys.stderr print(completed.stderr.strip(), file=stream) return passed def check_required_files() -> bool: missing = [str(path.relative_to(SKILL_DIR)) for path in REQUIRED_FILES if not path.is_file() or path.stat().st_size == 0] if missing: print(f"FAIL package resources missing or empty: {', '.join(missing)}", file=sys.stderr) return False print("PASS package resources are present.") return True def check_agent_skills_frontmatter() -> bool: """Validate the portable Agent Skills fields without adding a YAML dependency.""" source = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8") if not source.startswith("---\n") or "\n---\n" not in source[4:]: print("FAIL SKILL.md must begin with a YAML frontmatter block.", file=sys.stderr) return False frontmatter = source.split("\n---\n", 1)[0][4:] def scalar(field: str) -> str | None: match = re.search(rf"^{re.escape(field)}:\s*(.+?)\s*$", frontmatter, re.MULTILINE) return match.group(1).strip().strip('"\'') if match else None name = scalar("name") description = scalar("description") license_name = scalar("license") compatibility = scalar("compatibility") errors: list[str] = [] if name is None or re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name) is None or len(name) > 64: errors.append("name must be 1-64 lowercase alphanumeric/hyphen characters") elif name != SKILL_DIR.name: errors.append(f"name '{name}' must match parent directory '{SKILL_DIR.name}'") if description is None or not 1 <= len(description) <= 1024: errors.append("description must contain 1-1024 characters") if license_name != "MIT": errors.append("license must reference the bundled MIT license") if compatibility is None or not 1 <= len(compatibility) <= 500: errors.append("compatibility must contain 1-500 characters") if not re.search(r"^metadata:\s*$", frontmatter, re.MULTILINE): errors.append("metadata mapping is required for author and index fields") if errors: print(f"FAIL Agent Skills frontmatter: {'; '.join(errors)}", file=sys.stderr) return False print("PASS Agent Skills frontmatter, naming, license, compatibility, and metadata checks.") return True def check_english_and_markers() -> bool: turkish_specific = re.compile(r"[ğüşıöçĞÜŞİÖÇ]") unfinished_marker = "TO" + "DO" todo = re.compile(r"\[" + unfinished_marker + r"\]|" + unfinished_marker + ":") offenders: list[str] = [] content_suffixes = {".md", ".yaml", ".json", ".py", ".in", ".cpp"} for path in SKILL_DIR.rglob("*"): if not path.is_file() or "__pycache__" in path.parts or path.suffix not in content_suffixes: continue try: text = path.read_text(encoding="utf-8") except UnicodeDecodeError: continue if turkish_specific.search(text) or todo.search(text): offenders.append(str(path.relative_to(SKILL_DIR))) if offenders: print(f"FAIL language/template-marker check: {', '.join(offenders)}", file=sys.stderr) return False print("PASS English-only and unfinished-marker checks.") return True def check_skill_size() -> bool: line_count = len((SKILL_DIR / "SKILL.md").read_text(encoding="utf-8").splitlines()) if line_count >= 500: print(f"FAIL SKILL.md has {line_count} lines; expected fewer than 500.", file=sys.stderr) return False print(f"PASS SKILL.md line-count guard ({line_count}/499).") return True def check_eval_inventory() -> bool: quality_text = QUALITY_SUITE.read_text(encoding="utf-8") failure_text = FAILURE_MODE_REGRESSIONS.read_text(encoding="utf-8") quality_case_count = len(re.findall(r"\| E\d\d\s+—", quality_text)) failure_case_count = len(re.findall(r"\| F\d\d\s+—", failure_text)) if quality_case_count < 10 or failure_case_count < 5: print( f"FAIL evaluation coverage has {quality_case_count} standard and " f"{failure_case_count} failure-mode cases; expected at least 10 and 5.", file=sys.stderr, ) return False print( f"PASS evaluation inventory declares {quality_case_count} standard and " f"{failure_case_count} failure-mode scenarios." ) return True def check_theme_contrast() -> bool: """Verify normal-size text contrast for every filled button interaction state.""" source = THEME_TEMPLATE.read_text(encoding="utf-8") color_re = re.compile( r"ImVec4\s+(?P<name>\w+)\s*=\s*ImVec4\(" r"(?P<r>[0-9.]+)f,\s*(?P<g>[0-9.]+)f,\s*(?P<b>[0-9.]+)f," ) colors = { match.group("name"): tuple(float(match.group(channel)) for channel in ("r", "g", "b")) for match in color_re.finditer(source) } required_backgrounds = ( "buttonSurface", "buttonSurfaceHover", "buttonSurfaceActive", "dangerSurface", "dangerSurfaceHover", "dangerSurfaceActive", ) missing = [name for name in ("contentPrimary", *required_backgrounds) if name not in colors] if missing: print(f"FAIL theme contrast tokens missing: {', '.join(missing)}", file=sys.stderr) return False def luminance(rgb: tuple[float, float, float]) -> float: channels = [ value / 12.92 if value <= 0.04045 else math.pow((value + 0.055) / 1.055, 2.4) for value in rgb ] return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2] foreground_luminance = luminance(colors["contentPrimary"]) failures: list[str] = [] for name in required_backgrounds: background_luminance = luminance(colors[name]) lighter = max(foreground_luminance, background_luminance) darker = min(foreground_luminance, background_luminance) contrast = (lighter + 0.05) / (darker + 0.05) if contrast < 4.5: failures.append(f"{name}={contrast:.2f}:1") if failures: print(f"FAIL filled-button text contrast below 4.5:1: {', '.join(failures)}", file=sys.stderr) return False print("PASS filled-button text contrast is at least 4.5:1 in every interaction state.") return True def compile_templates(imgui_dir: Path) -> bool: imgui_header = imgui_dir / "imgui.h" if not imgui_header.is_file(): print(f"FAIL {imgui_dir}: imgui.h not found.", file=sys.stderr) return False compiler = shutil.which("g++") or shutil.which("c++") if compiler is None: print("FAIL no C++ compiler found (expected g++ or c++).", file=sys.stderr) return False # Keep generated build inputs inside the writable skill workspace. Managed runners may # expose a readable system temp directory while denying child work-tree creation there. with tempfile.TemporaryDirectory(prefix=".imgui-skill-compile-", dir=SKILL_DIR) as temp_dir: temp = Path(temp_dir) shutil.copy2(PANEL_TEMPLATE, temp / "imgui_panel_skeleton.cpp") shutil.copy2(THEME_TEMPLATE, temp / "imgui_design_system.h") command = [ compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", f"-I{imgui_dir}", f"-I{temp}", "-c", str(temp / "imgui_panel_skeleton.cpp"), "-o", str(temp / "imgui_panel_skeleton.o"), ] return run(command, f"compile templates against {imgui_dir}") def compile_official_revisions() -> list[bool]: git = shutil.which("git") if git is None: print("FAIL git is required for --official-revisions.", file=sys.stderr) return [False] results: list[bool] = [] with tempfile.TemporaryDirectory(prefix=".imgui-skill-official-", dir=SKILL_DIR) as temp_dir: root = Path(temp_dir) for revision in OFFICIAL_IMGUI_REVISIONS: destination = root / revision.replace("/", "_") fetched = False for attempt in range(1, 4): if destination.exists(): shutil.rmtree(destination) fetched = run( [git, "clone", "--depth", "1", "--branch", revision, OFFICIAL_IMGUI_REPOSITORY, str(destination)], f"fetch official Dear ImGui {revision} (attempt {attempt}/3)", ) if fetched: break if attempt < 3: time.sleep(float(attempt)) results.append(fetched) if fetched: results.append(compile_templates(destination)) return results def main() -> int: parser = argparse.ArgumentParser(description="Run Dear ImGui UI/UX Engineering quality gates.") parser.add_argument( "--imgui-dir", type=Path, action="append", default=[], metavar="DIR", help="Directory containing the target project's imgui.h; may be supplied multiple times.", ) parser.add_argument( "--require-compile", action="store_true", help="Compatibility flag; official v1.92.0 and master compilation already run by default.", ) parser.add_argument( "--official-revisions", action="store_true", help="Compatibility flag; official v1.92.0 and master compilation already run by default.", ) parser.add_argument( "--skip-official-revisions", action="store_true", help="Explicit offline opt-out. Runs structural/semantic/static checks but is not a release gate.", ) parser.add_argument( "--semantic-responses", type=Path, metavar="FILE", help="Additionally score a target model's E01-E10/F01-F05 response JSON object.", ) args = parser.parse_args() checks = [ check_required_files(), check_agent_skills_frontmatter(), check_english_and_markers(), check_skill_size(), check_eval_inventory(), check_theme_contrast(), ] try: compile(CHECKER.read_text(encoding="utf-8"), str(CHECKER), "exec") print("PASS static checker syntax compiles.") except (OSError, SyntaxError) as error: print(f"FAIL static checker syntax: {error}", file=sys.stderr) checks.append(False) checks.append(run([sys.executable, str(CHECKER), str(PANEL_TEMPLATE), str(BALANCED_FIXTURE)], "static checker passes production template and balanced fixture")) checks.append(run([sys.executable, str(CHECKER), "--quiet", str(UNBALANCED_FIXTURE)], "static checker rejects intentionally unbalanced fixture", expect_success=False)) checks.append(run([sys.executable, str(SEMANTIC_RUNNER), "--cases", str(SEMANTIC_CASES), "--responses", str(SEMANTIC_RESPONSES)], "reference responses satisfy every semantic contract")) if args.semantic_responses is not None: checks.append(run([sys.executable, str(SEMANTIC_RUNNER), "--cases", str(SEMANTIC_CASES), "--responses", str(args.semantic_responses.resolve())], "target model responses satisfy every semantic contract")) if args.skip_official_revisions and args.require_compile and not args.imgui_dir: print("FAIL --require-compile cannot be combined with an offline-only run.", file=sys.stderr) checks.append(False) for imgui_dir in args.imgui_dir: checks.append(compile_templates(imgui_dir.resolve())) if args.skip_official_revisions: print("WARNING official compile regression explicitly skipped; this is not a release-gate result.") else: checks.extend(compile_official_revisions()) if all(checks): print("ALL AUTOMATED STRUCTURAL, SEMANTIC, AND COMPILE GATES PASSED") return 0 print("QUALITY GATES FAILED", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())scripts/run_semantic_suite.py4.9 KB49c3c89c1355upstream ↗
#!/usr/bin/env python3 """Deterministically score responses against the 15 semantic skill contracts.""" from __future__ import annotations import argparse import json import math import sys from collections import defaultdict from pathlib import Path SKILL_DIR = Path(__file__).resolve().parents[1] DEFAULT_CASES = SKILL_DIR / "evals" / "semantic-cases.json" DEFAULT_RESPONSES = SKILL_DIR / "evals" / "fixtures" / "reference-responses.json" def load_json(path: Path) -> object: try: return json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as error: raise ValueError(f"could not load {path}: {error}") from error def assertion_matches(response: str, assertion: dict[str, object]) -> bool: normalized = response.casefold() any_terms = [str(term).casefold() for term in assertion.get("any", [])] all_terms = [str(term).casefold() for term in assertion.get("all", [])] return (not any_terms or any(term in normalized for term in any_terms)) and all( term in normalized for term in all_terms ) def score_case(case: dict[str, object], response: str) -> tuple[int, list[str], list[str]]: normalized = response.casefold() fatal_hits = [str(term) for term in case.get("fatal", []) if str(term).casefold() in normalized] assertions = list(case.get("assertions", [])) missed = [ str(assertion.get("label", "unnamed assertion")) for assertion in assertions if not assertion_matches(response, assertion) ] if fatal_hits: return 0, missed, fatal_hits matched = len(assertions) - len(missed) if matched == len(assertions): return 2, missed, fatal_hits if matched >= math.ceil(len(assertions) / 2): return 1, missed, fatal_hits return 0, missed, fatal_hits def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--cases", type=Path, default=DEFAULT_CASES) parser.add_argument("--responses", type=Path, default=DEFAULT_RESPONSES) args = parser.parse_args() try: case_document = load_json(args.cases) responses = load_json(args.responses) except ValueError as error: print(f"FAIL {error}", file=sys.stderr) return 1 if not isinstance(case_document, dict) or not isinstance(responses, dict): print("FAIL cases and responses must be JSON objects.", file=sys.stderr) return 1 cases = case_document.get("cases", []) suites = case_document.get("suites", {}) if not isinstance(cases, list) or not isinstance(suites, dict): print("FAIL invalid semantic case schema.", file=sys.stderr) return 1 case_ids = [str(case.get("id", "")) for case in cases if isinstance(case, dict)] expected_ids = {f"E{index:02d}" for index in range(1, 11)} | {f"F{index:02d}" for index in range(1, 6)} if len(case_ids) != len(set(case_ids)) or set(case_ids) != expected_ids: print("FAIL semantic cases must contain exactly E01-E10 and F01-F05 once.", file=sys.stderr) return 1 missing_responses = sorted(expected_ids - set(responses)) extra_responses = sorted(set(responses) - expected_ids) if missing_responses or extra_responses: print( f"FAIL response ID mismatch; missing={missing_responses}, extra={extra_responses}", file=sys.stderr, ) return 1 totals: defaultdict[str, int] = defaultdict(int) zero_cases: list[str] = [] for case in cases: case_id = str(case["id"]) suite = str(case["suite"]) response = responses[case_id] if not isinstance(response, str) or not response.strip(): print(f"FAIL {case_id}: response must be a non-empty string.", file=sys.stderr) return 1 score, missed, fatal_hits = score_case(case, response) totals[suite] += score if score == 0: zero_cases.append(case_id) details: list[str] = [] if missed: details.append("missed=" + ", ".join(missed)) if fatal_hits: details.append("fatal=" + ", ".join(fatal_hits)) suffix = f" ({'; '.join(details)})" if details else "" print(f"{'PASS' if score == 2 else 'FAIL'} {case_id} score={score}/2{suffix}") passed = not zero_cases for suite_name, contract in suites.items(): required = int(contract["required_score"]) maximum = int(contract["maximum_score"]) actual = totals[suite_name] suite_passed = actual >= required passed = passed and suite_passed print(f"{'PASS' if suite_passed else 'FAIL'} {suite_name} semantic score={actual}/{maximum} required={required}") if zero_cases: print(f"FAIL zero-score cases: {', '.join(zero_cases)}", file=sys.stderr) if passed: print("ALL SEMANTIC CONTRACTS PASSED (30/30)") return 0 print("SEMANTIC CONTRACTS FAILED", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())references/design-playbook.md9.5 KB37cbb1b3c4fbupstream ↗
# Dear ImGui Design Playbook Read this reference only when detailed layout patterns, component contracts, UI copy, or a review rubric are needed. The core workflow and release gate are in `SKILL.md`. ## 1. Fast design brief Before writing code, fill in the following in a short paragraph or table. State any assumption explicitly. | Field | Decision to make | Example | |---|---|---| | User | Who uses the tool and at what level of expertise? | Technical artist, build engineer, live-operations analyst | | Primary task | What is the most frequent and valuable job? | Adjust shader parameters for the selected asset quickly | | Object scale | How many records, properties, or samples exist? | 10–50 settings, 10,000 assets, 60 telemetry samples per second | | Reversibility | Which actions are risky? | Delete asset, publish a live setting, batch-convert files | | Input | Which devices must work besides a mouse? | Keyboard, gamepad, remote session | | Viewing priority | Which area must remain dominant? | Central canvas, table, or timeline | | Density | Is the user discovering or producing? | Daily expert use: dense | ## 2. Layout recipes ### 2.1 Asset editor Use a left pane for hierarchy and filtering, a central canvas or list for the selected asset, a right inspector, and a bottom issue/log surface. Give the hierarchy search and visible selection. Give the inspector category headers, affected-object identity, and reset-to-default affordances. When selection changes, ensure the central pane and inspector are driven by the same model. **Success criterion:** Without searching, a user can distinguish the current selection, its type, and available editable properties at a glance. ### 2.2 Data or telemetry workspace Place time range, filters, and refresh controls at the top; chart or table in the center; legend or details on the right; query, error, and workflow messages at the bottom. Start from the last useful time range and a few critical series. Move fine detail into a tooltip, drill-down, or details pane rather than overwhelming the chart with legend entries. **Success criterion:** A user can tell what is current, failed, or filtered without interpretation ambiguity. ### 2.3 Job or queue panel For every job, show an understandable name, stage, progress, expected outcome, cancel/retry action, and error detail. Do not lock long-running work inside a modal. In an error row, show a summary, cause, and next action; place technical logs behind optional disclosure. **Success criterion:** A user never confuses queued, running, failed, and completed work, and knows how to recover a failed job. ### 2.4 Scene or canvas tool Make the central canvas dominant. Use the left pane for tools and hierarchy, the right pane for inspection, the top bar for mode/tool switching, and the bottom for status, coordinates, or selection. Signal modes with text, icon, and/or status chip, not color alone. Make mouse operations explicitly cancellable with Escape, right-click, or a clear Cancel action. **Success criterion:** The user can always identify the active tool mode, selection scope, and likely result of the next action. ## 3. State matrix Design the following states deliberately. Non-default states often determine whether a tool feels production-ready. | State | Visual signal | Behavior | Example copy | |---|---|---|---| | Empty | Calm surface, concise explanation, one starting action | Guide the user forward | `No assets yet. Import your first asset.` | | No filter result | Filter summary and clear action | Preserve data; make clearing the filter easy | `No results for “metal”. Clear filter.` | | Loading | Inline progress, skeleton, or percentage | Preserve safe interaction; show cancel if available | `Building preview — 64%` | | Success | Brief, actionable confirmation | Offer undo when relevant | `42 assets tagged. Undo` | | Error | Clear error surface, cause, safe next step | Keep technical details expandable | `Import could not finish. Check the file path.` | | Disabled | Muted treatment and reason | Do not trigger the action | `Select a target before publishing.` | | Destructive confirmation | Target name/count, impact, reversibility | Safe default and explicit verb | `Delete “Forest” collection? This cannot be undone.` | ## 4. Component contracts ### Table and asset browser Keep the identifier/name, primary state, and the one to three supporting fields that drive a user's decision visible. Define column priority; hide low-priority columns or move them to the details pane in narrow space. Show readable sort direction, active-filter summary, and a selected row with clear but restrained contrast. **Behavior:** If single, multiple, and range selection are supported, make their rules consistent. Context menu, row action, and keyboard focus must address the same target object. Build the filtered index first, process `ImGuiTableSortSpecs` on that index, then render it with `ImGuiListClipper` at scale. ### Inspector Group fields by the user's mental model: Transform, Appearance, Physics, Build Settings, and similar categories. For each editable field, state the unit, valid range, mixed-value state, and change scope. Make reset fast but not easy to trigger accidentally. **Behavior:** If a dragged value previews live, create the command/undo entry when dragging ends. In a multi-selection, display non-common values as mixed or blank; never silently impose the first object's value. ### Command palette Design the command palette for keyboard use. Focus the search field when it opens. Display matches with command name, concise description, category, and shortcut. Make recent/frequent commands available with an empty search query. **Behavior:** Escape closes it, Enter runs the selected command, and arrow keys move through results. Use a visible second safety step for destructive commands rather than executing them immediately. ### Metric card A card contains value, name, time context, and directional information. Show a trend only when a meaningful comparison period exists. If a card is clickable, make that affordance visible and navigate to the associated detail view. **Avoid:** Turning every value into a card, using charts as ornamental filler, or relying on red and green as the only semantic cue. ### Modal, popup, and toast Use a modal for a short decision. The title should state verb and target, with explicit primary and cancel actions. Use a popup for contextual settings or small action groups, not as a replacement for the central work area. Use a toast for brief success feedback and undo; show safety, connection, and data-loss failures on a persistent surface as well. ## 5. Visual-token decisions ### Recommended naming ```cpp // surface: panel backgrounds; content: text; accent: focus and primary actions; semantic: state namespace ToolColor { constexpr ImVec4 SurfaceBase; constexpr ImVec4 SurfaceRaised; constexpr ImVec4 SurfaceOverlay; constexpr ImVec4 BorderSubtle; constexpr ImVec4 BorderStrong; constexpr ImVec4 ContentPrimary; constexpr ImVec4 ContentMuted; constexpr ImVec4 Accent; constexpr ImVec4 AccentHover; constexpr ImVec4 Success; constexpr ImVec4 Warning; constexpr ImVec4 Danger; } ``` Do not apply the same `Danger` token at arbitrary strengths to an error icon, delete button, and alarm message. Keep the token's meaning and allowed uses stable. Check contrast against a 4.5:1 target for normal text and 3:1 target for large text. [1] ### Spacing and density Choose a base scale of `4` or `5` px. Derive `FramePadding`, `ItemSpacing`, `CellPadding`, `WindowPadding`, and heading gaps from multiples of that scale. Do not increase density merely by shrinking text; preserve priority and row rhythm. ## 6. Technical review rubric | Area | Symptom to look for | Correction | |---|---|---| | Identity | Repeated label in a loop, random index, state loss in a changing title | Use a stable object ID with `PushID`, `##`, or `###`. [2] | | Focus | Selected row takes focus again on every frame | Request default focus only after explicit programmatic navigation or selection. | | Nullable text | Pointer-backed model field reaches `Selectable`, `TextUnformatted`, or `strcmp` without a guarantee | Document a non-null invariant or render through a null-safe helper with meaningful fallbacks. | | Stack | Conditional `PopStyleColor`, skipped `End`, unbalanced `PushID` | Pair every branch; consider scope guards/helpers. | | State | Two copies of the same data in UI and application model | Keep one model source; limit temporary UI state. | | Input | Underlying application shortcut fires while a UI control is active | Forward raw input to ImGui and separate application routing with capture signals. [2] | | Large data | Stutter while scrolling, every row rebuilt each frame | Use filtered/sorted index views, `ImGuiListClipper`, and visible-geometry generation. | | DPI | Tiny spacing/text, blurry fonts, or two systems writing `FontScaleDpi` | Reset style before `ScaleAllSizes()`; select either host-managed font scale or docking-branch `ConfigDpiScaleFonts`, never both. [3] | | Error flow | Silent failure, disappearing toast, no recovery | Add persistent error summary and retry/cancel/undo action. | | Visual | Ambiguous color meaning, low contrast, long-text overflow | Use tokens, contrast checks, text truncation/tooltip, and narrow-width tests. | ## References [1] [W3C WCAG 2.2: Understanding Contrast (Minimum)](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) [2] [Dear ImGui FAQ: ID system and input capture](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) [3] [Dear ImGui: fonts and DPI](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md)references/version-notes.md4.1 KB3afae2befd75upstream ↗
# Dear ImGui Compatibility Notes Read this file before copying a template into a project with a pinned or vendored Dear ImGui revision. Treat the project's local `imgui.h` as the final authority: compile against it, call `IMGUI_CHECKVERSION()`, and prefer feature/branch checks over assumptions derived from a version label. ## Tested baseline and validation method The templates are compiled in this skill against the official **v1.92.0** tag and the then-current official `master` checkout. The code includes a numeric `IMGUI_VERSION_NUM >= 19200` guard because its font/DPI implementation depends on the 1.92 API surface. That guard is a baseline, not proof that an arbitrary vendor fork carries every optional feature. | API or behavior | v1.92.0 official master tag | Current official master checked for this skill | Docking branch | Template treatment | |---|---|---|---|---| | `IMGUI_VERSION_NUM` | `19200` | Version is expected to advance | Present | Require `>= 19200`; compile against the vendored header. | | `ImGuiStyle::FontScaleDpi` | Present | Present | Present | Use only through the explicit `FontDpiPolicy`. | | `ImGuiStyle::ScaleAllSizes()` | Available public style API | Available | Available | Reset style, then apply once at startup or after a confirmed scale change. | | `ImGuiCol_TabSelected` | Present | Present | Present | Used by the theme. | | `ImGuiCol_TabSelectedOverline` | Present | Present | Present | Used by the theme; let the template's version guard and real project compilation reject unsupported forks. | | `ImGuiTableSortSpecs` / `TableGetSortSpecs()` | Present | Present | Present | Use to sort the model/index view, not merely table headers. | | `ImGuiListClipper` | Present | Present | Present | Use for large filtered/sorted lists. | | `IMGUI_HAS_DOCK` | Not a master-branch promise | Not a master-branch promise | Defined | Guard all docking-only names with this macro. | | `ImGui::DockSpaceOverViewport()` | Not a master-branch promise | Not a master-branch promise | Present | Compile only behind `IMGUI_HAS_DOCK`; submit before hosted windows. | | `io.ConfigDpiScaleFonts` | Not a master-branch promise | Not a master-branch promise | Present and experimental | Do not set `FontScaleDpi` manually when this configuration owns it. | | `io.ConfigDpiScaleViewports` | Not a master-branch promise | Not a master-branch promise | Present and experimental | Treat as a host/platform integration choice; verify against the docking branch. | > **Rule:** A numeric version check can establish a minimum baseline, but it cannot prove the availability of docking-branch symbols in a custom fork. Guard optional APIs by branch capability and compile the final code against the project's local Dear ImGui headers. ## Integration checklist Run these checks before adopting the templates: 1. Compare the project's `IMGUI_VERSION_NUM` with the template baseline. 2. Search the vendored `imgui.h` for every optional enum or function used by the copied template. 3. If `IMGUI_HAS_DOCK` is absent, keep the non-docking workspace path and do not call `DockSpaceOverViewport()`. 4. Select one `FontScaleDpi` owner: the host or the docking branch's `ConfigDpiScaleFonts`; do not let both write the value. 5. Compile with warnings enabled, run the project's Dear ImGui demo/metrics window, and visually test target DPI scales. ## Sources and provenance The v1.92.0 tag's `imgui.h` defines `IMGUI_VERSION_NUM` as `19200` and contains `FontScaleDpi`, `ImGuiCol_TabSelected`, and `ImGuiCol_TabSelectedOverline`. The current docking branch defines `IMGUI_HAS_DOCK`, `DockSpaceOverViewport()`, `ConfigDpiScaleFonts`, and `ConfigDpiScaleViewports`. Dear ImGui's font documentation describes `FontScaleDpi` and `ScaleAllSizes()` for DPI handling, while the docking documentation describes the dockspace submission rules. [1] [2] [3] [4] [1] [Dear ImGui v1.92.0 tag: `imgui.h`](https://github.com/ocornut/imgui/blob/v1.92.0/imgui.h) [2] [Dear ImGui docking branch: `imgui.h`](https://github.com/ocornut/imgui/blob/docking/imgui.h) [3] [Dear ImGui: using fonts and DPI](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) [4] [Dear ImGui docking wiki](https://github.com/ocornut/imgui/wiki/Docking)references/worked-example.md4.9 KBe09f04e5d45fupstream ↗
# Worked Example: Asset Browser Review Read this file when producing a design review, a before/after recommendation, or a structured output for a crowded C++ editor panel. Adapt the structure to the task; do not copy its domain details blindly. ## Input request > Review this Dear ImGui asset browser. It feels crowded, slows down with many assets, and selection sometimes behaves strangely. Give me a practical redesign and focused code fixes. ```cpp ImGui::Begin("Assets"); for (Asset& asset : assets) { if (ImGui::Button(asset.name)) selected = &asset; ImGui::SameLine(); ImGui::Text("%s | %s", asset.type, asset.status); } ImGui::End(); ``` ## Expected review output # Asset Browser Review ## Executive assessment The panel has three high-impact defects. It uses the visible asset name as the widget ID, so duplicate names collide. It creates one horizontal button/text row per asset without clipping, so large collections perform unnecessary per-frame work. It also lacks filtering, sorting, visible row selection, and an empty-result state; as a result, the user cannot scan or recover from a crowded view efficiently. ## Findings | Priority | Evidence | Impact | Recommended correction | Verification | |---|---|---|---|---| | High | `Button(asset.name)` uses a potentially duplicate visible label as the ID. | Clicking or state handling can target the wrong asset. | Wrap each row in `PushID(asset.id)`/`PopID()` and use the stable ID. | Add two assets with the same name; each remains independently selectable. | | High | Every asset is emitted on every frame. | Scrolling becomes costly as asset count grows. | Filter/sort an index view, then render visible rows with `ImGuiListClipper`. | Profile 10,000 assets; visible-row work scales with viewport height. | | Medium | Button list has no persistent selected-row treatment. | The current context is difficult to scan. | Use `Selectable` with row spanning and a right-side inspector. | Keyboard and pointer selection remain visible after scrolling. | | Medium | No filter/no-result flow exists. | Users cannot narrow a large collection or understand an empty view. | Add search, active-filter feedback, and a clear-filter affordance. | A no-match query presents recovery text and Clear. | ## Proposed interaction model Use a three-region workspace. The left/central asset browser contains a search field and table. Its first column exposes name and selection, while Type and Status support sorting. The right inspector displays selected-asset properties. The table preserves row identity through `asset.id`; the model owns selection as `selectedAssetId` rather than retaining a raw element pointer. The browser must compute a stable filtered/sorted index list. It should handle normal data, no filter result, and no selection explicitly. Pointer selection updates selection without forcibly taking keyboard focus. A command or explicit navigation action can request focus by setting a pending focus ID. ## Focused implementation outline ```cpp // Application model: do not retain a pointer into a vector that may reallocate. int selectedAssetId = -1; std::vector<int> filteredSortedAssetIndices; // 1. Rebuild the index list only when data, filter, or sort specs change. // 2. In BeginTable(), call TableGetSortSpecs() and sort the index list. // 3. Use ImGuiListClipper over filteredSortedAssetIndices. // 4. For every visible row: ImGui::PushID(asset.id); if (ImGui::Selectable(SafeText(asset.name, "<Unnamed asset>"), selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap)) { RequestAssetSelection(ui, asset.id); // Pointer selection: no forced keyboard focus. } ImGui::PopID(); ``` Use `templates/imgui_panel_skeleton.cpp.in` for the complete implementation pattern, including null-safe display strings, table sort handling, clipping, and explicit focus-transfer requests. ## Acceptance checks | Scenario | Expected result | |---|---| | Two assets share a display name | Each row has independent input/state because `asset.id` owns the widget scope. | | 10,000 assets with a narrow viewport | Only visible filtered/sorted rows are emitted. | | Filter matches no assets | User sees a no-results message and can clear the filter. | | Selection arrives from a command palette | The requested row becomes default keyboard focus once it is visible. | | A data source provides null name/type/status | UI renders fallback text and does not pass null to `strcmp`, `Selectable`, or text widgets. | | Project uses a non-docking Dear ImGui build | Browser and inspector work; dockspace code remains excluded. | ## Output conventions illustrated The review gives an assessment before recommendations, classifies findings by priority, includes code evidence, distinguishes design behavior from implementation work, and ends with testable acceptance checks. Use this structure for reviews. For a new-screen request, begin with the user/task model and state matrix instead of an issue table..gitignore92 B3860d5801515upstream ↗
__pycache__/ *.py[cod] .imgui-skill-compile-*/ .imgui-skill-official-*/ .DS_Store Thumbs.dbagents/openai.yaml1.1 KB02702ad134ebupstream ↗
interface: display_name: "Dear ImGui UI/UX Engineering" short_description: "Design, review, and harden production-quality Dear ImGui and C++ tool UIs" default_prompt: >- Use $imgui-ui-ux-engineering when the task names Dear ImGui or supplies direct evidence such as `ImGui::`, `imgui.h`, `ImGuiContext`, or ImGui backend symbols. If a C++ editor/tooling UI is unlabelled, keep framework choice open unless the user explicitly asks whether Dear ImGui is suitable. Do not apply it to a task that explicitly names another UI framework. First classify the work as a new workspace design, an existing-UI review, a component implementation, or a theme/design-system task. Then apply the appropriate workflow: specify task hierarchy and states for new designs; provide evidence, priority, correction, and verification for reviews; define behavior, IDs, focus, error states, and performance for components; or centralize semantic tokens, contrast, DPI, and interaction states for themes. Verify version-sensitive APIs against the project's vendored Dear ImGui headers and use the bundled quality harness when source is available.evals/failure-mode-regressions.md3.8 KB8b60551c6a39upstream ↗
# Failure-Mode Regression Cases Use these cases in addition to `quality-suite.md` when revising the skill or evaluating a model response. They are anonymized, concrete reproductions of recurring practitioner failure patterns; they do **not** claim to represent one identifiable product or user. A passing response must diagnose the root cause, propose a safe corrective pattern, and state a verification method rather than merely describing a more attractive layout. | ID | Incident-style prompt | Root failure to detect | Minimum passing assertions | |---|---|---|---| | F01 — stale filtered view | `My Asset Browser's search box accepts input, but results often remain unchanged until I change sort order. The filtered vector is rebuilt only after clicking a table header.` | UI state changed but the derived filtered/sorted index view was not invalidated. | The response invalidates/rebuilds the derived view on filter, data, and sort-spec changes; does not reorder the source model merely to render a view; defines a no-results state and a reproduction test. | | F02 — dangling inspector selection | `After an importer refresh, clicking the inspector sometimes edits the wrong asset or crashes. I store Asset* selectedAsset and the importer replaces a std::vector<Asset>.` | A retained pointer becomes invalid after vector replacement/reallocation. | The response stores a stable asset ID in UI state, resolves the live model object at render/action time, handles a missing selection safely, and verifies refresh plus deletion behavior. | | F03 — collapsed child stack mismatch | `I wrote: if (ImGui::BeginChild("Log")) { DrawLog(); ImGui::EndChild(); } and now DebugCheckVersionAndDataLayout asserts intermittently.` | `EndChild()` is incorrectly conditional on `BeginChild()` returning true. | The response moves `EndChild()` outside the conditional, explains the Begin/End contract, checks other scoped APIs independently, and recommends the bundled checker plus runtime metrics/debug validation. | | F04 — selection steals navigation focus | `Arrow-key navigation feels broken after I click any asset. I call SetItemDefaultFocus() whenever row.id == selectedAssetId.` | Default focus is asserted every frame instead of on one explicit navigation request. | The response separates pointer selection from programmatic focus transfer, uses a pending stable ID or equivalent one-shot state, preserves keyboard navigation, and tests command-palette selection versus pointer selection. | | F05 — DPI and status rendering drift | `At 200% DPI, text grows but rows stay cramped. On another monitor it grows again after every theme reload. Status colors are also different between the table and inspector.` | Multiple scale owners/cumulative `ScaleAllSizes()` calls and duplicated hard-coded status colors. | The response resets style before non-cumulative size scaling, selects exactly one owner for `FontScaleDpi`, distinguishes font versus metric scaling, centralizes semantic status tokens, and validates on at least two DPI values. | ## Evaluation protocol For each failure case, score the answer from 0 to 2. Award `0` when the root cause is absent or the proposed change is unsafe. Award `1` when the diagnosis is correct but either verification or a necessary Dear ImGui implementation detail is missing. Award `2` only when the response satisfies every listed assertion and clearly distinguishes model state, derived view state, and transient UI state where relevant. A release candidate must earn 10/10 across F01–F05, with no zero. Treat any recommendation that keeps a raw `std::vector` element pointer across a model refresh, conditionally omits a required `End*`, or writes `FontScaleDpi` from two owners as an automatic failure. The executable assertions are maintained in `semantic-cases.json` and run by `scripts/run_semantic_suite.py`.evals/quality-suite.md5.6 KB24c2b3fea262upstream ↗
# Dear ImGui UI/UX Engineering Evaluation Suite Use this suite after significant changes to the skill. Each case tests triggering behavior and output quality. The deterministic contracts live in `semantic-cases.json`; do not grade stylistic verbosity alone. ## Evaluation protocol Run every prompt with no extra context unless the case supplies code. Mark an assertion as pass only when the response makes the requirement explicit, provides an equivalent technically correct alternative, or clearly explains why the requirement is not applicable. A response fails a case if it gives only generic UI advice where the requested ImGui-specific reasoning is needed. Run `failure-mode-regressions.md` alongside this suite to test incident-style state, scope, focus, and DPI failures. | ID | Trigger prompt | Required assertions | |---|---|---| | E01 — Unlabelled framework restraint | `My C++ editor panel is overcrowded. It has a tree on the left, a viewport, and many properties on the right. How should I redesign it?` | The skill should not claim that Dear ImGui is in use when neither Dear ImGui nor direct API/header evidence is supplied. It should keep framework choice open and apply this skill only if the user explicitly asks whether Dear ImGui is suitable. | | E02 — Asset browser | `Design a Dear ImGui asset browser for 20,000 records. Users need text filtering, sorting, single selection, and a property inspector.` | The answer uses a stable model ID, filtered/sorted index view, `ImGuiTableSortSpecs`, and `ImGuiListClipper`. It specifies no-results behavior, selection ownership, and a verification plan. | | E03 — Duplicate-ID review | `Review this loop: for (auto& item : items) ImGui::Checkbox(item.name.c_str(), &item.enabled);` | The answer calls out duplicate visible labels/ID collisions, recommends `PushID(item.id)` or an equivalent stable-ID method, and distinguishes a visible label from a unique ID. | | E04 — Stack-balance review | `I call PushStyleColor inside if (warning) and PopStyleColor after the if. Is this safe?` | The answer identifies branch-dependent stack imbalance, gives a balanced correction, and includes a verification step. It should not claim that superficial visual testing alone is sufficient. | | E05 — DPI and docking | `My docking-branch tool moves between 100% and 200% DPI monitors. Should I set FontScaleDpi and ConfigDpiScaleFonts?` | The answer states that there must be one `FontScaleDpi` owner, describes the docking-branch automatic option, addresses size/padding scaling separately, and points to `references/version-notes.md` or asks the user to verify vendored headers. | | E06 — Null-safe model review | `Our asset importer can emit null name, type, and status pointers. Make this ImGui row safe.` | The answer avoids passing null to `strcmp`, `Selectable`, `TextUnformatted`, or formatted `%s` output. It proposes a documented non-null invariant or a safe display adapter with meaningful fallback text. | | E07 — Focus transfer | `When a command palette selects an asset, keyboard focus should move to it, but clicking a row must not steal focus every frame.` | The answer distinguishes pointer selection from explicit programmatic focus request, uses a pending focus ID or equivalent one-shot mechanism, and warns against unconditional `SetItemDefaultFocus()` for the selected row. | | E08 — Theme request | `Create a dark Dear ImGui theme with a strong blue accent and destructive actions.` | The answer centralizes semantic tokens, includes normal/hover/active/disabled treatments, checks text contrast, avoids scattered hard-coded component colors, and labels any API/version assumption. | | E09 — Custom component | `Build a custom timeline scrubber with ImDrawList.` | The answer evaluates whether standard widgets suffice, then specifies ID, hit area, hover/active/focus/disabled behavior, drag cancellation, clipping/performance, and keyboard or alternative interaction. | | E10 — Non-docking compatibility | `I need the asset workspace to compile with a standard non-docking Dear ImGui build.` | The answer omits or guards docking-only APIs, preserves functional independent windows, and does not claim a master build always defines `IMGUI_HAS_DOCK`. | ## Regression gates A skill revision is acceptable only when all ten standard cases and all five failure-mode cases pass, and when the following package checks also pass: 1. `scripts/check_imgui_cpp.py` can detect an intentionally unbalanced `PushID`/`PopID` fixture and return a nonzero exit code. 2. The same checker reports no error on the bundled panel template. 3. `python3 scripts/run_quality_suite.py` fetches temporary official `v1.92.0` and `master` sources by default, then compiles the panel template with warnings enabled against both. 4. Product CI additionally supplies `--imgui-dir /path/to/vendored/imgui` to compile against its own fork/pinned revision. 5. `SKILL.md` remains below 500 lines and points to version notes, the worked example, the evaluator, and the deterministic checker at the moment those resources are needed. The bundled reference responses must score a perfect 30/30 with `python3 scripts/run_semantic_suite.py`. To gate a target model, store its E01-E10 and F01-F05 responses in the same JSON-object format as `evals/fixtures/reference-responses.json`, then run `python3 scripts/run_quality_suite.py --semantic-responses RESPONSES.json`. ## Suggested scoring Score each case from 0 to 2: `0` for absent or unsafe behavior, `1` for partial/general guidance, and `2` for a concrete, technically correct, verifiable response. The release gate requires a perfect 20/20 standard score and 10/10 failure-mode score with no zero.evals/semantic-cases.json9.8 KBb694cfafcde4upstream ↗
{ "schema_version": 1, "suites": { "standard": {"required_score": 20, "maximum_score": 20}, "failure": {"required_score": 10, "maximum_score": 10} }, "cases": [ { "id": "E01", "suite": "standard", "prompt": "My C++ editor panel is overcrowded. It has a tree on the left, a viewport, and many properties on the right. How should I redesign it?", "assertions": [ {"label": "keeps framework choice open", "any": ["framework choice open", "framework is not established"]}, {"label": "requires evidence or suitability request", "any": ["direct api/header evidence", "explicit suitability question", "explicitly asks whether dear imgui is suitable"]} ], "fatal": ["dear imgui is definitely", "use dear imgui because"] }, { "id": "E02", "suite": "standard", "prompt": "Design a Dear ImGui asset browser for 20,000 records. Users need text filtering, sorting, single selection, and a property inspector.", "assertions": [ {"label": "stable ID", "any": ["stable asset id", "stable model id"]}, {"label": "derived index view", "any": ["filtered/sorted index view", "filtered and sorted index view"]}, {"label": "sort specs", "any": ["imguitablesortspecs"]}, {"label": "clipper", "any": ["imguilistclipper"]}, {"label": "no-results state", "any": ["no-results", "no results"]}, {"label": "selection ownership", "any": ["ui state owns selection", "selection is owned by ui state"]}, {"label": "verification", "any": ["verify", "test"]} ] }, { "id": "E03", "suite": "standard", "prompt": "Review this loop: for (auto& item : items) ImGui::Checkbox(item.name.c_str(), &item.enabled);", "assertions": [ {"label": "collision", "any": ["id collision", "duplicate visible labels"]}, {"label": "stable PushID", "any": ["pushid(item.id)", "pushid with a stable"]}, {"label": "visible versus unique", "any": ["visible label", "unique id"]} ] }, { "id": "E04", "suite": "standard", "prompt": "I call PushStyleColor inside if (warning) and PopStyleColor after the if. Is this safe?", "assertions": [ {"label": "branch imbalance", "any": ["branch-dependent stack imbalance", "underflows when warning is false"]}, {"label": "balanced correction", "any": ["push and pop inside the same branch", "keep push/pop in the same branch"]}, {"label": "verification", "any": ["bundled checker", "runtime debug", "metrics/debug"]} ], "fatal": ["safe as written"] }, { "id": "E05", "suite": "standard", "prompt": "My docking-branch tool moves between 100% and 200% DPI monitors. Should I set FontScaleDpi and ConfigDpiScaleFonts?", "assertions": [ {"label": "one owner", "any": ["one fontscaledpi owner", "exactly one owner"]}, {"label": "automatic docking option", "any": ["configdpiscalefonts can own", "configdpiscalefonts automatically"]}, {"label": "metric scaling", "any": ["scaleallsizes", "size and padding scaling"]}, {"label": "version verification", "any": ["version-notes.md", "vendored imgui.h", "vendored headers"]} ], "fatal": ["set both fontscaledpi and configdpiscalefonts"] }, { "id": "E06", "suite": "standard", "prompt": "Our asset importer can emit null name, type, and status pointers. Make this ImGui row safe.", "assertions": [ {"label": "blocks null API input", "any": ["never pass null", "do not pass null"]}, {"label": "names risky APIs", "all": ["strcmp", "selectable", "textunformatted", "%s"]}, {"label": "adapter or invariant", "any": ["safe display adapter", "non-null invariant"]}, {"label": "fallback", "any": ["fallback text", "<unnamed>", "unknown"]} ] }, { "id": "E07", "suite": "standard", "prompt": "When a command palette selects an asset, keyboard focus should move to it, but clicking a row must not steal focus every frame.", "assertions": [ {"label": "separates interaction sources", "any": ["pointer selection separate", "separate pointer selection"]}, {"label": "one-shot pending ID", "any": ["pending stable id", "pending focus id", "one-shot"]}, {"label": "avoids repeated focus", "any": ["not every frame", "do not call setitemdefaultfocus for every selected row"]}, {"label": "verification", "any": ["test command-palette", "test both"]} ] }, { "id": "E08", "suite": "standard", "prompt": "Create a dark Dear ImGui theme with a strong blue accent and destructive actions.", "assertions": [ {"label": "semantic tokens", "any": ["semantic tokens", "centralized tokens"]}, {"label": "interaction states", "all": ["normal", "hover", "active", "disabled"]}, {"label": "contrast", "any": ["4.5:1", "contrast"]}, {"label": "no scattered constants", "any": ["no scattered hard-coded", "avoid scattered hard-coded"]}, {"label": "version assumption", "any": ["version assumption", "imgui_version_num"]} ] }, { "id": "E09", "suite": "standard", "prompt": "Build a custom timeline scrubber with ImDrawList.", "assertions": [ {"label": "standard-widget assessment", "any": ["first check whether standard widgets", "evaluate standard widgets first"]}, {"label": "identity and hit area", "all": ["stable id", "hit area"]}, {"label": "states", "all": ["hover", "active", "focus", "disabled"]}, {"label": "cancellation", "any": ["drag cancellation", "cancel drag"]}, {"label": "performance", "all": ["clipping", "performance"]}, {"label": "keyboard", "any": ["keyboard", "alternative interaction"]} ] }, { "id": "E10", "suite": "standard", "prompt": "I need the asset workspace to compile with a standard non-docking Dear ImGui build.", "assertions": [ {"label": "guards docking", "any": ["guard docking-only api", "#if defined(imgui_has_dock)"]}, {"label": "fallback windows", "any": ["independent windows remain functional", "functional independent windows"]}, {"label": "no master assumption", "any": ["master does not guarantee imgui_has_dock", "master build does not guarantee"]} ] }, { "id": "F01", "suite": "failure", "prompt": "My Asset Browser's search box accepts input, but results often remain unchanged until I change sort order. The filtered vector is rebuilt only after clicking a table header.", "assertions": [ {"label": "invalidates all inputs", "all": ["filter", "data", "sort-spec"]}, {"label": "derived view", "any": ["rebuild the derived index view", "invalidate the derived view"]}, {"label": "preserves source model", "any": ["do not reorder the source model", "without reordering the source model"]}, {"label": "empty state", "any": ["no-results", "no results"]}, {"label": "reproduction", "any": ["reproduction test", "test typing"]} ] }, { "id": "F02", "suite": "failure", "prompt": "After an importer refresh, clicking the inspector sometimes edits the wrong asset or crashes. I store Asset* selectedAsset and the importer replaces a std::vector<Asset>.", "assertions": [ {"label": "stable selection ID", "any": ["store a stable asset id", "stable id in ui state"]}, {"label": "live resolution", "any": ["resolve the live object", "resolve it against the live model"]}, {"label": "missing selection", "any": ["missing selection", "clear selection safely"]}, {"label": "verification", "all": ["refresh", "deletion"]} ], "fatal": ["keep the asset*", "retain the pointer"] }, { "id": "F03", "suite": "failure", "prompt": "I wrote: if (ImGui::BeginChild(\"Log\")) { DrawLog(); ImGui::EndChild(); } and now DebugCheckVersionAndDataLayout asserts intermittently.", "assertions": [ {"label": "unconditional EndChild", "any": ["endchild outside the conditional", "endchild must always run"]}, {"label": "contract", "any": ["begin/end contract", "beginchild return value only controls contents"]}, {"label": "other scopes", "any": ["audit other scoped api", "check other scoped api"]}, {"label": "verification", "all": ["bundled checker", "runtime"]} ], "fatal": ["endchild only when beginchild returns true"] }, { "id": "F04", "suite": "failure", "prompt": "Arrow-key navigation feels broken after I click any asset. I call SetItemDefaultFocus() whenever row.id == selectedAssetId.", "assertions": [ {"label": "separates pointer and programmatic", "any": ["separate pointer selection", "pointer selection separate"]}, {"label": "one-shot stable ID", "any": ["pending stable id", "one-shot focus id"]}, {"label": "preserves navigation", "any": ["preserves keyboard navigation", "do not reassert focus every frame"]}, {"label": "verification", "all": ["command-palette", "pointer"]} ] }, { "id": "F05", "suite": "failure", "prompt": "At 200% DPI, text grows but rows stay cramped. On another monitor it grows again after every theme reload. Status colors are also different between the table and inspector.", "assertions": [ {"label": "non-cumulative reset", "any": ["reset style before scaleallsizes", "reset style before non-cumulative scaling"]}, {"label": "one font owner", "any": ["exactly one fontscaledpi owner", "one fontscaledpi owner"]}, {"label": "font versus metrics", "any": ["font scaling from metric scaling", "font versus metric scaling"]}, {"label": "semantic status tokens", "any": ["centralize semantic status tokens", "centralized semantic status colors"]}, {"label": "two DPI tests", "any": ["100% and 200%", "two dpi values"]} ], "fatal": ["call scaleallsizes every frame", "two fontscaledpi owners"] } ] }LICENSE1.0 KB5534d6d89362upstream ↗
MIT License Copyright (c) 2026 muhosekerci Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.templates/imgui_design_system.h.in8.5 KBa2744d4914d0upstream ↗
#pragma once // Dear ImGui tool-interface theme starter. // Target: Dear ImGui 1.92.0 or newer. Verify every API against the exact vendored revision. // Call ApplyToolTheme() during initialization and whenever the host reports a DPI-scale change. // Do not call it every frame. #include "imgui.h" #include <algorithm> #if !defined(IMGUI_VERSION_NUM) || IMGUI_VERSION_NUM < 19200 # error "imgui_design_system.h requires Dear ImGui 1.92.0 or newer." #endif namespace ToolUi { struct Metrics { float unit = 4.0f; float radiusSmall = 4.0f; float radiusMedium = 6.0f; float border = 1.0f; [[nodiscard]] ImVec2 framePadding() const { return {unit * 2.0f, unit * 1.35f}; } [[nodiscard]] ImVec2 itemSpacing() const { return {unit * 1.5f, unit * 1.5f}; } [[nodiscard]] ImVec2 cellPadding() const { return {unit * 2.0f, unit * 1.25f}; } }; // Choose one owner for FontScaleDpi. On the docking branch, ConfigDpiScaleFonts can // automatically overwrite FontScaleDpi as windows move across monitors. In that mode, // select DearImGuiManagedFonts; this template still owns size and padding scaling. enum class FontDpiPolicy { HostManagedFonts, DearImGuiManagedFonts, }; // Example dark palette. Validate brand colors and contrast against actual content. // Target at least 4.5:1 contrast for normal text and 3:1 for large text. struct Colors { ImVec4 surfaceBase = ImVec4(0.055f, 0.070f, 0.095f, 1.0f); ImVec4 surfaceRaised = ImVec4(0.080f, 0.100f, 0.135f, 1.0f); ImVec4 surfaceOverlay = ImVec4(0.115f, 0.140f, 0.185f, 1.0f); ImVec4 borderSubtle = ImVec4(0.190f, 0.225f, 0.280f, 0.72f); ImVec4 borderStrong = ImVec4(0.335f, 0.405f, 0.500f, 0.95f); ImVec4 contentPrimary = ImVec4(0.925f, 0.950f, 0.985f, 1.0f); ImVec4 contentSecondary = ImVec4(0.655f, 0.710f, 0.790f, 1.0f); ImVec4 contentDisabled = ImVec4(0.410f, 0.455f, 0.520f, 1.0f); ImVec4 accent = ImVec4(0.235f, 0.635f, 1.000f, 1.0f); ImVec4 accentHover = ImVec4(0.370f, 0.720f, 1.000f, 1.0f); ImVec4 accentActive = ImVec4(0.130f, 0.480f, 0.890f, 1.0f); // Filled controls use darker semantic surfaces so contentPrimary remains >= 4.5:1. ImVec4 buttonSurface = ImVec4(0.055f, 0.300f, 0.580f, 1.0f); ImVec4 buttonSurfaceHover = ImVec4(0.065f, 0.340f, 0.640f, 1.0f); ImVec4 buttonSurfaceActive = ImVec4(0.040f, 0.250f, 0.500f, 1.0f); ImVec4 success = ImVec4(0.250f, 0.805f, 0.545f, 1.0f); ImVec4 warning = ImVec4(1.000f, 0.700f, 0.240f, 1.0f); ImVec4 danger = ImVec4(1.000f, 0.345f, 0.355f, 1.0f); ImVec4 dangerSurface = ImVec4(0.620f, 0.120f, 0.150f, 1.0f); ImVec4 dangerSurfaceHover = ImVec4(0.720f, 0.140f, 0.170f, 1.0f); ImVec4 dangerSurfaceActive = ImVec4(0.520f, 0.090f, 0.120f, 1.0f); }; // Reset to a known base before applying size scaling. This prevents cumulative scaling when // the display moves between monitors. The application should invoke this only at startup or // after a confirmed DPI change, with a positive host-provided content scale. inline void ApplyToolTheme(float dpiScale = 1.0f, const Metrics& metrics = {}, const Colors& c = {}, FontDpiPolicy fontDpiPolicy = FontDpiPolicy::HostManagedFonts) { const float effectiveDpiScale = std::clamp(dpiScale, 0.75f, 4.0f); ImGuiStyle& style = ImGui::GetStyle(); // Preserve the docking branch's automatically managed font scale across the style reset. // Restoring the observed value does not derive it from host dpiScale or create a second owner. const float dearImGuiManagedFontScale = style.FontScaleDpi; style = ImGuiStyle{}; style.WindowPadding = ImVec2(metrics.unit * 3.0f, metrics.unit * 3.0f); style.FramePadding = metrics.framePadding(); style.CellPadding = metrics.cellPadding(); style.ItemSpacing = metrics.itemSpacing(); style.ItemInnerSpacing = ImVec2(metrics.unit * 1.5f, metrics.unit); style.TouchExtraPadding = ImVec2(0.0f, 0.0f); style.IndentSpacing = metrics.unit * 5.0f; style.ScrollbarSize = metrics.unit * 3.5f; style.GrabMinSize = metrics.unit * 2.75f; style.WindowRounding = metrics.radiusMedium; style.ChildRounding = metrics.radiusMedium; style.FrameRounding = metrics.radiusSmall; style.PopupRounding = metrics.radiusMedium; style.ScrollbarRounding = metrics.radiusMedium; style.GrabRounding = metrics.radiusSmall; style.TabRounding = metrics.radiusSmall; style.WindowBorderSize = metrics.border; style.ChildBorderSize = metrics.border; style.PopupBorderSize = metrics.border; style.FrameBorderSize = 0.0f; style.TabBorderSize = 0.0f; style.WindowMenuButtonPosition = ImGuiDir_Right; style.ColorButtonPosition = ImGuiDir_Right; style.ButtonTextAlign = ImVec2(0.5f, 0.5f); style.SelectableTextAlign = ImVec2(0.0f, 0.5f); ImVec4* colors = style.Colors; colors[ImGuiCol_Text] = c.contentPrimary; colors[ImGuiCol_TextDisabled] = c.contentDisabled; colors[ImGuiCol_WindowBg] = c.surfaceBase; colors[ImGuiCol_ChildBg] = c.surfaceBase; colors[ImGuiCol_PopupBg] = c.surfaceOverlay; colors[ImGuiCol_Border] = c.borderSubtle; colors[ImGuiCol_BorderShadow] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); colors[ImGuiCol_FrameBg] = c.surfaceRaised; colors[ImGuiCol_FrameBgHovered] = c.surfaceOverlay; colors[ImGuiCol_FrameBgActive] = c.borderStrong; colors[ImGuiCol_TitleBg] = c.surfaceBase; colors[ImGuiCol_TitleBgActive] = c.surfaceRaised; colors[ImGuiCol_MenuBarBg] = c.surfaceRaised; colors[ImGuiCol_ScrollbarBg] = c.surfaceBase; colors[ImGuiCol_ScrollbarGrab] = c.borderSubtle; colors[ImGuiCol_ScrollbarGrabHovered] = c.borderStrong; colors[ImGuiCol_ScrollbarGrabActive] = c.accentActive; colors[ImGuiCol_CheckMark] = c.accent; colors[ImGuiCol_SliderGrab] = c.accent; colors[ImGuiCol_SliderGrabActive] = c.accentHover; colors[ImGuiCol_Button] = c.buttonSurface; colors[ImGuiCol_ButtonHovered] = c.buttonSurfaceHover; colors[ImGuiCol_ButtonActive] = c.buttonSurfaceActive; colors[ImGuiCol_Header] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.22f); colors[ImGuiCol_HeaderHovered] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.42f); colors[ImGuiCol_HeaderActive] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.64f); colors[ImGuiCol_Separator] = c.borderSubtle; colors[ImGuiCol_SeparatorHovered] = c.accentHover; colors[ImGuiCol_SeparatorActive] = c.accent; colors[ImGuiCol_ResizeGrip] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.18f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.55f); colors[ImGuiCol_ResizeGripActive] = c.accent; colors[ImGuiCol_Tab] = c.surfaceRaised; colors[ImGuiCol_TabHovered] = c.surfaceOverlay; colors[ImGuiCol_TabSelected] = c.accentActive; colors[ImGuiCol_TabSelectedOverline] = c.accent; #if defined(IMGUI_HAS_DOCK) colors[ImGuiCol_DockingPreview] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.60f); #endif colors[ImGuiCol_TableHeaderBg] = c.surfaceRaised; colors[ImGuiCol_TableBorderStrong] = c.borderStrong; colors[ImGuiCol_TableBorderLight] = c.borderSubtle; colors[ImGuiCol_TableRowBg] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(c.surfaceRaised.x, c.surfaceRaised.y, c.surfaceRaised.z, 0.42f); colors[ImGuiCol_TextSelectedBg] = ImVec4(c.accent.x, c.accent.y, c.accent.z, 0.35f); colors[ImGuiCol_NavCursor] = c.accentHover; colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.0f, 0.0f, 0.0f, 0.55f); // Dear ImGui 1.92+ supports FontScaleDpi for fonts and ScaleAllSizes() for // paddings, hit regions, borders, and related style metrics. Do not write // FontScaleDpi here when the docking branch's ConfigDpiScaleFonts owns it. if (fontDpiPolicy == FontDpiPolicy::HostManagedFonts) style.FontScaleDpi = effectiveDpiScale; else style.FontScaleDpi = dearImGuiManagedFontScale; style.ScaleAllSizes(effectiveDpiScale); } inline bool PrimaryButton(const char* label, const ImVec2& size = ImVec2(0.0f, 0.0f)) { return ImGui::Button(label, size); } inline bool DangerButton(const char* label, const Colors& c, const ImVec2& size = ImVec2(0.0f, 0.0f)) { ImGui::PushStyleColor(ImGuiCol_Button, c.dangerSurface); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, c.dangerSurfaceHover); ImGui::PushStyleColor(ImGuiCol_ButtonActive, c.dangerSurfaceActive); const bool clicked = ImGui::Button(label, size); ImGui::PopStyleColor(3); return clicked; } } // namespace ToolUitemplates/imgui_panel_skeleton.cpp.in15 KB1f5cf8879378upstream ↗
// Dear ImGui tool-workspace starter. // Target: Dear ImGui 1.92.0 or newer; docking is optional and guarded below. // Include the copied imgui_design_system.h template before compiling this file. // Call DrawToolWorkspace() between ImGui::NewFrame() and ImGui::Render(). #include "imgui.h" #include "imgui_design_system.h" #if !defined(IMGUI_VERSION_NUM) || IMGUI_VERSION_NUM < 19200 # error "imgui_panel_skeleton.cpp requires Dear ImGui 1.92.0 or newer." #endif #include <algorithm> #include <cctype> #include <cstring> #include <vector> struct Asset { int id = 0; // Stable application-model identifier. // Nullable display strings are tolerated by this template; rendering uses SafeText(). const char* name = ""; const char* type = ""; const char* status = ""; bool editable = true; float exposure = 1.0f; }; enum AssetColumnId : ImGuiID { AssetColumnId_Name = 1, AssetColumnId_Type, AssetColumnId_Status, }; struct ToolUiState { int selectedAssetId = -1; // Set only when a command, hierarchy action, or other explicit navigation asks to move focus. int pendingKeyboardFocusAssetId = -1; char assetFilter[128] = ""; bool showLog = true; bool showInspector = true; bool showMetrics = false; // The host must call MarkAssetViewDirty() after adding/removing assets or changing // any value that participates in filtering or sorting. bool assetViewDirty = true; std::vector<int> filteredSortedAssetIndices; }; inline void MarkAssetViewDirty(ToolUiState& ui) { ui.assetViewDirty = true; } // Use this helper for programmatic selection that must also enter keyboard navigation. // Ordinary pointer selection does not need a forced default-focus request. inline void RequestAssetSelection(ToolUiState& ui, int assetId, bool requestKeyboardFocus = false) { ui.selectedAssetId = assetId; ui.pendingKeyboardFocusAssetId = requestKeyboardFocus ? assetId : -1; } static const char* SafeText(const char* value, const char* fallback = "") { return value != nullptr && value[0] != '\0' ? value : fallback; } static Asset* FindAsset(std::vector<Asset>& assets, int id) { for (Asset& asset : assets) if (asset.id == id) return &asset; return nullptr; } static bool ContainsCaseInsensitive(const char* haystack, const char* needle) { if (needle == nullptr || needle[0] == '\0') return true; if (haystack == nullptr) return false; for (const char* start = haystack; *start != '\0'; ++start) { const char* h = start; const char* n = needle; while (*h != '\0' && *n != '\0' && std::tolower(static_cast<unsigned char>(*h)) == std::tolower(static_cast<unsigned char>(*n))) { ++h; ++n; } if (*n == '\0') return true; } return false; } static bool AssetMatchesFilter(const Asset& asset, const char* filter) { return ContainsCaseInsensitive(asset.name, filter) || ContainsCaseInsensitive(asset.type, filter) || ContainsCaseInsensitive(asset.status, filter); } static int CompareTextCaseInsensitive(const char* left, const char* right) { left = left != nullptr ? left : ""; right = right != nullptr ? right : ""; while (*left != '\0' && *right != '\0') { const int a = std::tolower(static_cast<unsigned char>(*left)); const int b = std::tolower(static_cast<unsigned char>(*right)); if (a != b) return a < b ? -1 : 1; ++left; ++right; } if (*left == *right) return 0; return *left == '\0' ? -1 : 1; } static int CompareAssets(const Asset& left, const Asset& right, ImGuiID columnId) { switch (columnId) { case AssetColumnId_Type: return CompareTextCaseInsensitive(left.type, right.type); case AssetColumnId_Status: return CompareTextCaseInsensitive(left.status, right.status); case AssetColumnId_Name: default: return CompareTextCaseInsensitive(left.name, right.name); } } static void RebuildAssetView(ToolUiState& ui, const std::vector<Asset>& assets, const ImGuiTableSortSpecs* sortSpecs) { ui.filteredSortedAssetIndices.clear(); ui.filteredSortedAssetIndices.reserve(assets.size()); for (int index = 0; index < static_cast<int>(assets.size()); ++index) { if (AssetMatchesFilter(assets[index], ui.assetFilter)) ui.filteredSortedAssetIndices.push_back(index); } const ImGuiID sortColumn = (sortSpecs != nullptr && sortSpecs->SpecsCount > 0) ? sortSpecs->Specs[0].ColumnUserID : AssetColumnId_Name; const ImGuiSortDirection sortDirection = (sortSpecs != nullptr && sortSpecs->SpecsCount > 0) ? sortSpecs->Specs[0].SortDirection : ImGuiSortDirection_Ascending; std::sort(ui.filteredSortedAssetIndices.begin(), ui.filteredSortedAssetIndices.end(), [&assets, sortColumn, sortDirection](int leftIndex, int rightIndex) { const int comparison = CompareAssets(assets[leftIndex], assets[rightIndex], sortColumn); if (comparison == 0) return assets[leftIndex].id < assets[rightIndex].id; // Stable tie-breaker. return sortDirection == ImGuiSortDirection_Descending ? comparison > 0 : comparison < 0; }); ui.assetViewDirty = false; } static const ImVec4& StatusColor(const Asset& asset, const ToolUi::Colors& colors) { const char* status = SafeText(asset.status); if (std::strcmp(status, "Ready") == 0 || std::strcmp(status, "Healthy") == 0) return colors.success; if (std::strcmp(status, "Warning") == 0 || std::strcmp(status, "Pending") == 0) return colors.warning; if (std::strcmp(status, "Failed") == 0 || std::strcmp(status, "Error") == 0) return colors.danger; return colors.contentSecondary; } static void DrawMainMenu(ToolUiState& ui) { if (!ImGui::BeginMainMenuBar()) return; if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Import…", "Ctrl+I")) { // DispatchImportCommand(); } if (ImGui::MenuItem("Save Workspace", "Ctrl+S")) { // DispatchSaveWorkspaceCommand(); } ImGui::Separator(); if (ImGui::MenuItem("Quit", "Alt+F4")) { // DispatchQuitCommand(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { ImGui::MenuItem("Inspector", nullptr, &ui.showInspector); ImGui::MenuItem("Activity Log", nullptr, &ui.showLog); ImGui::MenuItem("Metrics", nullptr, &ui.showMetrics); ImGui::EndMenu(); } ImGui::Separator(); ImGui::TextDisabled("Workspace"); ImGui::SameLine(); ImGui::TextUnformatted("Production"); ImGui::SameLine(); ImGui::TextDisabled("• Saved"); ImGui::EndMainMenuBar(); } static void DrawAssetBrowser(ToolUiState& ui, std::vector<Asset>& assets, const ToolUi::Colors& colors) { if (!ImGui::Begin("Assets##panel")) { ImGui::End(); return; } ImGui::SetNextItemWidth(-1.0f); if (ImGui::InputTextWithHint("##asset-filter", "Filter assets…", ui.assetFilter, IM_ARRAYSIZE(ui.assetFilter))) MarkAssetViewDirty(ui); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Filter by name, type, or status"); ImGui::Spacing(); ImGui::TextDisabled("%d assets", static_cast<int>(assets.size())); ImGui::SameLine(); if (ImGui::SmallButton("Clear##asset-filter") && ui.assetFilter[0] != '\0') { ui.assetFilter[0] = '\0'; MarkAssetViewDirty(ui); } const ImGuiTableFlags tableFlags = ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp; if (ImGui::BeginTable("AssetsTable##assets", 3, tableFlags, ImVec2(0.0f, 0.0f))) { ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableSetupColumn("Asset", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthStretch, 0.58f, AssetColumnId_Name); ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 0.22f, AssetColumnId_Type); ImGui::TableSetupColumn("Status", ImGuiTableColumnFlags_WidthStretch, 0.20f, AssetColumnId_Status); ImGui::TableHeadersRow(); ImGuiTableSortSpecs* sortSpecs = ImGui::TableGetSortSpecs(); const bool sortChanged = sortSpecs != nullptr && sortSpecs->SpecsDirty; if (ui.assetViewDirty || sortChanged) RebuildAssetView(ui, assets, sortSpecs); if (sortSpecs != nullptr) sortSpecs->SpecsDirty = false; ImGuiListClipper clipper; clipper.Begin(static_cast<int>(ui.filteredSortedAssetIndices.size())); if (ui.pendingKeyboardFocusAssetId >= 0) { int focusRow = -1; for (int row = 0; row < static_cast<int>(ui.filteredSortedAssetIndices.size()); ++row) { if (assets[ui.filteredSortedAssetIndices[row]].id == ui.pendingKeyboardFocusAssetId) { focusRow = row; break; } } if (focusRow >= 0) clipper.IncludeItemByIndex(focusRow); else ui.pendingKeyboardFocusAssetId = -1; // Deleted or excluded by the active filter. } while (clipper.Step()) { for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) { Asset& asset = assets[ui.filteredSortedAssetIndices[row]]; const bool selected = (asset.id == ui.selectedAssetId); ImGui::PushID(asset.id); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); const ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap; if (ImGui::Selectable(SafeText(asset.name, "<Unnamed asset>"), selected, selectableFlags)) RequestAssetSelection(ui, asset.id); if (ui.pendingKeyboardFocusAssetId == asset.id) { ImGui::SetItemDefaultFocus(); ImGui::SetScrollHereY(0.5f); ui.pendingKeyboardFocusAssetId = -1; } ImGui::TableSetColumnIndex(1); ImGui::TextUnformatted(SafeText(asset.type, "Unknown")); ImGui::TableSetColumnIndex(2); ImGui::TextColored(StatusColor(asset, colors), "%s", SafeText(asset.status, "Unknown")); ImGui::PopID(); } } if (ui.filteredSortedAssetIndices.empty()) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::TextDisabled("No assets match the active filter."); } ImGui::EndTable(); } ImGui::End(); } static void DrawInspector(ToolUiState& ui, std::vector<Asset>& assets) { if (!ImGui::Begin("Inspector##panel", &ui.showInspector)) { ImGui::End(); return; } Asset* selected = FindAsset(assets, ui.selectedAssetId); if (selected == nullptr) { ImGui::TextDisabled("No asset selected"); ImGui::TextWrapped("Select an asset from the browser to inspect and edit its properties."); ImGui::End(); return; } ImGui::TextUnformatted(SafeText(selected->name, "<Unnamed asset>")); ImGui::SameLine(); ImGui::TextDisabled("%s", SafeText(selected->type, "Unknown")); ImGui::Separator(); if (ImGui::CollapsingHeader("Rendering", ImGuiTreeNodeFlags_DefaultOpen)) { if (!selected->editable) { ImGui::BeginDisabled(); ImGui::TextDisabled("This asset is locked by its source."); } if (ImGui::BeginTable("InspectorFields##rendering", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_BordersInnerV)) { ImGui::TableSetupColumn("Label", ImGuiTableColumnFlags_WidthFixed, 104.0f); ImGui::TableSetupColumn("Control", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::AlignTextToFramePadding(); ImGui::TextUnformatted("Exposure"); ImGui::TableSetColumnIndex(1); ImGui::SetNextItemWidth(-1.0f); if (ImGui::DragFloat("##exposure", &selected->exposure, 0.05f, -8.0f, 8.0f, "%.2f EV")) { // DispatchSetExposurePreview(selected->id, selected->exposure); } if (ImGui::IsItemDeactivatedAfterEdit()) { // DispatchSetExposureCommandForUndo(selected->id, selected->exposure); } ImGui::EndTable(); } if (!selected->editable) ImGui::EndDisabled(); } ImGui::Spacing(); if (ImGui::Button("Reveal in Browser")) { // NavigateToAsset(selected->id); } ImGui::SameLine(); if (ImGui::Button("Reset to Default")) { // DispatchResetAssetCommand(selected->id); } ImGui::End(); } static void DrawActivityLog(ToolUiState& ui, const ToolUi::Colors& colors) { if (!ui.showLog) return; if (!ImGui::Begin("Activity##panel", &ui.showLog)) { ImGui::End(); return; } ImGui::TextColored(colors.success, "Ready"); ImGui::SameLine(); ImGui::TextDisabled("Workspace loaded successfully."); ImGui::TextDisabled("14:32:09"); ImGui::SameLine(); ImGui::TextUnformatted("Shader cache refreshed (32 entries)."); ImGui::End(); } static void DrawMetrics(ToolUiState& ui) { if (!ui.showMetrics) return; if (!ImGui::Begin("Metrics##panel", &ui.showMetrics)) { ImGui::End(); return; } ImGui::TextDisabled("Frame time"); const float frameRate = ImGui::GetIO().Framerate; if (frameRate > 0.0f) ImGui::Text("%.2f ms", 1000.0f / frameRate); else ImGui::TextDisabled("Collecting frame data\xE2\x80\xA6"); ImGui::Separator(); ImGui::TextDisabled("Use application metrics, not only UI frame rate, for production profiling."); ImGui::End(); } void DrawToolWorkspace(ToolUiState& ui, std::vector<Asset>& assets, const ToolUi::Colors& colors) { // DockSpaceOverViewport is only available in a docking-enabled Dear ImGui build. #if defined(IMGUI_HAS_DOCK) ImGui::DockSpaceOverViewport(0, ImGui::GetMainViewport(), ImGuiDockNodeFlags_None); #endif DrawMainMenu(ui); DrawAssetBrowser(ui, assets, colors); DrawInspector(ui, assets); DrawActivityLog(ui, colors); DrawMetrics(ui); }
Plain-text copy, no login: /skill-bundles/muhosekerci-imgui-ui-ux-engineering.md