Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6a41f9e03a | |||
| b765e54eff | |||
| c66cad3423 | |||
| 348cf666f5 | |||
| 572802e2ee | |||
| 10a91f9a64 | |||
| eb96e5a64e | |||
| 5cb59b3652 | |||
| 0c1cf2938f | |||
| aa0fa8d320 | |||
| 43564ef675 | |||
| 53dc237e46 | |||
| 46febdb973 | |||
| f05962954f | |||
| 58d4e8ab2f | |||
| 5420bfd644 | |||
| cc08187ced | |||
| c10e72b3fe | |||
| 6218ba54e3 |
@@ -0,0 +1,29 @@
|
||||
name: Mirror to GitCode
|
||||
on:
|
||||
push:
|
||||
branches: [ "**" ] # 任意分支推送触发
|
||||
create:
|
||||
tags: [ "*" ] # 新建 tag 触发
|
||||
workflow_dispatch: # 支持手动触发
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 必须拿全历史+所有 tag
|
||||
- name: Push --mirror to GitCode
|
||||
env:
|
||||
GITCODE_USER: ${{ secrets.GITCODE_USER }}
|
||||
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
|
||||
run: |
|
||||
set -e
|
||||
git config --global user.name "mirror-bot"
|
||||
git config --global user.email "mirror-bot@users.noreply.github.com"
|
||||
# 如果你的命名空间不是个人用户,而是组织,请把 ${GITCODE_USER} 换成组织名
|
||||
git remote add gitcode https://${GITCODE_USER}:${GITCODE_TOKEN}@gitcode.com/${GITCODE_USER}/StellarX.git
|
||||
git push --prune --mirror gitcode
|
||||
File diff suppressed because it is too large
Load Diff
+157
@@ -7,6 +7,163 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
[中文文档](CHANGELOG.md)
|
||||
|
||||
## [v3.0.1] - 2026 - 03 - 17
|
||||
|
||||
==Notice==
|
||||
|
||||
This update changes the **semantics of `TextBox::setText`**.
|
||||
If your old code manually called `draw()` after calling `setText()`, you should now remove that call. Otherwise, under the new version, old code may cause `TextBox` to flicker in some cases.
|
||||
|
||||
### 🙏 Acknowledgements
|
||||
|
||||
Special thanks to [Pengfei Zhu](https://github.com/zhupengfeivip) for helping improve the StellarX documentation, especially the **Include Directories and Library Directories Configuration** section, and for reporting the issue where passing `NULL` in window mode would cause a console window to pop up ([Issues#9](https://github.com/Ysm-04/StellarX/issues/9)).
|
||||
|
||||
### ⚙️ Changes
|
||||
|
||||
- **Changed semantics of `TextBox::setText`:**
|
||||
The old dirty-mark-only behavior has been replaced with a more robust workflow.
|
||||
- If the text has not changed, the function returns immediately without doing anything.
|
||||
- If the text has changed, it will decide whether to redraw immediately or request an upstream redraw depending on whether the graphics context/window has already been created. If the graphics context/window has not yet been created, it will only mark itself as dirty.
|
||||
|
||||
- **TextBox - text overflow truncation:**
|
||||
If the user types text or calls `setText()` to set text, and the text length does not exceed `maxCharLen` but its pixel width exceeds the `TextBox` width, the displayed text will be truncated by character and appended with `...` for rendering.
|
||||
The full original text is still stored internally and is not affected when retrieved through getter methods.
|
||||
|
||||
### ✅ Fixes
|
||||
|
||||
- **`TabControl::getActiveIndex() const` could return the last tab index when the tab list was not empty but no tab was active:**
|
||||
Fixed the issue where calling `getActiveIndex()` could sometimes return an incorrect index.
|
||||
Now:
|
||||
- if the tab list is empty, it returns `-1`
|
||||
- if no tab is active, it returns `-1`
|
||||
- if a tab is active, it returns the index of the active tab
|
||||
|
||||
- **Continuous full redraw while a dialog is open:**
|
||||
Added a new variable `dialogOpen` to `Window`.
|
||||
When a dialog is shown, `dialogOpen` is set to `true`. Only when `dialogOpen` is `true` will `needRedraw` be checked. After redrawing, `dialogOpen` is immediately reset to `false`.
|
||||
|
||||
- **Synthetic `WM_MOUSEMOVE` being dispatched when a dialog opens, instead of only when it closes:**
|
||||
Added a condition when dispatching synthetic `WM_MOUSEMOVE`.
|
||||
Now it is only synthesized and dispatched when `dialogClose` is `true`, meaning only after a dialog is closed.
|
||||
|
||||
- **Normal control event dispatch order in `Window::runEventLoop`:**
|
||||
Changed the traversal of `controls (vector)` from forward order
|
||||
`for (auto& c : controls)`
|
||||
to reverse order
|
||||
`for (auto it = controls.rbegin(); it != controls.rend(); ++it)`
|
||||
|
||||
## [v3.0.0] - 2026-01-09
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- **Logging System Demo**: Located in: examples\SXLog-LoggingSystemDemo
|
||||
- **Lightweight Logging System SxLog (SxLogger / SxLogLine / SxLogScope / Sink / TagFilter / LanguageSwitch):** A unified logging entry and macro encapsulation is introduced, supporting level and tag-based filtering, console/file output, and optional file rolling based on size thresholds. It also provides bilingual text selection capabilities (via `SX_T` / `SxT`). The logging macros have a short-circuit mechanism: logs will not be constructed or string concatenated if the level or tag condition is not met. Output is serialized with mutex to ensure thread safety. The module does not depend on WinAPI debug output channels and does not introduce third-party libraries.
|
||||
- Typical usage: `SX_LOGD/SX_LOGI/SX_LOGW/SX_LOGE/SX_LOGF/SX_LOG_TRACE` with stream concatenation; `SX_TRACE_SCOPE` for scope timing.
|
||||
- Core configuration: `setMinLevel(...)`, `setTagFilter(...)`, `enableConsole(true/false)`, `enableFile(path, append, rotateBytes)`, `setLanguage(ZhCN/EnUS)`, `setGBK()`
|
||||
|
||||
### ⚙️ Changes
|
||||
|
||||
- **TabControl Tab Switching Logic Adjustment:** The logic for tab button switching has been modified to “first close the currently opened tab, then open the triggered tab,” avoiding potential timing issues caused by the “open first, close later” sequence in complex containers/snapshot chains. The external API remains unchanged (involving the internal switching logic of `TabControl::add`).
|
||||
- **Setter Semantics Refined for Controls:** The responsibility of setters is clarified to be “updating state and marking as dirty,” with drawing now uniformly triggered by the window/container's redraw mechanism, reducing lifecycle coupling and snapshot pollution risks (see related fix entries below).
|
||||
|
||||
### ✅ Fixes
|
||||
|
||||
- **TextBox::setText Causes Interruptions Before Entering Event Loop:** Fixed the issue where calling `TextBox::setText()` before window initialization (before `initgraph()` or when the graphical context is not ready) caused access conflicts and crashes. The previous implementation coupled “state updates” with “immediate drawing,” leading to `setText()` internally triggering `draw()`, which crashed when there was no graphics context (e.g., `saveBackground()/getimage()`). Now, the setter only updates the text and marks the control as dirty, with the drawing handled by the unified redraw flow.
|
||||
- **TabControl Switching and Table Content Overlap (Ghosting):** Fixed a stable ghosting issue when switching tabs or resetting the table data. The issue was caused by partial redraws happening before the snapshot was ready, leading to snapshot contamination. This was addressed by rolling back the behavior of `setIsVisible(true)` immediately triggering `requestRepaint`, and instead marking as dirty while adding safeguards to `Canvas::requestRepaint` and `TabControl::requestRepaint`: when the container is `dirty`, `hasSnap=0`, or the snapshot cache is invalid, partial fast-path is disabled and full redraw is triggered to ensure correct snapshot chains.
|
||||
|
||||
### ⚠️ Breaking Changes
|
||||
|
||||
- **Removal of Button Dimension Alias APIs:** Removed `Button::getButtonWidth()` and `Button::getButtonHeight()`, unifying the control's dimension APIs under the base class `Control::getWidth()` and `Control::getHeight()`. This change will break backward compatibility if the old methods were used, but the behavior (retrieving `width/height`) remains the same.
|
||||
- **Removal of Immediate Refresh Side Effects in Setters:** The side effect of immediate drawing in setters like `setIsVisible(true)` and `setText()` has been removed. If previous business code relied on "immediate visibility update after calling," you will now need to ensure a subsequent redraw path (via window's main loop/container redraw or explicit refresh) for visual updates to be completed.
|
||||
|
||||
### 📌 Upgrade Instructions
|
||||
|
||||
1. **Button Dimension API Migration:**
|
||||
- `getButtonWidth()` → `getWidth()`
|
||||
- `getButtonHeight()` → `getHeight()`
|
||||
2. **Adapting to Setters No Longer Triggering Immediate Drawing:**
|
||||
- It is now possible to set properties (like `TextBox::setText("default")`) during initialization, with visual updates being handled by the first `Window::draw()` or the main event loop.
|
||||
- If you need immediate visual updates in non-event-driven scenarios, you must ensure that a redraw path is triggered (avoid manually calling `draw()` inside the setter, as this would cause lifecycle coupling).
|
||||
3. **SxLog Integration Suggestions:**
|
||||
- Ensure basic configuration at the program entry (console output/minimum level/language), and use consistent tags (such as `Dirty/Resize/Table/Canvas/TabControl`) to establish traceable event chains; for high-frequency paths, control noise and I/O costs using level and tag filtering.
|
||||
|
||||
## [v2.3.2] - 2025 - 12 - 20
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **Table: runtime reset for headers and data:** added `Table::clearHeaders()`, `Table::clearData()`, and `Table::resetTable()`. This allows a single `Table` instance to dynamically update its headers/data at runtime, and triggers the required recalculation (cell sizing / pagination info) and redraw.
|
||||
- **TextBox: password mode:** added `PASSWORD_MODE` to `TextBoxmode`. User input is stored internally, while the render layer displays masked characters (e.g., `*`). The real text can be retrieved via `TextBox::getText()`.
|
||||
|
||||
### ⚙️ Changed
|
||||
|
||||
- **TabControl: clarified default active page semantics:**
|
||||
- Calling `TabControl::setActiveIndex()` **before the first draw** now only records the default active index; it no longer immediately triggers the tab button click callback.
|
||||
- **After the first draw completes**, if a default active index was set, the active state is applied and the active page is drawn (if the index is out of range, the last page is activated by default).
|
||||
- Calling `TabControl::setActiveIndex()` **during runtime (non-first draw)** switches the active page immediately when the index is valid; out-of-range indices are ignored.
|
||||
|
||||
### ✅ Fixed
|
||||
|
||||
- **TabControl::setActiveIndex crash when called before drawing:** fixed a null-pointer access caused by triggering the tab button click callback before initialization. The default activation is now applied after the first draw completes, preventing crashes and ensuring the active page is rendered on first draw.
|
||||
- **TabControl rendering glitches when toggling visibility (hidden -> visible):** fixed multi-page overlap/ghosting caused by non-active pages being incorrectly drawn after `setIsVisible(false) -> setIsVisible(true)`. Now, when TabControl is visible, only the active page is visible/drawable; if there is no active page, nothing is drawn.
|
||||
|
||||
## [v2.3.1] - 2025-11-30
|
||||
|
||||
### 🙏 Acknowledgements
|
||||
|
||||
- Special thanks to user [@To-KongBai](https://github.com/To-KongBai) for providing stable reproduction steps and key phenomenon comparisons (container nested child control coordinate transformation issue), which helped us quickly identify and fix the control coordinate transformation problem in deeply nested containers. ([Issues#6](https://github.com/Ysm-04/StellarX/issues/6))
|
||||
- In the upcoming website (currently undergoing ICP filing), we plan to add a contributors' wall to acknowledge users. We welcome everyone to report bugs or share interfaces created with StellarX, and we will carefully read and include acknowledgements.
|
||||
- Sincere thanks to every user who reports bugs—your feedback makes StellarX more stable and robust.
|
||||
|
||||
### ⚙️ Changes
|
||||
|
||||
- **Dialog Background Snapshot Mechanism:** `Dialog` no longer captures and destroys its own snapshot. The methods for capturing and restoring snapshots have been **removed** from `Dialog`, and the base class `Canvas` now handles all snapshot management. The `draw` method in `Dialog` no longer deals with snapshots.
|
||||
- **Timing Adjustment for Window and Control Redrawing on Size Change:** In the main event loop, when the window size changes, control sizes are processed first. Old snapshots are discarded, followed by the redrawing of the window with the new size, and finally, the controls are redrawn.
|
||||
|
||||
### ✅ Fixes
|
||||
|
||||
- **Child Control Coordinate Transformation in Nested Containers:** `Canvas` overrides the base class's `setX/Y` methods to synchronize the global coordinates of child controls when the parent container's global coordinates change. This prevents child controls in nested containers from incorrectly treating the container's relative coordinates as global coordinates.
|
||||
- **Solid Background Window Title Not Applied:** In the `Window`'s `draw()` method, the window title is forcibly set to ensure that the title passed when creating the window is applied correctly, preventing the issue where the window title doesn't take effect.
|
||||
- **Tab Control Background Residue when Changing Coordinates:** In the overridden `setX/Y` methods of `TabControl`, all tabs and their child controls are forced to discard snapshots when the tab's coordinates change. This prevents background residue caused by incorrect snapshot restoration order after modifying coordinates.
|
||||
- **Table Page Number Label and Pagination Button Misalignment when Changing Coordinates:** In `Table`'s `setX/Y`, the `isNeedButtonAndPageNum` state is reset to `true`, ensuring that the pagination button and page number label are recalculated and remain centered directly beneath the table when redrawn.
|
||||
|
||||
## [v2.3.0] - 2025-11-18
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- Introduced `LayoutMode` adaptive layout mode and `Anchor` anchor points. Controls can now call `setLayoutMode` to set layout mode and `steAnchor` to set anchor points, enabling controls to adapt to window changes during resizing. Dialog controls only recalculate their position during window resizing to maintain center alignment.
|
||||
- Added `adaptiveLayout()` API to `Window`, called by the main event loop to recalculate control positions and sizes based on anchor points during window resizing, enabling dual-anchored controls (left-right or top-bottom) to automatically stretch with window changes.
|
||||
|
||||
### ⚙️ Changed
|
||||
|
||||
- **Optimized Window Resizing Mechanism**: Refactored `WndProcThunk`, `runEventLoop`, and `pumpResizeIfNeeded` to uniformly record window size changes and perform one-time repainting at the end of the event loop, preventing jitter and sequencing issues caused by repeated drawing during resizing.
|
||||
- **Added Dialog Size Scheduling Interface**: Introduced `Window::scheduleResizeFromModal()`, used in conjunction with `pumpResizeIfNeeded()`. During modal dialog display, the parent window can update client area size in real time and relayout child controls during unified finalization, while the dialog maintains its original size.
|
||||
- **Redraw Sequence Optimization**: Replaced `InvalidateRect` with `ValidateRect` during the finalization phase after window size changes, preventing the system from sending additional `WM_PAINT` messages that could cause reentrant drawing.
|
||||
- **Other Improvements**: Fixed delayed background snapshot updates for table pagination buttons and page number labels; improved dialog background capture logic.
|
||||
|
||||
### ✅ Fixed
|
||||
|
||||
- **Modal Dialog Resizing Fix**: Resolved the issue where window resizing during modal dialog display prevented underlying controls from updating their sizes and positions according to anchor points; simultaneously eliminated ghosting artifacts caused by repeated dialog redrawing.
|
||||
- **Drawing Sequence Disorder Fix**: Addressed sporadic drawing sequence disorders, control ghosting, and border flickering during window resizing, ensuring controls are drawn in the order they were added.
|
||||
- **Stability Fixes**: Corrected abnormal frames caused by sudden window size changes in certain scenarios; resolved delayed background snapshot updates for tables and dialogs under edge conditions.
|
||||
|
||||
## [v2.2.2] - 2025 - 11- 08
|
||||
|
||||
### ⚙️ Changes
|
||||
|
||||
- Modified the coordinate transfer method for the Canvas container. Child control coordinates are now passed as relative coordinates (with the origin at the top-left corner of the container, obtainable via the `getX`/`getY` interface), instead of the original global coordinates. Child control coordinates can now be set to negative values.
|
||||
- The example under `examples\register-viewer` has been updated to the latest version, aligning container child controls to use relative coordinates.
|
||||
|
||||
### ✅ Fixes
|
||||
|
||||
- Fixed jittering/bouncing and flickering when resizing the window (left/top edges):
|
||||
- `WM_SIZING` only clamps the minimum size; `WM_GETMINMAXINFO` sets the window-level minimum tracking size.
|
||||
- Freezes redrawing during dragging and handles resizing uniformly upon release; `WM_SIZE` only records the new size without interfering with drawing.
|
||||
- Disabled `WM_ERASEBKGND` background erasing and removed `CS_HREDRAW`/`CS_VREDRAW` to reduce flickering.
|
||||
- Fixed issues related to dialog boxes:
|
||||
- Resolved occasional residual functional buttons after closing a dialog.
|
||||
- Fixed issues where window resizing failed to redraw or displayed a corrupted background when a modal dialog was active.
|
||||
- Fixed delayed updates of background snapshots for the table control's pagination buttons and page number labels during window changes.
|
||||
|
||||
## [v2.2.1] - 2025-11-04
|
||||
|
||||
==This release is a hotfix for v2.2.0==
|
||||
|
||||
+143
-1
@@ -3,10 +3,152 @@
|
||||
StellarX 项目所有显著的变化都将被记录在这个文件中。
|
||||
|
||||
格式基于 [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
并且本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
||||
并且本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)
|
||||
|
||||
[English document](CHANGELOG.en.md)
|
||||
|
||||
## [v3.0.1] - 2026 - 03 - 17
|
||||
|
||||
==注意==
|
||||
|
||||
此次更新变更了**TextBox::setText语义**之前如果再调用`setText`之后手动调用了`draw`方法现在应当删除,否则旧代码在新版本可能会造成`TextBox`闪烁(概率触发)【配置包含目录与库目录】
|
||||
|
||||
### 🙏 鸣谢
|
||||
|
||||
感谢用户[Pengfei Zhu](https://github.com/zhupengfeivip)帮StellarX完善文档【配置包含目录与库目录】部分,以及反馈在窗口模式传递参数NULL时会弹出命令行窗口的问题[Issues#9](https://github.com/Ysm-04/StellarX/issues/9)
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **TextBox::setText语义变化:**由原来的仅标脏改为更健全的工作原理
|
||||
- 如果文本未发生变化则立即return不做任何操作
|
||||
- 如果文本变化则根据是否已经创建图形上下文/窗口决定是否立即重绘/向上请求,如果图形上下文/窗口还为创建则仅标记为脏
|
||||
- **TextBox-文本溢出截断:**如果用户输入或者调用`setText`设置文本,文本不超过`maxCharLen`但是像素长度超过`TextBox`则按字符截断并添加...绘制,内部仍然保存完整的文本不影响get方法获取
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- **TabControl::getActiveIndex() const当页签对列表不为空时,如果所有页签都未激活则会返回最后一个页签的索引:**修复再调用`getActiveIndex()`概率获取错误的索引,如果页签对列表为空或者没有页签激活则返回-1,如果有页签激活则返回对应页签索引
|
||||
- **对话框打开时持续持续触发全量重绘:**Window新增变量`dialogOpen`,在对话框弹出时设置`dialogOpen`为`true`,只有dialogOpen为真时才判断`needredraw`,在重绘后立即设置`dialogOpen`为`flase`
|
||||
- **对话框关闭合成WM_MOUSEMOVE下发更新 可见控件hover 状态,在对话框打开时也会触发:**合成`WM_MOUSEMOVE`下发时判断是否有对话框关闭,只有`dialogClose`为真才合成并下发`WM_MOUSEMOVE`
|
||||
- **Window::runEventLoop普通控件事件分发顺序:**将`controls(vector)`的正序遍历`for (auto& c : controls)`改为逆序遍历`for (auto it = controls.rbegin(); it != controls.rend(); ++it)`
|
||||
|
||||
## [v3.0.0] - 2026 - 01 - 09
|
||||
|
||||
### ✨ 新增
|
||||
|
||||
- **日志系统使用Demo** 在:examples\SXLog-日志系统使用demo
|
||||
|
||||
- **轻量日志系统 SxLog(SxLogger / SxLogLine / SxLogScope / Sink / TagFilter / LanguageSwitch):**新增统一日志入口与宏封装,支持按级别与 Tag 筛选输出,支持控制台/文件落地与可选滚动(按大小阈值),并提供中英文双语文本选择能力(`SX_T` / `SxT`)。日志宏具备短路机制:未命中级别或 Tag 时不构造日志对象、不拼接字符串;输出侧以行级互斥保证多线程下不交错。该模块不依赖 WinAPI 调试输出通道、不引入第三方库。
|
||||
- 典型用法:`SX_LOGD/SX_LOGI/SX_LOGW/SX_LOGE/SX_LOGF/SX_LOG_TRACE` + 流式拼接;`SX_TRACE_SCOPE` 作用域耗时统计
|
||||
- 核心配置:`setMinLevel(...)`、`setTagFilter(...)`、`enableConsole(true/false)`、`enableFile(path, append, rotateBytes)`、`setLanguage(ZhCN/EnUS)`、`setGBK()`
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **TabControl 页签切换时序调整:**修改页签按钮切换逻辑为“先关闭当前已打开页,再打开目标页”,避免“先打开再关闭”在复杂容器/快照链路下引入的时序不确定性;对外 API 不变(涉及 `TabControl::add` 内部切换逻辑)。
|
||||
- **控件 Setter 语义收敛:**明确控件 Setter 的职责为“更新状态并标脏”,绘制统一由窗口/容器的重绘收口机制触发,降低生命周期耦合与快照污染风险(见下方相关修复条目)。
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- **TextBox::setText 在进入事件循环前调用触发中断:**修复在窗口尚未初始化(未 `initgraph()`、图形上下文未就绪)前调用 `TextBox::setText()` 导致访问冲突崩溃的问题。旧实现将“状态更新”和“立即绘制”耦合,`setText()` 内部直接触发 `draw()`,进而在无图形上下文时进入 `saveBackground()/getimage()` 路径崩溃;现已移除 Setter 内直接绘制,仅保留赋值与置脏,绘制交由统一重绘流程完成。
|
||||
- **TabControl 切换/关闭后 Table 新旧内容重叠(重影):**修复页签切换与表格重置数据后出现的稳定残影问题。根因是“快照未就绪阶段发生局部重绘”导致快照污染;本次回退 `setIsVisible(true)` 的“立即向上 requestRepaint”行为,改为仅置脏,并为 `Canvas::requestRepaint` 与 `TabControl::requestRepaint` 增加护栏:当容器 `dirty` 或 `hasSnap=0` 或快照缓存无效时,禁止 partial fast-path,自动降级为全量重绘以保证快照链路正确性;同时修正 `Table::setData(...)` 列补齐边界问题,降低异常噪声。
|
||||
|
||||
### ⚠️ 可能不兼容
|
||||
|
||||
- **删除 Button 尺寸别名 API(Breaking):**移除 `Button::getButtonWidth()` / `Button::getButtonHeight()`,统一使用基类 `Control::getWidth()` / `Control::getHeight()` 获取控件尺寸。该改动会导致旧代码在升级到 v3.0.0 后编译失败,但行为语义保持一致(仍读取同一 `width/height`)。
|
||||
- **可见性/文本设置的“即时刷新”副作用移除:**`setIsVisible(true)` 与 `setText()` 等 Setter 不再保证立刻触发绘制;如业务代码此前依赖“调用后立即可见”,需要确保后续存在一次重绘收口(窗口主循环/容器重绘/显式刷新)以完成视觉更新。
|
||||
|
||||
### 📌 升级指引
|
||||
|
||||
1. **Button 宽高接口迁移:**
|
||||
- `getButtonWidth()` → `getWidth()`
|
||||
- `getButtonHeight()` → `getHeight()`
|
||||
2. **Setter 不再“立即绘制”的适配:**
|
||||
- 初始化阶段可先设置属性(如 `TextBox::setText("default")`),由首次 `Window::draw()` / 主事件循环的统一绘制完成可视刷新;
|
||||
- 若在非事件驱动场景下程序化更新后需要立刻刷新,请确保触发一次统一重绘路径(避免在 Setter 内手动调用 `draw()` 造成生命周期耦合)。
|
||||
3. **SxLog 接入建议:**
|
||||
- 在程序入口完成基础配置(控制台输出/最低级别/语言),并使用统一 Tag(如 `Dirty/Resize/Table/Canvas/TabControl`)建立可回放的事件链路;高频路径建议通过级别与 Tag 控制噪声与 I/O 成本。
|
||||
|
||||
## [v2.3.2] - 2025 - 12 - 20
|
||||
|
||||
### ✨ 新增
|
||||
|
||||
- **Table 支持运行期重置表头与数据:**新增 `Table::clearHeaders()`、`Table::clearData()`、`Table::resetTable()`,允许同一 `Table` 在运行过程中动态切换表头与数据,并触发必要的单元格尺寸/分页信息重算与重绘。
|
||||
- **TextBox 新增密码模式:**`TextBoxmode` 新增 `PASSWORD_MODE`;输入内容内部保存,绘制层面使用掩码字符(如 `*`)替代显示,真实文本可通过 `TextBox::getText()` 获取。
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **TabControl 默认激活页语义明确化:**
|
||||
- 首次绘制前调用 `TabControl::setActiveIndex()`:仅记录默认激活索引,不再立即触发页签按钮点击回调;
|
||||
- 首次绘制完成后:若设置了默认激活索引则应用激活状态并绘制激活页(索引越界时默认激活最后一个页);
|
||||
- 程序运行过程中调用 `TabControl::setActiveIndex()`:索引合法则立即切换激活页并绘制;索引越界则不做处理。
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- **TabControl::setActiveIndex 绘制前调用导致程序中断:**修复绘制前设置默认激活索引时触发空指针访问的问题;现在默认激活逻辑延后到首次绘制完成后再生效,避免崩溃并保证首次绘制即可绘制激活页。
|
||||
- **TabControl 由不可见设置为可见时绘制错乱:**修复 `setIsVisible(false) -> setIsVisible(true)` 后非激活页被错误绘制导致的多页重叠/残影;现在 TabControl 可见时仅激活页可见/可绘制,无激活页则不绘制任何页。
|
||||
|
||||
## [v2.3.1] - 2025 - 11 - 30
|
||||
|
||||
### 🙏 鸣谢
|
||||
|
||||
- 感谢用户 [@To-KongBai](https://github.com/To-KongBai) 提供稳定复现步骤与关键现象对比(容器嵌套孙控件坐标转换问题),帮助我们快速确认多容器嵌套时的控件坐标转换问题并修复。([Issues#6](https://github.com/Ysm-04/StellarX/issues/6))
|
||||
- 在即将上线的官网中(ICP备案中)我们计划加入一个贡献者鸣谢墙,欢迎各位用户反馈BUG或者分享自己用星垣做的界面,我们将认真阅读并收录鸣谢
|
||||
- 真诚的感谢每一位反馈BUG的用户,你们的反馈将使星垣更加稳定和健壮
|
||||
|
||||
### ✨ 新增
|
||||
|
||||
新增一个登录界面Demo在主仓库**examples/**目录下
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **Dialog背景快照机制:**`Dialog`不在自己抓取和销毁快照,**删除**重载的抓取和恢复快照的方法,完全交由基类`Canvas`处理,`Dialog`的`draw`方法中不在处理快照
|
||||
- **窗口变化重绘时控件和窗口重绘的时机调整:**主事件循环中窗口大小发生变化时先处理控件尺寸,并回贴和释放旧快照,然后再重绘新尺寸窗口,最后绘制控件
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- **容器嵌套时子控件坐标转化:**`Canvas`重写了基类的`setX/Y`方法,在容器全局坐标发生变化时同步修改子控件的全局坐标,防止在容器嵌套时,容器的相对坐标被子控件当成全局坐标处理
|
||||
- **纯色背景窗口标题不生效:**在`Window`的`draw()`方法中强制设置窗口标题,以防止,创建窗口时传递的窗口标题不生效
|
||||
- **选项卡控件页签打开时动态改变坐标背景残留:**在`TabControl`重写的`setX/Y`方法中,当选项卡的坐标发生变化时强制让所有页签以及页和子控件丢一次快照,防止,在修改坐标后因,快照恢复顺序引起的选项卡激活页残留
|
||||
- **Table动态改变坐标页码标签和翻页按钮错乱:**在`Table`控件的`setX/Y`中重置`isNeedButtonAndPageNum`状态为真,在绘制时重新计算翻页按钮和页码标签的位置以保持在表格正下方居中位置显示
|
||||
|
||||
## [v2.3.0] - 2025 - 11 - 18
|
||||
|
||||
### ✨ 新增
|
||||
|
||||
- 新增`LayoutMode `自适应布局模式和`Anchor`锚点,控件中可以调用 `setLayoutMode`
|
||||
设置布局模式以及`steAnchor`设置锚点,达到窗口拉伸时控件自适应窗口变化。对话框控件在窗口变化时只会重新计算位置,来保证居中显示
|
||||
- `Window`新增`adaptiveLayout()`这个API由主事件循环调用,在窗口拉伸时根据锚点重新计算控件位置和尺寸,使左右/上下双锚定控件随窗口变化自动伸缩。
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **优化窗口尺寸调整机制**:重构 `WndProcThunk`、`runEventLoop` 和 `pumpResizeIfNeeded`,统一记录窗口尺寸变化并在事件循环尾部一次性重绘,避免拉伸过程中重复绘制引发抖动与顺序错乱。
|
||||
- **新增对话框尺寸调度接口**:引入 `Window::scheduleResizeFromModal()`,配合 `pumpResizeIfNeeded()` 使用。模态对话框显示期间,父窗口可实时更新客户区尺寸并在统一收口时重新布局子控件,对话框自身尺寸保持不变。
|
||||
- **重绘顺序优化**:在窗口尺寸变化后的收口阶段使用 `ValidateRect` 代替 `InvalidateRect`,避免系统再次发送 `WM_PAINT` 导致重入绘制。
|
||||
- **其他改进**:修复表格翻页按钮与页码标签等元素背景快照更新不及时的问题;改进对话框背景捕捉逻辑。
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- **模态对话框拉伸修复**:解决了模态对话框弹出时,窗口拉伸无法让底层控件按照锚点更新尺寸和位置的问题;同时避免对话框反复重绘导致残影。
|
||||
- **绘制顺序错乱修复**:解决窗口拉伸时偶发的绘制顺序紊乱、控件残影和边框闪烁问题,确保控件按添加顺序依次绘制。
|
||||
- **稳定性修复**:修正某些情况下窗口尺寸突变导致的异常帧;解决表格和对话框背景快照在边界条件下未及时更新的问题。
|
||||
|
||||
## [v2.2.2] - 2025 - 11- 08
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- Canvas容器坐标传递方式改变,子控件坐标由原来的传递全局坐标改为传递相对坐标(坐标原点为容器的左上角坐标可通过getX/Y接口获得)可以设置子控件坐标为负值
|
||||
- examples\register-viewer下的案例已同步修改为最新,同步容器子控件为相对坐标
|
||||
|
||||
### ✅ 修复
|
||||
|
||||
- 修复窗口拉伸(左/上边)时的抖动/弹回与闪烁
|
||||
- `WM_SIZING` 仅做最小尺寸夹紧;`WM_GETMINMAXINFO` 设置窗口级最小轨迹
|
||||
- 拖拽期冻结重绘,松手统一收口;`WM_SIZE` 只记录尺寸不抢绘制
|
||||
- 禁用 `WM_ERASEBKGND` 擦背景并移除 `CS_HREDRAW/CS_VREDRAW`,减少闪烁
|
||||
- 对话框的相关问题
|
||||
- 对话框关闭后概率出现功能按钮残留
|
||||
- 模态对话框触发时,窗口拉伸无法重绘或背景错乱
|
||||
- 表格控件在窗口变化时其翻页按钮和页码标签背景快照更新不及时的问题
|
||||
|
||||
## [v2.2.1] - 2025 - 11 - 4
|
||||
|
||||
==此版本为v2.2.0的修复版本==
|
||||
|
||||
+29
-1
@@ -7,13 +7,41 @@ project(StellarX VERSION 2.0.0 LANGUAGES CXX)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED True)
|
||||
|
||||
# 为了支持 out-of-source builds,创建构建目录
|
||||
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)
|
||||
|
||||
# 设置生成的二进制文件输出目录
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
# 包含头文件目录(目前头文件都在根目录)
|
||||
include_directories(${CMAKE_SOURCE_DIR})
|
||||
|
||||
# 源文件收集
|
||||
# 通过选项设置是否启用调试信息
|
||||
option(USE_DEBUG "Build with debug information" OFF)
|
||||
if(USE_DEBUG)
|
||||
set(CMAKE_BUILD_TYPE Debug)
|
||||
else()
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
endif()
|
||||
|
||||
# 查找源文件
|
||||
file(GLOB_RECURSE SOURCES
|
||||
"${CMAKE_SOURCE_DIR}/*.cpp"
|
||||
)
|
||||
|
||||
# 生成可执行文件
|
||||
add_executable(StellarX ${SOURCES})
|
||||
|
||||
# 可以选择性地查找外部库并链接(例如 Boost,SDL2等)
|
||||
# FindPackage(Boost REQUIRED)
|
||||
# target_link_libraries(StellarX Boost::Boost)
|
||||
|
||||
# 为外部依赖配置路径
|
||||
# set(Boost_DIR "path/to/boost")
|
||||
# find_package(Boost REQUIRED)
|
||||
|
||||
# 如果有额外的库需要链接,继续在此处添加
|
||||
# target_link_libraries(StellarX Boost::Boost)
|
||||
|
||||
|
||||
+27
-13
@@ -2,13 +2,18 @@
|
||||
|
||||
[中文README](README.md)
|
||||
|
||||
official website:https://stellarx-gui.top
|
||||
blog: https://blog.stellarx-gui.top
|
||||
|
||||
> For framework information and quick start instructions, please visit the official website. For detailed usage tutorials, please refer to the StellarX Xingyuan page on my personal blog.
|
||||
|
||||
------
|
||||
|
||||

|
||||
[](https://github.com/Ysm-04/StellarX)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -25,23 +30,27 @@ This is a **teaching-grade and tooling-grade** framework that helps developers u
|
||||
|
||||
------
|
||||
|
||||
## **🆕 v2.2.1 (Hotfix for v2.2.0)**
|
||||
### 🆕V3.0.1 - Major Update
|
||||
|
||||
- Addressed a flickering issue that occurred when using the Canvas and TabControl containers.
|
||||
- Fixed issues where border remnants and functional buttons could persist after closing a Dialog.
|
||||
[CHANGELOG.en.md](CHANGELOG.en.md)
|
||||
|
||||
For details, please refer to the [CHANGELOG.en](CHANGELOG.en.md).
|
||||
==Notice==
|
||||
|
||||
## What’s new in v2.2.0
|
||||
This update changes the **semantics of `TextBox::setText`**.
|
||||
If your previous code manually called `draw()` after calling `setText()`, that call should now be removed. Otherwise, under the new version, old code may cause `TextBox` flickering in some cases.
|
||||
|
||||
- **New TabControl for multi-page tabbed UIs:** With `TabControl`, it’s easy to create a tabbed layout. Tabs can be arranged on the top, bottom, left, or right, and clicking switches the displayed page. Suitable for settings panels and multi-view switching.
|
||||
- **Enhanced control show/hide and resize responsiveness:** All controls now share a unified interface (`setIsVisible`) to toggle visibility. When a container control is hidden, its child controls automatically hide/show with it. Meanwhile, we introduce `onWindowResize` for controls to respond to window size changes so elements update in sync after resizing, eliminating artifacts or misalignment.
|
||||
- **Refined text-style mechanism:** The Label control now uses a unified `ControlText` style structure. Developers can easily customize font, color, size, etc. (replacing older interfaces, and more flexible). Button Tooltips also support richer customization and different texts for toggle states.
|
||||
- **Other improvements:** Dialog management gains de-duplication to prevent identical prompts from popping up repeatedly. Several bug fixes and refresh optimizations further improve stability.
|
||||
### 🙏 Acknowledgements
|
||||
|
||||
See `CHANGELOG.md / CHANGELOG.en.md` for the full list.
|
||||
Special thanks to [Pengfei Zhu](https://github.com/zhupengfeivip) for helping improve the StellarX documentation, especially the **Include Directories and Library Directories Configuration** section, and for reporting the issue where passing `NULL` in window mode would cause a console window to appear ([Issues#9](https://github.com/Ysm-04/StellarX/issues/9)).
|
||||
|
||||
------
|
||||
### ⚙️ Changes
|
||||
|
||||
- **Changed semantics of `TextBox::setText`:** from the previous dirty-mark-only behavior to a more robust workflow
|
||||
- If the text has not changed, it returns immediately without doing anything.
|
||||
- If the text has changed, it decides whether to redraw immediately or request an upstream redraw depending on whether the graphics context/window has already been created. If the graphics context/window has not yet been created, it only marks itself as dirty.
|
||||
- **TextBox - text overflow truncation:** when the user enters text or calls `setText` to set text, if the text length does not exceed `maxCharLen` but its pixel width exceeds the `TextBox` width, the displayed text will be truncated by character and appended with `...` when rendered. The full original text is still stored internally and is not affected when retrieved through getter methods.
|
||||
|
||||
**For other fixes and changes, please refer to the [Changelog](CHANGELOG.md).**
|
||||
|
||||
## 📦 Project Structure & Design Philosophy
|
||||
|
||||
@@ -181,6 +190,11 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
|
||||
| `MessageBoxResult` | Result | `OK`, `Cancel`, `Yes`, `No`, `Abort`, `Retry`, `Ignore` |
|
||||
| `TabPlacement` | Tab position | `Top`, `Bottom`, `Left`, `Right` |
|
||||
|
||||
| Enum | Description | Common values |
|
||||
| ------------ | ---------------------- | -------------------------------------------- |
|
||||
| `LayoutMode` | 窗口布局模式 | `Fixed`, `AnchorToEdges` |
|
||||
| `Anchor` | 控件相对于父容器的锚点 | `NoAnchor` ,`Left` , `Right`, `Top`,`Bottom` |
|
||||
|
||||
### Structs
|
||||
|
||||
| Struct | Description |
|
||||
|
||||
@@ -2,13 +2,23 @@
|
||||
|
||||
[English document](README.en.md)
|
||||
|
||||
官网地址:https://stellarx-gui.top
|
||||
博客:https://blog.stellarx-gui.top
|
||||
|
||||
> 框架信息以及快速开始可前往官网查看,详细的使用教程可前往个人博客的StellarX星垣页面查看
|
||||
|
||||
> 本仓库为 **StellarX** 主仓:开发与 Issue/PR 均在 GitHub 进行。
|
||||
> GitCode 仅为只读镜像:如需反馈请到 GitHub:https://github.com/Ysm-04/StellarX
|
||||
|
||||
[](https://gitcode.com/Ysm-04/StellarX)
|
||||
|
||||
------
|
||||
|
||||

|
||||
[](https://github.com/Ysm-04/StellarX)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -25,24 +35,28 @@
|
||||
|
||||
---
|
||||
|
||||
## 🆕v2.2.1(v2.2.0修复版)
|
||||
|
||||
- 解决了使用Canvas和TabControl容器时,出现频闪问题
|
||||
|
||||
- 修复了Dialog对话框关闭时概率出边边框残留和功能按钮残留问题
|
||||
|
||||
详情参考[更新日志](CHANGELOG.md)
|
||||
|
||||
|
||||
### 🆕V3.0.1 - 重要更新
|
||||
|
||||
## V2.2.0 有何变化
|
||||
完整版建议查看[更新日志](CHANGELOG.md)
|
||||
|
||||
- **新增 TabControl 控件,实现多页面选项卡界面:** 通过 `TabControl` 可以轻松创建选项卡式布局,支持页签在上下左右排列、点击切换显示不同内容页面。适用于设置面板、多视图切换等场景。
|
||||
- **控件显隐与布局响应能力增强:** 现在所有控件都可以使用统一接口动态隐藏或显示(`setIsVisible`),容器控件隐藏时其内部子控件会自动随之隐藏/显示。与此同时,引入控件对窗口尺寸变化的响应机制(`onWindowResize`),窗口拉伸后界面各元素可协调更新,杜绝拉伸过程中出现残影或错位。
|
||||
- **文本样式机制完善:** Label 控件改用统一的文本样式结构 `ControlText`,开发者可方便地设置字体、颜色、大小等属性来定制 Label 的外观(替代旧接口,更加灵活)。Button 的 Tooltip 提示也支持更丰富的定制和针对切换状态的不同提示文本。
|
||||
- **其他改进:** 框架底层的对话框管理增加了防重复弹出相同提示的机制,修复了一些细节 Bug 并优化了刷新效率,进一步提升了稳定性。
|
||||
==注意==
|
||||
|
||||
详见 `CHANGELOG.md / CHANGELOG.en.md` 获取完整更新列表。
|
||||
此次更新变更了**TextBox::setText语义**之前如果再调用`setText`之后手动调用了`draw`方法现在应当删除,否则旧代码在新版本可能会造成`TextBox`闪烁(概率触发)【配置包含目录与库目录】
|
||||
|
||||
### 🙏 鸣谢
|
||||
|
||||
感谢用户[Pengfei Zhu](https://github.com/zhupengfeivip)帮StellarX完善文档【配置包含目录与库目录】部分,以及反馈在窗口模式传递参数NULL时会弹出命令行窗口的问题[Issues#9](https://github.com/Ysm-04/StellarX/issues/9)
|
||||
|
||||
### ⚙️ 变更
|
||||
|
||||
- **TextBox::setText语义变化:**由原来的仅标脏改为更健全的工作原理
|
||||
- 如果文本未发生变化则立即return不做任何操作
|
||||
- 如果文本变化则根据是否已经创建图形上下文/窗口决定是否立即重绘/向上请求,如果图形上下文/窗口还为创建则仅标记为脏
|
||||
- **TextBox-文本溢出截断:**如果用户输入或者调用`setText`设置文本,文本不超过`maxCharLen`但是像素长度超过`TextBox`则按字符截断并添加...绘制,内部仍然保存完整的文本不影响get方法获取
|
||||
|
||||
**其余修复及变更请前往[更新日志](CHANGELOG.md)**
|
||||
|
||||
---
|
||||
|
||||
@@ -184,6 +198,13 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
|
||||
| `MessageBoxResult` | 结果 | `OK`, `Cancel`, `Yes`, `No`, `Abort`, `Retry`, `Ignore` |
|
||||
| `TabPlacement` | 页签位置 | `Top`,`Bottom`,`Left`,`Right` |
|
||||
|
||||
| 枚举 | 描述 | 常用值 |
|
||||
| ------------ | ---------------------- | -------------------------------------------- |
|
||||
| `LayoutMode` | 窗口布局模式 | `Fixed`, `AnchorToEdges` |
|
||||
| Anchor | 控件相对于父容器的锚点 | `NoAnchor` ,`Left` , `Right`, `Top`,`Bottom` |
|
||||
|
||||
|
||||
|
||||
### 结构体
|
||||
|
||||
| 结构体 | 描述 |
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
#include"StellarX.h"//包含SXLog头文件
|
||||
|
||||
#if 1
|
||||
// 业务场景只需用日志系统时的最简用法示例
|
||||
/*
|
||||
//设置编码 按需开启
|
||||
StellarX::SxLogger::setGBK();
|
||||
|
||||
//启用日志文件和控制台输出 按需开启
|
||||
StellarX::SxLogger::Get().enableFile("stellarx.log", false, 1024);
|
||||
StellarX::SxLogger::Get().enableConsole(true);
|
||||
|
||||
//设置最低日志级别和语言 按需设置
|
||||
StellarX::SxLogger::Get().setMinLevel(StellarX::SxLogLevel::Debug); // Info/Debug/Trace 自己切
|
||||
StellarX::SxLogger::Get().setLanguage(StellarX::SxLogLanguage::ZhCN); // ZhCN / EnUS
|
||||
*/
|
||||
using namespace StellarX;
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
// 1) 可选:把 Windows 控制台切到 GBK,避免中文乱码(内部用 system("chcp 936"))
|
||||
SxLogger::setGBK();
|
||||
|
||||
// 2) 获取全局 logger 并开启控制台输出
|
||||
SxLogger& log = SxLogger::Get();
|
||||
log.enableConsole(true);
|
||||
|
||||
// 3) 最低输出级别(Debug 及以上都会输出)
|
||||
log.setMinLevel(SxLogLevel::Debug);
|
||||
|
||||
// 4) 语言选择(影响 SX_T 的文本选择,不做转码)
|
||||
log.setLanguage(SxLogLanguage::ZhCN);
|
||||
|
||||
// 5) 打几条日志(流式拼接)
|
||||
SX_LOGI("Init") << SX_T("日志系统已启用", "logging enabled");
|
||||
SX_LOGD("Init") << "minLevel=" << (int)log.getMinLevel();
|
||||
|
||||
// 6) 作用域耗时统计(只有 Trace 级别打开且 shouldLog 命中才会输出)
|
||||
{
|
||||
SX_TRACE_SCOPE("Perf", "demo-scope");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
// 7) 切换语言演示
|
||||
log.setLanguage(SxLogLanguage::EnUS);
|
||||
SX_LOGI("Init") << SX_T("这条不会显示中文", "this line is English");
|
||||
|
||||
// 8) Tag 过滤演示(只允许 Init)
|
||||
log.setTagFilter(SxTagFilterMode::Whitelist, { "Init" });
|
||||
SX_LOGI("Init") << "allowed";
|
||||
SX_LOGI("Table") << "blocked (should not appear)";
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
+1
-1
@@ -24,7 +24,7 @@ int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _
|
||||
// 3. 为按钮设置点击事件(使用Lambda表达式)
|
||||
myButton->setOnClickListener([&mainWindow]() {
|
||||
// 使用消息框工厂创建模态对话框
|
||||
auto result = StellarX::MessageBox::ShowModal(
|
||||
auto result = StellarX::MessageBox::showModal(
|
||||
mainWindow,
|
||||
"欢迎使用星垣GUI\r\n作者:我在人间做废物",
|
||||
"问候",
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
auto blackColor = RGB(202, 255, 255);
|
||||
char initData[33] = "00000000000000000000000000000000";//初始数据
|
||||
bool gSigned = false; //是否为有符号数
|
||||
void main()
|
||||
{
|
||||
Window mainWindow(700,500,NULL,RGB(255,255,255), "寄存器查看工具 V1.0——我在人间做废物 (同类工具定制:3150131407(Q / V))");
|
||||
|
||||
int main()
|
||||
{
|
||||
Window mainWindow(700, 510, NULL, RGB(255, 255, 255), "寄存器查看工具 V1.0——我在人间做废物 (同类工具定制:3150131407(Q / V))");
|
||||
|
||||
//选择区控件
|
||||
auto selectionAreaLabel = std::make_unique<Label>(18, 0,"32位选择区");
|
||||
auto selectionAreaLabel = std::make_unique<Label>(18, 0, "32位选择区");
|
||||
selectionAreaLabel->setTextdisap(true);
|
||||
std::vector<std::unique_ptr<Label>>selectionAreaButtonLabel;
|
||||
std::vector<std::unique_ptr<Button>>selectionAreaButton;
|
||||
@@ -21,22 +21,22 @@ void main()
|
||||
|
||||
selectionArea->setCanvasBkColor(blackColor);
|
||||
selectionArea->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
|
||||
for (int y = 0; y < 2; y ++)
|
||||
|
||||
for (int y = 0; y < 2; y++)
|
||||
{
|
||||
std::ostringstream os;
|
||||
for (int x = 0; x <16; x++)
|
||||
for (int x = 0; x < 16; x++)
|
||||
{
|
||||
if (0 == y)
|
||||
{
|
||||
selectionAreaButtonLabel.push_back(std::make_unique<Label>(x * 35 + 40 + 28 * (x / 4), 26, "", RGB(208, 208, 208)));
|
||||
selectionAreaButtonLabel.push_back(std::make_unique<Label>(x * 35 + 25 + 28 * (x / 4), 26, "", RGB(208, 208, 208)));
|
||||
os << std::setw(2) << std::setfill('0') << 31 - x;
|
||||
selectionAreaButtonLabel.back()->setText(os.str());
|
||||
selectionAreaButtonLabel.back()->setTextdisap(true);
|
||||
|
||||
selectionAreaButton.push_back(
|
||||
std::make_unique<Button>(x * 35 + 42 + 28 * (x / 4), 58,20,32,"0",
|
||||
blackColor,RGB(171, 196, 220),StellarX::ButtonMode::TOGGLE));
|
||||
std::make_unique<Button>(x * 35 + 27 + 28 * (x / 4), 58, 25, 30, "0",
|
||||
blackColor, RGB(171, 196, 220), StellarX::ButtonMode::TOGGLE));
|
||||
selectionAreaButton.back()->textStyle.color = RGB(226, 116, 152);
|
||||
selectionAreaButton.back()->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
selectionAreaButton_ptr.push_back(selectionAreaButton.back().get());
|
||||
@@ -55,19 +55,19 @@ void main()
|
||||
}
|
||||
else
|
||||
{
|
||||
selectionAreaButtonLabel.push_back(std::make_unique<Label>(x * 35 + 40 + 28 * (x / 4), 90, "", RGB(208, 208, 208)));
|
||||
os << std::setw(2) << std::setfill('0') << 15-x;
|
||||
selectionAreaButtonLabel.push_back(std::make_unique<Label>(x * 35 + 25 + 28 * (x / 4), 90, "", RGB(208, 208, 208)));
|
||||
os << std::setw(2) << std::setfill('0') << 15 - x;
|
||||
selectionAreaButtonLabel.back()->setText(os.str());
|
||||
selectionAreaButtonLabel.back()->setTextdisap(true);
|
||||
|
||||
selectionAreaButton.push_back(
|
||||
std::make_unique<Button>(x * 35 + 42 + 28 * (x / 4), 120, 20, 32, "0",
|
||||
std::make_unique<Button>(x * 35 + 27 + 28 * (x / 4), 120, 25, 30, "0",
|
||||
blackColor, RGB(171, 196, 220), StellarX::ButtonMode::TOGGLE));
|
||||
selectionAreaButton.back()->textStyle.color = RGB(226, 116, 152);
|
||||
selectionAreaButton.back()->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
selectionAreaButton_ptr.push_back(selectionAreaButton.back().get());
|
||||
int k =15 - x;
|
||||
selectionAreaButton.back()->setOnToggleOnListener([k,btn = selectionAreaButton_ptr.back()]()
|
||||
int k = 15 - x;
|
||||
selectionAreaButton.back()->setOnToggleOnListener([k, btn = selectionAreaButton_ptr.back()]()
|
||||
{
|
||||
btn->setButtonText("1");
|
||||
initData[k] = '1';
|
||||
@@ -78,8 +78,8 @@ void main()
|
||||
initData[k] = '0';
|
||||
});
|
||||
}
|
||||
os.str("");
|
||||
os.clear();
|
||||
os.str("");
|
||||
os.clear();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -90,25 +90,34 @@ void main()
|
||||
selectionArea->addControl(std::move(s));
|
||||
//功能区控件
|
||||
//功能区总容器
|
||||
auto function = std::make_unique<Canvas>(0, 0, 0, 0);
|
||||
auto function = std::make_unique<Canvas>(10, 170, 680, 70);
|
||||
function->setCanvasfillMode(StellarX::FillMode::Null);
|
||||
|
||||
auto bitInvert = std::make_unique<Canvas>(10,170,220,70);
|
||||
auto leftShift = std::make_unique<Canvas>(240, 170, 220, 70);
|
||||
auto rightShift = std::make_unique<Canvas>(470, 170, 220, 70);
|
||||
function->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
function->setCanvasBkColor(blackColor);
|
||||
auto bitInvert_que = std::make_unique<Canvas>(0, 0, 220, 70);
|
||||
auto leftShift_que = std::make_unique<Canvas>(230, 0, 220, 70);
|
||||
auto rightShift_que = std::make_unique<Canvas>(460, 0, 220, 70);
|
||||
|
||||
auto bitInvert = bitInvert_que.get();
|
||||
auto leftShift = leftShift_que.get();
|
||||
auto rightShift = rightShift_que.get();
|
||||
|
||||
bitInvert->setCanvasBkColor(blackColor);
|
||||
bitInvert->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
leftShift->setCanvasBkColor(blackColor);
|
||||
leftShift->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
rightShift->setCanvasBkColor(blackColor);
|
||||
rightShift->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
|
||||
|
||||
auto bitInvertLabel = std::make_unique<Label>(18,160,"位取反");
|
||||
|
||||
function->addControl(std::move(bitInvert_que));
|
||||
function->addControl(std::move(leftShift_que));
|
||||
function->addControl(std::move(rightShift_que));
|
||||
|
||||
auto bitInvertLabel = std::make_unique<Label>(13, -10, "位取反");
|
||||
bitInvertLabel->setTextdisap(true);
|
||||
auto leftShiftLabel = std::make_unique<Label>(248, 160, "左移位");
|
||||
auto leftShiftLabel = std::make_unique<Label>(13, -10, "左移位");
|
||||
leftShiftLabel->setTextdisap(true);
|
||||
auto rightShiftLabel = std::make_unique<Label>(478, 160, "右移位");
|
||||
auto rightShiftLabel = std::make_unique<Label>(13, -10, "右移位");
|
||||
rightShiftLabel->setTextdisap(true);
|
||||
|
||||
// ====== 公用小工具======
|
||||
@@ -139,22 +148,22 @@ void main()
|
||||
|
||||
//取反区控件
|
||||
std::array<std::unique_ptr<Label>, 4> bitInvertFunctionLabel;
|
||||
bitInvertFunctionLabel[0] = std::make_unique<Label>(35, 180, "低位");
|
||||
bitInvertFunctionLabel[1] = std::make_unique<Label>(90, 180, "高位");
|
||||
bitInvertFunctionLabel[2] = std::make_unique<Label>(15, 198, "从");
|
||||
bitInvertFunctionLabel[3] = std::make_unique<Label>(75, 198, "到");
|
||||
bitInvertFunctionLabel[0] = std::make_unique<Label>(30, 10, "低位");
|
||||
bitInvertFunctionLabel[1] = std::make_unique<Label>(90, 10, "高位");
|
||||
bitInvertFunctionLabel[2] = std::make_unique<Label>(15, 38, "从");
|
||||
bitInvertFunctionLabel[3] = std::make_unique<Label>(75, 38, "到");
|
||||
|
||||
std::array<std::unique_ptr<TextBox>, 2> bitInvertFunctionTextBox;
|
||||
bitInvertFunctionTextBox[0] = std::make_unique<TextBox>(35, 203, 35, 30, "0");
|
||||
bitInvertFunctionTextBox[1] = std::make_unique<TextBox>(95, 203, 35, 30, "0");
|
||||
bitInvertFunctionTextBox[0] = std::make_unique<TextBox>(35, 35, 35, 30, "0");
|
||||
bitInvertFunctionTextBox[1] = std::make_unique<TextBox>(95, 35, 35, 30, "0");
|
||||
auto invL = bitInvertFunctionTextBox[0].get();
|
||||
auto invH = bitInvertFunctionTextBox[1].get();
|
||||
auto bitInvertFunctionButton = std::make_unique<Button>(150,195, 70, 35, "位取反",
|
||||
auto bitInvertFunctionButton = std::make_unique<Button>(135, 35, 80, 30, "位取反",
|
||||
blackColor, RGB(171, 196, 220));
|
||||
bitInvertFunctionButton->textStyle.color = RGB(226, 116, 152);
|
||||
bitInvertFunctionButton->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto bitInvertFunctionButton_ptr = bitInvertFunctionButton.get();
|
||||
|
||||
|
||||
bitInvert->addControl(std::move(bitInvertFunctionButton));
|
||||
bitInvert->addControl(std::move(bitInvertLabel));
|
||||
for (auto& b : bitInvertFunctionTextBox)
|
||||
@@ -171,22 +180,22 @@ void main()
|
||||
bitInvert->addControl(std::move(b));
|
||||
}
|
||||
//左移控件
|
||||
auto leftShiftFunctionLabel = std::make_unique<Label>(435, 198, "位");
|
||||
auto leftShiftFunctionLabel = std::make_unique<Label>(198, 30, "位");
|
||||
leftShiftFunctionLabel->setTextdisap(true);
|
||||
|
||||
auto leftShiftFunctionTextBox = std::make_unique<TextBox>(325, 195, 100, 30, "0");
|
||||
auto leftShiftFunctionTextBox = std::make_unique<TextBox>(90, 30, 100, 30, "0");
|
||||
leftShiftFunctionTextBox->setMaxCharLen(3);
|
||||
leftShiftFunctionTextBox->textStyle.color = RGB(226, 116, 152);
|
||||
leftShiftFunctionTextBox->setTextBoxBk(RGB(244, 234, 142));
|
||||
leftShiftFunctionTextBox->setTextBoxshape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto shlBox = leftShiftFunctionTextBox.get();
|
||||
auto leftShiftFunctionButton = std::make_unique<Button>(250, 195, 60, 30, "左移",
|
||||
auto leftShiftFunctionButton = std::make_unique<Button>(15, 30, 60, 30, "左移",
|
||||
blackColor, RGB(171, 196, 220));
|
||||
leftShiftFunctionButton->textStyle.color = RGB(226, 116, 152);
|
||||
leftShiftFunctionButton->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto leftShiftFunctionButton_ptr = leftShiftFunctionButton.get();
|
||||
|
||||
|
||||
|
||||
|
||||
leftShift->addControl(std::move(leftShiftFunctionButton));
|
||||
leftShift->addControl(std::move(leftShiftFunctionTextBox));
|
||||
|
||||
@@ -194,47 +203,44 @@ void main()
|
||||
leftShift->addControl(std::move(leftShiftFunctionLabel));
|
||||
|
||||
//右移控件
|
||||
auto rightShiftFunctionLabel = std::make_unique<Label>(665, 198, "位");
|
||||
auto rightShiftFunctionLabel = std::make_unique<Label>(198, 30, "位");
|
||||
rightShiftFunctionLabel->setTextdisap(true);
|
||||
auto rightShiftFunctionTextBox = std::make_unique<TextBox>(555, 195, 100, 30, "0");
|
||||
auto rightShiftFunctionTextBox = std::make_unique<TextBox>(90, 30, 100, 30, "0");
|
||||
rightShiftFunctionTextBox->setMaxCharLen(3);
|
||||
rightShiftFunctionTextBox->textStyle.color = RGB(226, 116, 152);
|
||||
rightShiftFunctionTextBox->setTextBoxBk(RGB(244, 234, 142));
|
||||
rightShiftFunctionTextBox->setTextBoxshape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto shrBox = rightShiftFunctionTextBox.get();
|
||||
|
||||
auto rightShiftFunctionButton = std::make_unique<Button>(480, 195, 60, 30, "右移",
|
||||
auto rightShiftFunctionButton = std::make_unique<Button>(15, 30, 60, 30, "右移",
|
||||
blackColor, RGB(171, 196, 220));
|
||||
rightShiftFunctionButton->textStyle.color = RGB(226, 116, 152);
|
||||
rightShiftFunctionButton->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto rightShiftFunctionButton_ptr = rightShiftFunctionButton.get();
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
rightShift->addControl(std::move(rightShiftFunctionButton));
|
||||
|
||||
rightShift->addControl(std::move(rightShiftFunctionTextBox));
|
||||
rightShift->addControl(std::move(rightShiftLabel));
|
||||
rightShift->addControl(std::move(rightShiftFunctionLabel));
|
||||
|
||||
function->addControl(std::move(bitInvert));
|
||||
function->addControl(std::move(leftShift));
|
||||
function->addControl(std::move(rightShift));
|
||||
|
||||
|
||||
//显示区控件
|
||||
//数值显示
|
||||
auto NumericalDisplayArea = std::make_unique<Canvas>(10, 255, 680, 70);
|
||||
NumericalDisplayArea->setCanvasBkColor(blackColor);
|
||||
NumericalDisplayArea->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
|
||||
|
||||
std::array<std::unique_ptr<Label>, 3> NumericalDisplayAreaLabel;
|
||||
NumericalDisplayAreaLabel[0] = std::make_unique<Label>(18, 245, "数值显示区");
|
||||
NumericalDisplayAreaLabel[1] = std::make_unique<Label>(20, 278, "十六进制");
|
||||
NumericalDisplayAreaLabel[2] = std::make_unique<Label>(330, 278, "十进制");
|
||||
NumericalDisplayAreaLabel[0] = std::make_unique<Label>(18, -10, "数值显示区");
|
||||
NumericalDisplayAreaLabel[1] = std::make_unique<Label>(20, 25, "十六进制");
|
||||
NumericalDisplayAreaLabel[2] = std::make_unique<Label>(330, 25, "十进制");
|
||||
|
||||
std::array<std::unique_ptr<TextBox>, 2> NumericalDisplayAreaTextBox;
|
||||
NumericalDisplayAreaTextBox[0] = std::make_unique<TextBox>(110, 275, 200, 30, "0");
|
||||
NumericalDisplayAreaTextBox[1] = std::make_unique<TextBox>(400, 275, 200, 30, "0");
|
||||
NumericalDisplayAreaTextBox[0] = std::make_unique<TextBox>(110, 25, 200, 30, "0");
|
||||
NumericalDisplayAreaTextBox[1] = std::make_unique<TextBox>(400, 25, 200, 30, "0");
|
||||
auto hex = NumericalDisplayAreaTextBox[0].get();
|
||||
auto dec = NumericalDisplayAreaTextBox[1].get();
|
||||
|
||||
@@ -257,15 +263,15 @@ void main()
|
||||
auto BinaryDisplayArea = std::make_unique<Canvas>(10, 335, 680, 110);
|
||||
BinaryDisplayArea->setCanvasBkColor(blackColor);
|
||||
BinaryDisplayArea->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
|
||||
|
||||
std::array<std::unique_ptr<Label>, 3> BinaryDisplayAreaLabel;
|
||||
BinaryDisplayAreaLabel[0] = std::make_unique<Label>(18, 325, "二进制显示区");
|
||||
BinaryDisplayAreaLabel[1] = std::make_unique<Label>(35, 353, "上次值");
|
||||
BinaryDisplayAreaLabel[2] = std::make_unique<Label>(35, 400, "本次值");
|
||||
BinaryDisplayAreaLabel[0] = std::make_unique<Label>(18, -10, "二进制显示区");
|
||||
BinaryDisplayAreaLabel[1] = std::make_unique<Label>(35, 20, "上次值");
|
||||
BinaryDisplayAreaLabel[2] = std::make_unique<Label>(35, 67, "本次值");
|
||||
|
||||
std::array<std::unique_ptr<TextBox>, 2> BinaryDisplayAreaTextBox;
|
||||
BinaryDisplayAreaTextBox[0] = std::make_unique<TextBox>(110, 350, 520, 30, "0000_0000_0000_0000_0000_0000_0000_0000");
|
||||
BinaryDisplayAreaTextBox[1] = std::make_unique<TextBox>(110, 400, 520, 30, "0000_0000_0000_0000_0000_0000_0000_0000");
|
||||
BinaryDisplayAreaTextBox[0] = std::make_unique<TextBox>(110, 20, 520, 30, "0000_0000_0000_0000_0000_0000_0000_0000");
|
||||
BinaryDisplayAreaTextBox[1] = std::make_unique<TextBox>(110, 67, 520, 30, "0000_0000_0000_0000_0000_0000_0000_0000");
|
||||
auto Last = BinaryDisplayAreaTextBox[0].get();
|
||||
auto This = BinaryDisplayAreaTextBox[1].get();
|
||||
|
||||
@@ -366,17 +372,17 @@ void main()
|
||||
auto configuration = std::make_unique<Canvas>(10, 455, 680, 40);
|
||||
configuration->setCanvasBkColor(blackColor);
|
||||
configuration->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
|
||||
|
||||
auto configurationLabel = std::make_unique<Label>(20, 445, "配置区");
|
||||
|
||||
auto configurationLabel = std::make_unique<Label>(20, -10, "配置区");
|
||||
configurationLabel->setTextdisap(true);
|
||||
|
||||
std::array<std::unique_ptr<Button>,2> configurationButton;
|
||||
configurationButton[0] = std::make_unique<Button>(450, 465, 80, 20, "一键置0",
|
||||
std::array<std::unique_ptr<Button>, 2> configurationButton;
|
||||
configurationButton[0] = std::make_unique<Button>(420, 10, 90, 20, "一键置0",
|
||||
blackColor, RGB(171, 196, 220));
|
||||
configurationButton[0]->textStyle.color = RGB(226, 116, 152);
|
||||
configurationButton[0]->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
|
||||
configurationButton[1] = std::make_unique<Button>(550, 465, 80, 20, "一键置1",
|
||||
|
||||
configurationButton[1] = std::make_unique<Button>(530, 10, 90, 20, "一键置1",
|
||||
blackColor, RGB(171, 196, 220));
|
||||
configurationButton[1]->textStyle.color = RGB(226, 116, 152);
|
||||
configurationButton[1]->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
@@ -419,16 +425,16 @@ void main()
|
||||
|
||||
|
||||
auto signedToggle = std::make_unique<Button>(
|
||||
350, 465, 80, 20, "无符号",
|
||||
330, 10, 80, 20, "无符号",
|
||||
blackColor, RGB(171, 196, 220), StellarX::ButtonMode::TOGGLE);
|
||||
signedToggle->textStyle.color = RGB(226, 116, 152);
|
||||
signedToggle->setButtonShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
auto* signedTogglePtr = signedToggle.get();
|
||||
|
||||
|
||||
signedTogglePtr->setOnToggleOnListener([&]() {
|
||||
gSigned = true;
|
||||
signedTogglePtr->setButtonText("有符号");
|
||||
|
||||
StellarX::MessageBox::showModal(mainWindow, "有符号模式下,\n最高位为符号位,\n其余位为数值位。", "有符号模式");
|
||||
// 立即刷新十进制显示:用当前位图算出新值,仅改 dec
|
||||
auto cur = snapshotBits();
|
||||
const uint32_t u = [&] { uint32_t v = 0; for (int b = 0; b < 32; ++b) if (cur[b]) v |= (1u << b); return v; }();
|
||||
@@ -438,19 +444,20 @@ void main()
|
||||
signedTogglePtr->setOnToggleOffListener([&]() {
|
||||
gSigned = false;
|
||||
signedTogglePtr->setButtonText("无符号");
|
||||
|
||||
StellarX::MessageBox::showAsync(mainWindow, "无符号模式下,\n所有位均为数值位。", "无符号模式");
|
||||
auto cur = snapshotBits();
|
||||
const uint32_t u = [&] { uint32_t v = 0; for (int b = 0; b < 32; ++b) if (cur[b]) v |= (1u << b); return v; }();
|
||||
dec->setText(std::to_string(u));
|
||||
});
|
||||
|
||||
signedTogglePtr->enableTooltip(true);
|
||||
signedTogglePtr->setTooltipTextsForToggle("切换无符号模式", "切换有符号模式");
|
||||
|
||||
configuration->addControl(std::move(configurationButton[0]));
|
||||
configuration->addControl(std::move(configurationButton[1]));
|
||||
configuration->addControl(std::move(signedToggle));
|
||||
configuration->addControl(std::move(configurationLabel));
|
||||
|
||||
|
||||
mainWindow.addControl(std::move(selectionArea));
|
||||
mainWindow.addControl(std::move(function));
|
||||
mainWindow.addControl(std::move(NumericalDisplayArea));
|
||||
@@ -459,4 +466,4 @@ void main()
|
||||
|
||||
mainWindow.draw();
|
||||
return mainWindow.runEventLoop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// 本Demo基于 StellarX 构建,轻量级的 Windows GUI 框架。
|
||||
#include"StellarX.h"
|
||||
|
||||
int main()
|
||||
{
|
||||
Window win(1300, 800, NULL, RGB(255, 255, 0), "记账管理系统");
|
||||
|
||||
/*********登录界面***********/
|
||||
//标签
|
||||
std::unique_ptr<Label> logIn_label[3];
|
||||
Label* p[3];
|
||||
logIn_label[0] = std::make_unique<Label>(90, 150, "欢迎使用餐馆记账管理系统");
|
||||
logIn_label[1] = std::make_unique<Label>(400, 300, "账号");
|
||||
logIn_label[2] = std::make_unique<Label>(400, 400, "密码");
|
||||
p[0] = logIn_label[0].get();
|
||||
for (auto& log : logIn_label)
|
||||
{
|
||||
log->setTextdisap(true);
|
||||
log->setLayoutMode(StellarX::LayoutMode::AnchorToEdges);
|
||||
log->textStyle.lpszFace = "华文行楷";
|
||||
}
|
||||
logIn_label[0]->textStyle.nHeight = 100;
|
||||
logIn_label[0]->setAnchor(StellarX::Anchor::Top, StellarX::Anchor::NoAnchor);
|
||||
logIn_label[1]->textStyle.nHeight = 50;
|
||||
logIn_label[1]->setAnchor(StellarX::Anchor::Bottom, StellarX::Anchor::NoAnchor);
|
||||
logIn_label[2]->textStyle.nHeight = 50;
|
||||
logIn_label[2]->setAnchor(StellarX::Anchor::Bottom, StellarX::Anchor::NoAnchor);
|
||||
|
||||
//输入框
|
||||
std::unique_ptr<TextBox> logIn_textBox[2];
|
||||
TextBox* logIn_textBox_ptr[2];
|
||||
logIn_textBox[0] = std::make_unique<TextBox>(500, 295, 450, 50);
|
||||
logIn_textBox[1] = std::make_unique<TextBox>(500, 395, 450, 50);
|
||||
logIn_textBox_ptr[0] = logIn_textBox[0].get();
|
||||
logIn_textBox_ptr[1] = logIn_textBox[1].get();
|
||||
for (auto& tb : logIn_textBox)
|
||||
{
|
||||
tb->setLayoutMode(StellarX::LayoutMode::AnchorToEdges);
|
||||
tb->setAnchor(StellarX::Anchor::Bottom, StellarX::Anchor::NoAnchor);
|
||||
tb->setMaxCharLen(15);
|
||||
}
|
||||
//按钮
|
||||
std::unique_ptr<Button> logIn_Button[2];
|
||||
Button* logIn_Button_ptr[2];
|
||||
logIn_Button[0] = std::make_unique<Button>(350, 500, 300, 50, "管理员登录");
|
||||
logIn_Button[1] = std::make_unique<Button>(750, 500, 300, 50, "操作员登录");
|
||||
logIn_Button_ptr[0] = logIn_Button[0].get();
|
||||
logIn_Button_ptr[1] = logIn_Button[1].get();
|
||||
for (auto& b : logIn_Button)
|
||||
{
|
||||
b->setLayoutMode(StellarX::LayoutMode::AnchorToEdges);
|
||||
b->setAnchor(StellarX::Anchor::Bottom, StellarX::Anchor::NoAnchor);
|
||||
}
|
||||
//log画布
|
||||
auto log_Canvas = std::make_unique<Canvas>(0, 0, 1300, 800);
|
||||
Canvas* log_Canvas_ptr = log_Canvas.get();
|
||||
log_Canvas_ptr->setCanvasfillMode(StellarX::FillMode::Null);
|
||||
log_Canvas_ptr->setShape(StellarX::ControlShape::B_RECTANGLE);
|
||||
log_Canvas_ptr->setLayoutMode(StellarX::LayoutMode::AnchorToEdges);
|
||||
log_Canvas_ptr->setAnchor(StellarX::Anchor::Bottom, StellarX::Anchor::Top);
|
||||
|
||||
//将log界面控价加入logCanvas统一管理
|
||||
for (auto& b : logIn_Button)
|
||||
log_Canvas_ptr->addControl(std::move(b));
|
||||
for (auto& tb : logIn_textBox)
|
||||
log_Canvas_ptr->addControl(std::move(tb));
|
||||
for (auto& la : logIn_label)
|
||||
log_Canvas_ptr->addControl(std::move(la));
|
||||
|
||||
/**************业务UI****************/
|
||||
|
||||
auto tabControl = std::make_unique<TabControl>(10, 10, 1280, 780);
|
||||
auto tabControl_ptr = tabControl.get();
|
||||
tabControl_ptr->setIsVisible(false);
|
||||
tabControl_ptr->setCanvasfillMode(StellarX::FillMode::Null);
|
||||
tabControl_ptr->setShape(StellarX::ControlShape::ROUND_RECTANGLE);
|
||||
tabControl_ptr->setTabPlacement(StellarX::TabPlacement::Left);
|
||||
tabControl_ptr->setTabBarHeight(100);
|
||||
//添加页签及页
|
||||
auto tabP = std::make_pair(std::make_unique<Button>(0, 0, 100, 100, "点餐"), std::make_unique<Canvas>(0, 0, 1290, 790));
|
||||
tabP.second->setCanvasfillMode(StellarX::FillMode::Null);
|
||||
tabP.second->setShape(StellarX::ControlShape::ROUND_RECTANGLE);
|
||||
|
||||
tabControl_ptr->add(std::move(tabP));
|
||||
|
||||
/*------------login事件-------------*/
|
||||
//管理员登录按钮事件
|
||||
logIn_Button_ptr[0]->setOnClickListener([&p, &tabControl_ptr, &log_Canvas_ptr, &logIn_textBox_ptr, &win]()
|
||||
{
|
||||
if ("\0" == logIn_textBox_ptr[0]->getText() || "\0" == logIn_textBox_ptr[1]->getText())
|
||||
{
|
||||
if ("\0" == logIn_textBox_ptr[0]->getText())logIn_textBox_ptr[0]->setTextBoxBk(RGB(255, 0, 0));
|
||||
if ("\0" == logIn_textBox_ptr[1]->getText())logIn_textBox_ptr[1]->setTextBoxBk(RGB(255, 0, 0));
|
||||
std::cout << "\a";
|
||||
StellarX::MessageBox::showModal(win, "账号或密码不能为空!", "提示");
|
||||
}
|
||||
else
|
||||
{
|
||||
log_Canvas_ptr->setIsVisible(false);
|
||||
tabControl_ptr->setIsVisible(true);
|
||||
win.draw("image\\bk1.jpg");
|
||||
}
|
||||
});
|
||||
//操作员登录按钮事件
|
||||
logIn_Button_ptr[1]->setOnClickListener([&tabControl_ptr, &log_Canvas_ptr, &logIn_textBox_ptr, &win]()
|
||||
{
|
||||
if ("\0" == logIn_textBox_ptr[0]->getText() || "\0" == logIn_textBox_ptr[1]->getText())
|
||||
{
|
||||
if ("\0" == logIn_textBox_ptr[0]->getText())logIn_textBox_ptr[0]->setTextBoxBk(RGB(255, 0, 0));
|
||||
if ("\0" == logIn_textBox_ptr[1]->getText())logIn_textBox_ptr[1]->setTextBoxBk(RGB(255, 0, 0));
|
||||
std::cout << "\a";
|
||||
StellarX::MessageBox::showModal(win, "账号或密码不能为空!", "提示");
|
||||
}
|
||||
else
|
||||
{
|
||||
log_Canvas_ptr->setIsVisible(false);
|
||||
tabControl_ptr->setIsVisible(true);
|
||||
win.draw("image\\bk1.jpg");
|
||||
}
|
||||
});
|
||||
|
||||
win.addControl(std::move(log_Canvas));
|
||||
win.addControl(std::move(tabControl));
|
||||
win.draw("image\\bk1.jpg");
|
||||
|
||||
return win.runEventLoop();
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 87 KiB |
+137
-144
@@ -21,174 +21,167 @@
|
||||
#include "Control.h"
|
||||
#include"label.h"
|
||||
|
||||
|
||||
#define DISABLEDCOLOUR RGB(96, 96, 96) //禁用状态颜色
|
||||
#define TEXTMARGINS_X 6
|
||||
#define TEXTMARGINS_X 6
|
||||
#define TEXTMARGINS_Y 4
|
||||
constexpr int bordWith = 1; //边框宽度,用于快照恢复时的偏移计算
|
||||
constexpr int bordHeight = 1; //边框高度,用于快照恢复时的偏移计算
|
||||
|
||||
class Button : public Control
|
||||
{
|
||||
|
||||
std::string text; // 按钮上的文字
|
||||
bool click; // 是否被点击
|
||||
bool hover; // 是否被悬停
|
||||
std::string text; // 按钮上的文字
|
||||
bool click; // 是否被点击
|
||||
bool hover; // 是否被悬停
|
||||
|
||||
std::string cutText; // 切割后的文本
|
||||
bool needCutText = true; // 是否需要切割文本
|
||||
bool isUseCutText = false; // 是否使用切割文本
|
||||
int padX = TEXTMARGINS_X; // 文本最小左右内边距
|
||||
int padY = TEXTMARGINS_Y; // 文本最小上下内边距
|
||||
std::string cutText; // 切割后的文本
|
||||
bool needCutText = true; // 是否需要切割文本
|
||||
bool isUseCutText = false; // 是否使用切割文本
|
||||
int padX = TEXTMARGINS_X; // 文本最小左右内边距
|
||||
int padY = TEXTMARGINS_Y; // 文本最小上下内边距
|
||||
|
||||
COLORREF buttonTrueColor; // 按钮被点击后的颜色
|
||||
COLORREF buttonFalseColor; // 按钮未被点击的颜色
|
||||
COLORREF buttonHoverColor; // 按钮被鼠标悬停的颜色
|
||||
COLORREF buttonBorderColor = RGB(0,0,0);// 按钮边框颜色
|
||||
COLORREF buttonTrueColor; // 按钮被点击后的颜色
|
||||
COLORREF buttonFalseColor; // 按钮未被点击的颜色
|
||||
COLORREF buttonHoverColor; // 按钮被鼠标悬停的颜色
|
||||
COLORREF buttonBorderColor = RGB(0, 0, 0);// 按钮边框颜色
|
||||
|
||||
StellarX::ButtonMode mode; // 按钮模式
|
||||
StellarX::ControlShape shape; // 按钮形状
|
||||
StellarX::ButtonMode mode; // 按钮模式
|
||||
StellarX::ControlShape shape; // 按钮形状
|
||||
|
||||
StellarX::FillMode buttonFillMode = StellarX::FillMode::Solid; //按钮填充模式
|
||||
StellarX::FillStyle buttonFillIma = StellarX::FillStyle::BDiagonal; //按钮填充图案
|
||||
IMAGE* buttonFileIMAGE = nullptr; //按钮填充图像
|
||||
StellarX::FillMode buttonFillMode = StellarX::FillMode::Solid; //按钮填充模式
|
||||
StellarX::FillStyle buttonFillIma = StellarX::FillStyle::BDiagonal; //按钮填充图案
|
||||
IMAGE* buttonFileIMAGE = nullptr; //按钮填充图像
|
||||
|
||||
|
||||
|
||||
std::function<void()> onClickCallback; //回调函数
|
||||
std::function<void()> onToggleOnCallback; //TOGGLE模式下的回调函数
|
||||
std::function<void()> onToggleOffCallback; //TOGGLE模式下的回调函数
|
||||
std::function<void()> onClickCallback; //回调函数
|
||||
std::function<void()> onToggleOnCallback; //TOGGLE模式下的回调函数
|
||||
std::function<void()> onToggleOffCallback; //TOGGLE模式下的回调函数
|
||||
|
||||
StellarX::ControlText oldStyle = textStyle; // 按钮文字样式
|
||||
int oldtext_width = -1;
|
||||
int oldtext_height = -1;
|
||||
int text_width = 0;
|
||||
int text_height = 0;
|
||||
StellarX::ControlText oldStyle = textStyle; // 按钮文字样式
|
||||
int oldtext_width = -1;
|
||||
int oldtext_height = -1;
|
||||
int text_width = 0;
|
||||
int text_height = 0;
|
||||
|
||||
// === Tooltip ===
|
||||
bool tipEnabled = false; // 是否启用
|
||||
bool tipVisible = false; // 当前是否显示
|
||||
bool tipFollowCursor = false; // 是否跟随鼠标
|
||||
bool tipUserOverride = false; // 是否用户自定义了tip文本
|
||||
int tipDelayMs = 1000; // 延时(毫秒)
|
||||
int tipOffsetX = 12; // 相对鼠标偏移
|
||||
int tipOffsetY = 18;
|
||||
ULONGLONG tipHoverTick = 0; // 开始悬停的时间戳
|
||||
int lastMouseX = 0; // 最新鼠标位置(用于定位)
|
||||
int lastMouseY = 0;
|
||||
// === Tooltip ===
|
||||
bool tipEnabled = false; // 是否启用
|
||||
bool tipVisible = false; // 当前是否显示
|
||||
bool tipFollowCursor = false; // 是否跟随鼠标
|
||||
bool tipUserOverride = false; // 是否用户自定义了tip文本
|
||||
int tipDelayMs = 1000; // 延时(毫秒)
|
||||
int tipOffsetX = 12; // 相对鼠标偏移
|
||||
int tipOffsetY = 18;
|
||||
ULONGLONG tipHoverTick = 0; // 开始悬停的时间戳
|
||||
int lastMouseX = 0; // 最新鼠标位置(用于定位)
|
||||
int lastMouseY = 0;
|
||||
|
||||
std::string tipTextClick; //NORMAL 模式下用
|
||||
std::string tipTextOn; // click==true 时用
|
||||
std::string tipTextOff; // click==false 时用
|
||||
Label tipLabel; // 直接复用Label作为提示
|
||||
|
||||
public:
|
||||
StellarX::ControlText textStyle; // 按钮文字样式
|
||||
std::string tipTextClick; // NORMAL 模式下用
|
||||
std::string tipTextOn; // click==true 时用
|
||||
std::string tipTextOff; // click==false 时用
|
||||
Label tipLabel; // 直接复用Label作为提示
|
||||
|
||||
public:
|
||||
|
||||
//默认按钮颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//自定义按钮未被点击和被点击颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
COLORREF ct, COLORREF cf, StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL,
|
||||
StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//自定义按钮颜色和悬停颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
COLORREF ct, COLORREF cf,COLORREF ch,
|
||||
StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//析构函数 释放图形指针内存
|
||||
~Button();
|
||||
StellarX::ControlText textStyle; // 按钮文字样式
|
||||
|
||||
//绘制按钮
|
||||
void draw() override;
|
||||
//按钮事件处理
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
|
||||
//设置回调函数
|
||||
void setOnClickListener(const std::function<void()>&& callback);
|
||||
//设置TOGGLE模式下被点击的回调函数
|
||||
void setOnToggleOnListener(const std::function<void()>&& callback);
|
||||
//设置TOGGLE模式下取消点击的回调函数
|
||||
void setOnToggleOffListener(const std::function<void()>&& callback);
|
||||
//设置按钮模式
|
||||
void setbuttonMode(StellarX::ButtonMode mode);
|
||||
//设置圆角矩形椭圆宽度
|
||||
void setROUND_RECTANGLEwidth(int width);
|
||||
//设置圆角矩形椭圆高度
|
||||
void setROUND_RECTANGLEheight(int height);
|
||||
//设置按钮填充模式
|
||||
void setFillMode(StellarX::FillMode mode);
|
||||
//设置按钮填充图案
|
||||
void setFillIma(StellarX::FillStyle ima);
|
||||
//设置按钮填充图像
|
||||
void setFillIma(std::string imaName);
|
||||
//设置按钮边框颜色
|
||||
void setButtonBorder(COLORREF Border);
|
||||
//设置按钮未被点击颜色
|
||||
void setButtonFalseColor(COLORREF color);
|
||||
//设置按钮文本
|
||||
void setButtonText(const char* text);
|
||||
void setButtonText(std::string text);
|
||||
//设置按钮形状
|
||||
void setButtonShape(StellarX::ControlShape shape);
|
||||
//设置按钮点击状态
|
||||
void setButtonClick(BOOL click);
|
||||
public:
|
||||
|
||||
//判断按钮是否被点击
|
||||
bool isClicked() const;
|
||||
|
||||
//获取按钮文字
|
||||
std::string getButtonText() const;
|
||||
const char* getButtonText_c() const;
|
||||
//获取按钮模式
|
||||
StellarX::ButtonMode getButtonMode() const;
|
||||
//获取按钮形状
|
||||
StellarX::ControlShape getButtonShape() const;
|
||||
//获取按钮填充模式
|
||||
StellarX::FillMode getFillMode() const;
|
||||
//默认按钮颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//自定义按钮未被点击和被点击颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
COLORREF ct, COLORREF cf, StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL,
|
||||
StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//自定义按钮颜色和悬停颜色
|
||||
Button(int x, int y, int width, int height, const std::string text,
|
||||
COLORREF ct, COLORREF cf, COLORREF ch,
|
||||
StellarX::ButtonMode mode = StellarX::ButtonMode::NORMAL, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
//析构函数 释放图形指针内存
|
||||
~Button();
|
||||
|
||||
//绘制按钮
|
||||
void draw() override;
|
||||
//按钮事件处理
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
|
||||
//设置回调函数
|
||||
void setOnClickListener(const std::function<void()>&& callback);
|
||||
//设置TOGGLE模式下被点击的回调函数
|
||||
void setOnToggleOnListener(const std::function<void()>&& callback);
|
||||
//设置TOGGLE模式下取消点击的回调函数
|
||||
void setOnToggleOffListener(const std::function<void()>&& callback);
|
||||
//设置按钮模式
|
||||
void setbuttonMode(StellarX::ButtonMode mode);
|
||||
//设置圆角矩形椭圆宽度
|
||||
void setROUND_RECTANGLEwidth(int width);
|
||||
//设置圆角矩形椭圆高度
|
||||
void setROUND_RECTANGLEheight(int height);
|
||||
//设置按钮填充模式
|
||||
void setFillMode(StellarX::FillMode mode);
|
||||
//设置按钮填充图案
|
||||
void setFillIma(StellarX::FillStyle ima);
|
||||
//设置按钮填充图像
|
||||
void setFillIma(std::string imaName);
|
||||
//设置按钮边框颜色
|
||||
void setButtonBorder(COLORREF Border);
|
||||
//设置按钮未被点击颜色
|
||||
void setButtonFalseColor(COLORREF color);
|
||||
//设置按钮文本
|
||||
void setButtonText(const char* text);
|
||||
void setButtonText(std::string text);
|
||||
//设置按钮形状
|
||||
void setButtonShape(StellarX::ControlShape shape);
|
||||
//设置按钮点击状态
|
||||
void setButtonClick(BOOL click);
|
||||
|
||||
//判断按钮是否被点击
|
||||
bool isClicked() const;
|
||||
|
||||
//获取按钮文字
|
||||
std::string getButtonText() const;
|
||||
const char* getButtonText_c() const;
|
||||
//获取按钮模式
|
||||
StellarX::ButtonMode getButtonMode() const;
|
||||
//获取按钮形状
|
||||
StellarX::ControlShape getButtonShape() const;
|
||||
//获取按钮填充模式
|
||||
StellarX::FillMode getFillMode() const;
|
||||
//获取按钮填充图案
|
||||
StellarX::FillStyle getFillIma() const;
|
||||
StellarX::FillStyle getFillIma() const;
|
||||
//获取按钮填充图像
|
||||
IMAGE* getFillImaImage() const;
|
||||
//获取按钮边框颜色
|
||||
COLORREF getButtonBorder() const;
|
||||
COLORREF getButtonBorder() const;
|
||||
//获取按钮文字颜色
|
||||
COLORREF getButtonTextColor() const;
|
||||
COLORREF getButtonTextColor() const;
|
||||
//获取按钮文字样式
|
||||
StellarX::ControlText getButtonTextStyle() const;
|
||||
//获取按钮宽度
|
||||
int getButtonWidth() const;
|
||||
//获取按钮高度
|
||||
int getButtonHeight() const;
|
||||
StellarX::ControlText getButtonTextStyle() const;
|
||||
public:
|
||||
// === Tooltip API===
|
||||
//设置是否启用提示框
|
||||
void enableTooltip(bool on) { tipEnabled = on; if (!on) tipVisible = false; }
|
||||
//设置提示框延时
|
||||
void setTooltipDelay(int ms) { tipDelayMs = (ms < 0 ? 0 : ms); }
|
||||
//设置提示框是否跟随鼠标
|
||||
void setTooltipFollowCursor(bool on) { tipFollowCursor = on; }
|
||||
//设置提示框位置偏移
|
||||
void setTooltipOffset(int dx, int dy) { tipOffsetX = dx; tipOffsetY = dy; }
|
||||
//设置提示框样式
|
||||
void setTooltipStyle(COLORREF text, COLORREF bk, bool transparent);
|
||||
//设置提示框文本
|
||||
void setTooltipText(const std::string& s){ tipTextClick = s; tipUserOverride = true; }
|
||||
void setTooltipTextsForToggle(const std::string& onText, const std::string& offText);
|
||||
// === Tooltip API===
|
||||
//设置是否启用提示框
|
||||
void enableTooltip(bool on) { tipEnabled = on; if (!on) tipVisible = false; }
|
||||
//设置提示框延时
|
||||
void setTooltipDelay(int ms) { tipDelayMs = (ms < 0 ? 0 : ms); }
|
||||
//设置提示框是否跟随鼠标
|
||||
void setTooltipFollowCursor(bool on) { tipFollowCursor = on; }
|
||||
//设置提示框位置偏移
|
||||
void setTooltipOffset(int dx, int dy) { tipOffsetX = dx; tipOffsetY = dy; }
|
||||
//设置提示框样式
|
||||
void setTooltipStyle(COLORREF text, COLORREF bk, bool transparent);
|
||||
//设置提示框文本
|
||||
void setTooltipText(const std::string& s) { tipTextClick = s; tipUserOverride = true; }
|
||||
void setTooltipTextsForToggle(const std::string& onText, const std::string& offText);
|
||||
private:
|
||||
//初始化按钮
|
||||
void initButton(const std::string text, StellarX::ButtonMode mode, StellarX::ControlShape shape, COLORREF ct, COLORREF cf, COLORREF ch);
|
||||
//判断鼠标是否在圆形按钮内
|
||||
bool isMouseInCircle(int mouseX, int mouseY, int x, int y, int radius);
|
||||
//判断鼠标是否在椭圆按钮内
|
||||
bool isMouseInEllipse(int mouseX, int mouseY, int x, int y, int width, int height);
|
||||
//初始化按钮
|
||||
void initButton(const std::string text, StellarX::ButtonMode mode, StellarX::ControlShape shape, COLORREF ct, COLORREF cf, COLORREF ch);
|
||||
//判断鼠标是否在圆形按钮内
|
||||
bool isMouseInCircle(int mouseX, int mouseY, int x, int y, int radius);
|
||||
//判断鼠标是否在椭圆按钮内
|
||||
bool isMouseInEllipse(int mouseX, int mouseY, int x, int y, int width, int height);
|
||||
//获取对话框类型
|
||||
bool model() const override { return false; }
|
||||
void cutButtonText();
|
||||
// 统一隐藏&恢复背景
|
||||
void hideTooltip();
|
||||
// 根据当前 click 状态选择文案
|
||||
void refreshTooltipTextForState();
|
||||
|
||||
bool model() const override { return false; }
|
||||
//文本截断
|
||||
void cutButtonText();
|
||||
// 统一隐藏&恢复背景
|
||||
void hideTooltip();
|
||||
// 根据当前 click 状态选择文案
|
||||
void refreshTooltipTextForState();
|
||||
};
|
||||
|
||||
|
||||
+44
-41
@@ -18,53 +18,56 @@
|
||||
|
||||
#pragma once
|
||||
#include "Control.h"
|
||||
#include"Table.h"
|
||||
|
||||
class Canvas : public Control
|
||||
{
|
||||
protected:
|
||||
std::vector<std::unique_ptr<Control>> controls;
|
||||
|
||||
StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE; //容器形状
|
||||
StellarX::FillMode canvasFillMode = StellarX::FillMode::Solid; //容器填充模式
|
||||
StellarX::LineStyle canvasLineStyle = StellarX::LineStyle::Solid; //线型
|
||||
int canvaslinewidth = 1; //线宽
|
||||
|
||||
COLORREF canvasBorderClor = RGB(0, 0, 0); //边框颜色
|
||||
COLORREF canvasBkClor = RGB(255,255,255); //背景颜色
|
||||
std::vector<std::unique_ptr<Control>> controls;
|
||||
|
||||
StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE; //容器形状
|
||||
StellarX::FillMode canvasFillMode = StellarX::FillMode::Solid; //容器填充模式
|
||||
StellarX::LineStyle canvasLineStyle = StellarX::LineStyle::Solid; //线型
|
||||
int canvaslinewidth = 1; //线宽
|
||||
|
||||
// 清除所有子控件
|
||||
COLORREF canvasBorderClor = RGB(0, 0, 0); //边框颜色
|
||||
COLORREF canvasBkClor = RGB(255, 255, 255); //背景颜色
|
||||
|
||||
// 清除所有子控件
|
||||
void clearAllControls();
|
||||
public:
|
||||
Canvas();
|
||||
Canvas(int x, int y, int width, int height);
|
||||
~Canvas() {}
|
||||
//绘制容器及其子控件
|
||||
void draw() override;
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
//添加控件
|
||||
void addControl(std::unique_ptr<Control> control);
|
||||
//设置容器样式
|
||||
void setShape(StellarX::ControlShape shape);
|
||||
//设置容器填充模式
|
||||
void setCanvasfillMode(StellarX::FillMode mode);
|
||||
//设置容器边框颜色
|
||||
void setBorderColor(COLORREF color);
|
||||
//设置填充颜色
|
||||
void setCanvasBkColor(COLORREF color);
|
||||
//设置线形
|
||||
void setCanvasLineStyle(StellarX::LineStyle style);
|
||||
//设置线段宽度
|
||||
void setLinewidth(int width);
|
||||
//设置不可见后传递给子控件重写
|
||||
void setIsVisible(bool visible) override;
|
||||
void setDirty(bool dirty) override;
|
||||
void onWindowResize() override;
|
||||
void requestRepaint(Control* parent)override;
|
||||
//获取子控件列表
|
||||
std::vector<std::unique_ptr<Control>>& getControls() { return controls; }
|
||||
private:
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
};
|
||||
Canvas();
|
||||
Canvas(int x, int y, int width, int height);
|
||||
~Canvas() {}
|
||||
|
||||
void setX(int x)override;
|
||||
void setY(int y)override;
|
||||
|
||||
//绘制容器及其子控件
|
||||
void draw() override;
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
//添加控件
|
||||
void addControl(std::unique_ptr<Control> control);
|
||||
//设置容器样式
|
||||
void setShape(StellarX::ControlShape shape);
|
||||
//设置容器填充模式
|
||||
void setCanvasfillMode(StellarX::FillMode mode);
|
||||
//设置容器边框颜色
|
||||
void setBorderColor(COLORREF color);
|
||||
//设置填充颜色
|
||||
void setCanvasBkColor(COLORREF color);
|
||||
//设置线形
|
||||
void setCanvasLineStyle(StellarX::LineStyle style);
|
||||
//设置线段宽度
|
||||
void setLinewidth(int width);
|
||||
//设置不可见后传递给子控件重写
|
||||
void setIsVisible(bool visible) override;
|
||||
void setDirty(bool dirty) override;
|
||||
void onWindowResize() override;
|
||||
void requestRepaint(Control* parent)override;
|
||||
//获取子控件列表
|
||||
std::vector<std::unique_ptr<Control>>& getControls() { return controls; }
|
||||
private:
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
};
|
||||
|
||||
+102
-94
@@ -9,23 +9,20 @@
|
||||
* - 定义控件基本属性(坐标、尺寸、脏标记)
|
||||
* - 提供绘图状态管理(saveStyle/restoreStyle)
|
||||
* - 声明纯虚接口(draw、handleEvent等)
|
||||
* - 支持移动语义,禁止拷贝语义
|
||||
* - 禁止移动语义,禁止拷贝语义
|
||||
*
|
||||
* @使用场景: 作为所有具体控件类的基类,不直接实例化
|
||||
* @所属框架: 星垣(StellarX) GUI框架
|
||||
* @作者: 我在人间做废物
|
||||
******************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#ifndef _WIN32_WINNT
|
||||
#define _WIN32_WINNT 0x0600
|
||||
#define _WIN32_WINNT 0x0600
|
||||
#endif
|
||||
#ifndef WINVER
|
||||
#define WINVER _WIN32_WINNT
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <easyx.h>
|
||||
@@ -38,108 +35,119 @@
|
||||
class Control
|
||||
{
|
||||
protected:
|
||||
std::string id; // 控件ID
|
||||
int localx,x, localy,y; // 左上角坐标
|
||||
int localWidth,width, localHeight,height; // 控件尺寸
|
||||
Control* parent = nullptr; // 父控件
|
||||
bool dirty = true; // 是否重绘
|
||||
bool show = true; // 是否显示
|
||||
std::string id; // 控件ID
|
||||
int localx, x, localy, y; // 左上角坐标
|
||||
int localWidth, width, localHeight, height; // 控件尺寸
|
||||
Control* parent = nullptr; // 父控件
|
||||
bool dirty = true; // 是否重绘
|
||||
bool show = true; // 是否显示
|
||||
|
||||
/* == 背景快照 == */
|
||||
IMAGE* saveBkImage = nullptr;
|
||||
int saveBkX = 0, saveBkY = 0; // 快照保存起始坐标
|
||||
int saveWidth = 0, saveHeight = 0; // 快照保存尺寸
|
||||
bool hasSnap = false; // 当前是否持有有效快照
|
||||
/* == 布局模式 == */
|
||||
StellarX::LayoutMode layoutMode = StellarX::LayoutMode::Fixed; // 布局模式
|
||||
StellarX::Anchor anchor_1 = StellarX::Anchor::Top; // 锚点
|
||||
StellarX::Anchor anchor_2 = StellarX::Anchor::Right; // 锚点
|
||||
|
||||
StellarX::RouRectangle rouRectangleSize; // 圆角矩形椭圆宽度和高度
|
||||
/* == 背景快照 == */
|
||||
IMAGE* saveBkImage = nullptr;
|
||||
int saveBkX = 0, saveBkY = 0; // 快照保存起始坐标
|
||||
int saveWidth = 0, saveHeight = 0; // 快照保存尺寸
|
||||
bool hasSnap = false; // 当前是否持有有效快照
|
||||
|
||||
LOGFONT* currentFont = new LOGFONT(); // 保存当前字体样式和颜色
|
||||
COLORREF* currentColor = new COLORREF();
|
||||
COLORREF* currentBkColor = new COLORREF(); // 保存当前填充色
|
||||
COLORREF* currentBorderColor = new COLORREF(); // 边框颜色
|
||||
LINESTYLE* currentLineStyle = new LINESTYLE(); // 保存当前线型
|
||||
StellarX::RouRectangle rouRectangleSize; // 圆角矩形椭圆宽度和高度
|
||||
|
||||
Control(const Control&) = delete;
|
||||
Control& operator=(const Control&) = delete;
|
||||
Control(Control&&) = delete;
|
||||
Control& operator=(Control&&) = delete;
|
||||
LOGFONT* currentFont = new LOGFONT(); // 保存当前字体样式和颜色
|
||||
COLORREF* currentColor = new COLORREF();
|
||||
COLORREF* currentBkColor = new COLORREF(); // 保存当前填充色
|
||||
COLORREF* currentBorderColor = new COLORREF(); // 边框颜色
|
||||
LINESTYLE* currentLineStyle = new LINESTYLE(); // 保存当前线型
|
||||
|
||||
Control() : localx(0),x(0), localy(0),y(0), localWidth(100),width(100),height(100), localHeight(100) {}
|
||||
Control(int x, int y, int width, int height)
|
||||
: localx(x), x(x), localy(y), y(y), localWidth(width), width(width), height(height), localHeight(height){}
|
||||
Control(const Control&) = delete;
|
||||
Control& operator=(const Control&) = delete;
|
||||
Control(Control&&) = delete;
|
||||
Control& operator=(Control&&) = delete;
|
||||
|
||||
Control() : localx(0), x(0), localy(0), y(0), localWidth(100), width(100), height(100), localHeight(100) {}
|
||||
Control(int x, int y, int width, int height)
|
||||
: localx(x), x(x), localy(y), y(y), localWidth(width), width(width), height(height), localHeight(height) {
|
||||
}
|
||||
public:
|
||||
|
||||
virtual ~Control()
|
||||
{
|
||||
delete currentFont;
|
||||
delete currentColor;
|
||||
delete currentBkColor;
|
||||
delete currentBorderColor;
|
||||
delete currentLineStyle;
|
||||
virtual ~Control()
|
||||
{
|
||||
delete currentFont;
|
||||
delete currentColor;
|
||||
delete currentBkColor;
|
||||
delete currentBorderColor;
|
||||
delete currentLineStyle;
|
||||
|
||||
currentFont = nullptr;
|
||||
currentColor = nullptr;
|
||||
currentBkColor = nullptr;
|
||||
currentBorderColor = nullptr;
|
||||
currentLineStyle = nullptr;
|
||||
discardBackground();
|
||||
}
|
||||
currentFont = nullptr;
|
||||
currentColor = nullptr;
|
||||
currentBkColor = nullptr;
|
||||
currentBorderColor = nullptr;
|
||||
currentLineStyle = nullptr;
|
||||
discardBackground();
|
||||
}
|
||||
protected:
|
||||
//向上请求重绘
|
||||
virtual void requestRepaint(Control* parent);
|
||||
//根控件/无父时触发重绘
|
||||
virtual void onRequestRepaintAsRoot();
|
||||
//向上请求重绘
|
||||
virtual void requestRepaint(Control* parent);
|
||||
//根控件/无父时触发重绘
|
||||
virtual void onRequestRepaintAsRoot();
|
||||
protected:
|
||||
//保存背景快照
|
||||
virtual void saveBackground(int x, int y, int w, int h);
|
||||
// putimage 回屏
|
||||
virtual void restBackground();
|
||||
// 释放快照(窗口重绘/尺寸变化后必须作废)
|
||||
void discardBackground();
|
||||
//保存背景快照
|
||||
virtual void saveBackground(int x, int y, int w, int h);
|
||||
// putimage 回屏
|
||||
virtual void restBackground();
|
||||
// 释放快照(窗口重绘/尺寸变化后必须作废)
|
||||
void discardBackground();
|
||||
public:
|
||||
//释放快照重新保存,在尺寸变化时更新背景快照避免尺寸变化导致显示错位
|
||||
void updateBackground();
|
||||
//窗口变化丢快照
|
||||
virtual void onWindowResize();
|
||||
// 获取位置和尺寸
|
||||
int getX() const { return x; }
|
||||
int getY() const { return y; }
|
||||
int getWidth() const { return width; }
|
||||
int getHeight() const { return height; }
|
||||
int getRight() const { return x + width; }
|
||||
int getBottom() const { return y + height; }
|
||||
|
||||
int getLocalX() const { return localx; }
|
||||
int getLocalY() const { return localy; }
|
||||
int getLocalWidth() const { return localWidth; }
|
||||
int getLocalHeight() const { return localHeight; }
|
||||
int getLocalRight() const { return localx + localWidth; }
|
||||
int getLocalBottom() const { return localy + localHeight; }
|
||||
//释放快照重新保存,在尺寸变化时更新背景快照避免尺寸变化导致显示错位
|
||||
void updateBackground();
|
||||
//窗口变化丢快照
|
||||
virtual void onWindowResize();
|
||||
// 获取位置和尺寸
|
||||
int getX() const { return x; }
|
||||
int getY() const { return y; }
|
||||
int getWidth() const { return width; }
|
||||
int getHeight() const { return height; }
|
||||
int getRight() const { return x + width; }
|
||||
int getBottom() const { return y + height; }
|
||||
|
||||
void setX(int x) { this->x = x; dirty = true; }
|
||||
void setY(int y) { this->y = y; dirty = true; }
|
||||
void setWidth(int width) { this->width = width; dirty = true; }
|
||||
void setHeight(int height) { this->height = height; dirty = true; }
|
||||
int getLocalX() const { return localx; }
|
||||
int getLocalY() const { return localy; }
|
||||
int getLocalWidth() const { return localWidth; }
|
||||
int getLocalHeight() const { return localHeight; }
|
||||
int getLocalRight() const { return localx + localWidth; }
|
||||
int getLocalBottom() const { return localy + localHeight; }
|
||||
|
||||
virtual void setX(int x) { this->x = x; dirty = true; }
|
||||
virtual void setY(int y) { this->y = y; dirty = true; }
|
||||
virtual void setWidth(int width) { this->width = width; dirty = true; }
|
||||
virtual void setHeight(int height) { this->height = height; dirty = true; }
|
||||
public:
|
||||
|
||||
virtual void draw() = 0;
|
||||
virtual bool handleEvent(const ExMessage& msg) = 0;//返回true代表事件已消费
|
||||
//设置是否显示
|
||||
virtual void setIsVisible(bool show);
|
||||
//设置父容器指针
|
||||
void setParent(Control* parent) { this->parent = parent; }
|
||||
//设置是否重绘
|
||||
virtual void setDirty(bool dirty) { this->dirty = dirty; }
|
||||
|
||||
//检查控件是否可见
|
||||
bool IsVisible() const { return show; };
|
||||
//获取控件id
|
||||
std::string getId() const { return id; }
|
||||
//检查是否为脏
|
||||
bool isDirty() { return dirty; }
|
||||
//用来检查对话框是否模态,其他控件不用实现
|
||||
virtual bool model()const = 0;
|
||||
virtual void draw() = 0;
|
||||
virtual bool handleEvent(const ExMessage& msg) = 0;//返回true代表事件已消费
|
||||
//设置是否显示
|
||||
virtual void setIsVisible(bool show);
|
||||
//设置父容器指针
|
||||
void setParent(Control* parent) { this->parent = parent; }
|
||||
//设置是否重绘
|
||||
virtual void setDirty(bool dirty) { this->dirty = dirty; }
|
||||
//检查控件是否可见
|
||||
bool IsVisible() const { return show; };
|
||||
//获取控件id
|
||||
std::string getId() const { return id; }
|
||||
//检查是否为脏
|
||||
bool isDirty() { return dirty; }
|
||||
//用来检查对话框是否模态,其他控件不用实现
|
||||
virtual bool model()const = 0;
|
||||
//布局
|
||||
void setLayoutMode(StellarX::LayoutMode layoutMode_);
|
||||
void setAnchor(StellarX::Anchor anchor_1, StellarX::Anchor anchor_2);
|
||||
StellarX::Anchor getAnchor_1() const;
|
||||
StellarX::Anchor getAnchor_2() const;
|
||||
StellarX::LayoutMode getLayoutMode() const;
|
||||
protected:
|
||||
void saveStyle();
|
||||
void restoreStyle();
|
||||
void saveStyle();
|
||||
void restoreStyle();
|
||||
};
|
||||
+347
-302
@@ -27,320 +27,365 @@
|
||||
*/
|
||||
namespace StellarX
|
||||
{
|
||||
/**
|
||||
* @枚举类名称: FillStyle
|
||||
* @功能描述: 用来定义控件填充图案的枚举类
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件填充图案
|
||||
* 可以在控件初始化时设置填充图案
|
||||
* 根据具体情况选择不同的填充图案
|
||||
* 默认填充图案为水平线
|
||||
*
|
||||
* @取值说明:
|
||||
* Horizontal - 水平线
|
||||
* Vertical - 垂直线
|
||||
* FDiagonal - 反斜线
|
||||
* BDiagonal - 正斜线
|
||||
* Cross - 十字
|
||||
* DiagCross - 网格
|
||||
*
|
||||
* @使用示例:
|
||||
* FillStyle var = FillStyle::Horizontal;
|
||||
*
|
||||
* @备注:
|
||||
* 此枚举类仅支持图案填充模式
|
||||
*/
|
||||
enum class FillStyle
|
||||
{
|
||||
Horizontal = HS_HORIZONTAL, // 水平线
|
||||
Vertical = HS_VERTICAL, // 垂直线
|
||||
FDiagonal = HS_FDIAGONAL, // 反斜线
|
||||
BDiagonal = HS_BDIAGONAL, // 正斜线
|
||||
Cross = HS_CROSS, // 十字
|
||||
DiagCross = HS_DIAGCROSS // 网格
|
||||
};
|
||||
/**
|
||||
* @枚举类名称: FillStyle
|
||||
* @功能描述: 用来定义控件填充图案的枚举类
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件填充图案
|
||||
* 可以在控件初始化时设置填充图案
|
||||
* 根据具体情况选择不同的填充图案
|
||||
* 默认填充图案为水平线
|
||||
*
|
||||
* @取值说明:
|
||||
* Horizontal - 水平线
|
||||
* Vertical - 垂直线
|
||||
* FDiagonal - 反斜线
|
||||
* BDiagonal - 正斜线
|
||||
* Cross - 十字
|
||||
* DiagCross - 网格
|
||||
*
|
||||
* @使用示例:
|
||||
* FillStyle var = FillStyle::Horizontal;
|
||||
*
|
||||
* @备注:
|
||||
* 此枚举类仅支持图案填充模式
|
||||
*/
|
||||
enum class FillStyle
|
||||
{
|
||||
Horizontal = HS_HORIZONTAL, // 水平线
|
||||
Vertical = HS_VERTICAL, // 垂直线
|
||||
FDiagonal = HS_FDIAGONAL, // 反斜线
|
||||
BDiagonal = HS_BDIAGONAL, // 正斜线
|
||||
Cross = HS_CROSS, // 十字
|
||||
DiagCross = HS_DIAGCROSS // 网格
|
||||
};
|
||||
|
||||
/**
|
||||
* @枚举类名称: FillMode
|
||||
* @功能描述: 用来定义控件填充模式的枚举类
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件填充模式
|
||||
* 可以在控件初始化时设置填充模式
|
||||
* 根据具体情况选择不同的填充模式
|
||||
* 默认填充模式为固实填充
|
||||
*
|
||||
* @取值说明:
|
||||
* Solid - 固实填充
|
||||
* Null - 不填充
|
||||
* Hatched - 图案填充
|
||||
* Pattern - 自定义图案填充
|
||||
* DibPattern - 自定义图像填充
|
||||
*
|
||||
* @使用示例:
|
||||
* FillMode var = FillMode::Solid;
|
||||
*/
|
||||
enum class FillMode
|
||||
{
|
||||
Solid = BS_SOLID, //固实填充
|
||||
Null = BS_NULL, // 不填充
|
||||
Hatched = BS_HATCHED, // 图案填充
|
||||
Pattern = BS_PATTERN, // 自定义图案填充
|
||||
DibPattern = BS_DIBPATTERN // 自定义图像填充
|
||||
};
|
||||
/**
|
||||
* @枚举类名称: FillMode
|
||||
* @功能描述: 用来定义控件填充模式的枚举类
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件填充模式
|
||||
* 可以在控件初始化时设置填充模式
|
||||
* 根据具体情况选择不同的填充模式
|
||||
* 默认填充模式为固实填充
|
||||
*
|
||||
* @取值说明:
|
||||
* Solid - 固实填充
|
||||
* Null - 不填充
|
||||
* Hatched - 图案填充
|
||||
* Pattern - 自定义图案填充
|
||||
* DibPattern - 自定义图像填充
|
||||
*
|
||||
* @使用示例:
|
||||
* FillMode var = FillMode::Solid;
|
||||
*/
|
||||
enum class FillMode
|
||||
{
|
||||
Solid = BS_SOLID, //固实填充
|
||||
Null = BS_NULL, // 不填充
|
||||
Hatched = BS_HATCHED, // 图案填充
|
||||
Pattern = BS_PATTERN, // 自定义图案填充
|
||||
DibPattern = BS_DIBPATTERN // 自定义图像填充
|
||||
};
|
||||
|
||||
/**
|
||||
* @枚举类名称: LineStyle
|
||||
* @功能描述: 此枚举类用来定义控件边框线型
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件边框线型
|
||||
* 可以在控件初始化时设置边框线型
|
||||
* 根据具体情况选择不同的线型
|
||||
* 默认线型为实线
|
||||
*
|
||||
* @取值说明:
|
||||
* Solid // 实线
|
||||
* Dash // 虚线
|
||||
* Dot // 点线
|
||||
* DashDot // 点划线
|
||||
* DashDotDot // 双点划线
|
||||
* Null // 无线
|
||||
*
|
||||
* @使用示例:
|
||||
* LineStyle var = LineStyle::Solid;
|
||||
*/
|
||||
enum class LineStyle
|
||||
{
|
||||
Solid = PS_SOLID, // 实线
|
||||
Dash = PS_DASH, // 虚线
|
||||
Dot = PS_DOT, // 点线
|
||||
DashDot = PS_DASHDOT, // 点划线
|
||||
DashDotDot = PS_DASHDOTDOT, // 双点划线
|
||||
Null = PS_NULL // 无线
|
||||
};
|
||||
/**
|
||||
* @枚举类名称: LineStyle
|
||||
* @功能描述: 此枚举类用来定义控件边框线型
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据此枚举类可以自定义控件边框线型
|
||||
* 可以在控件初始化时设置边框线型
|
||||
* 根据具体情况选择不同的线型
|
||||
* 默认线型为实线
|
||||
*
|
||||
* @取值说明:
|
||||
* Solid // 实线
|
||||
* Dash // 虚线
|
||||
* Dot // 点线
|
||||
* DashDot // 点划线
|
||||
* DashDotDot // 双点划线
|
||||
* Null // 无线
|
||||
*
|
||||
* @使用示例:
|
||||
* LineStyle var = LineStyle::Solid;
|
||||
*/
|
||||
enum class LineStyle
|
||||
{
|
||||
Solid = PS_SOLID, // 实线
|
||||
Dash = PS_DASH, // 虚线
|
||||
Dot = PS_DOT, // 点线
|
||||
DashDot = PS_DASHDOT, // 点划线
|
||||
DashDotDot = PS_DASHDOTDOT, // 双点划线
|
||||
Null = PS_NULL // 无线
|
||||
};
|
||||
|
||||
/**
|
||||
* @结构体名称: ControlText
|
||||
* @功能描述: 控件字体样式 可以自定义不同的样式
|
||||
*
|
||||
* @详细说明:
|
||||
* 主要使用的场景为:需要修改或想自定义控件字体大小,字体样式,颜色等
|
||||
*
|
||||
* @成员说明:
|
||||
* int nHeight = 0; - 字体高度
|
||||
* int nWidth = 0; - 字体宽度 如果为0则自适应
|
||||
* LPCTSTR lpszFace = "宋体"; - 字体名称
|
||||
* COLORREF color = RGB(0, 0, 0); - 字体颜色
|
||||
* int nEscapement = 0; - 字符串旋转角度
|
||||
* int nOrientation = 0; - 字符旋转角度
|
||||
* int nWeight = 0; - 字体粗细 范围0~1000 0表示默认
|
||||
* bool bItalic = false; - 是否斜体
|
||||
* bool bUnderline = false; - 是否下划线
|
||||
* bool bStrikeOut = false; - 是否删除线
|
||||
*/
|
||||
struct ControlText
|
||||
{
|
||||
int nHeight = 0; //- 字体高度
|
||||
int nWidth = 0; //- 字体宽度 如果为0则自适应
|
||||
LPCTSTR lpszFace = "微软雅黑"; //- 字体名称
|
||||
COLORREF color = RGB(0, 0, 0); //- 字体颜色
|
||||
int nEscapement = 0; //- 字符串旋转角度
|
||||
int nOrientation = 0; //- 字符旋转角度
|
||||
int nWeight = 0; //- 字体粗细 范围0~1000 0表示默认
|
||||
bool bItalic = false; //- 是否斜体
|
||||
bool bUnderline = false; //- 是否下划线
|
||||
bool bStrikeOut = false; //- 是否删除线
|
||||
/**
|
||||
* @结构体名称: ControlText
|
||||
* @功能描述: 控件字体样式 可以自定义不同的样式
|
||||
*
|
||||
* @详细说明:
|
||||
* 主要使用的场景为:需要修改或想自定义控件字体大小,字体样式,颜色等
|
||||
*
|
||||
* @成员说明:
|
||||
* int nHeight = 0; - 字体高度
|
||||
* int nWidth = 0; - 字体宽度 如果为0则自适应
|
||||
* LPCTSTR lpszFace = "宋体"; - 字体名称
|
||||
* COLORREF color = RGB(0, 0, 0); - 字体颜色
|
||||
* int nEscapement = 0; - 字符串旋转角度
|
||||
* int nOrientation = 0; - 字符旋转角度
|
||||
* int nWeight = 0; - 字体粗细 范围0~1000 0表示默认
|
||||
* bool bItalic = false; - 是否斜体
|
||||
* bool bUnderline = false; - 是否下划线
|
||||
* bool bStrikeOut = false; - 是否删除线
|
||||
*/
|
||||
struct ControlText
|
||||
{
|
||||
int nHeight = 0; //- 字体高度
|
||||
int nWidth = 0; //- 字体宽度 如果为0则自适应
|
||||
LPCTSTR lpszFace = "微软雅黑"; //- 字体名称
|
||||
COLORREF color = RGB(0, 0, 0); //- 字体颜色
|
||||
int nEscapement = 0; //- 字符串旋转角度
|
||||
int nOrientation = 0; //- 字符旋转角度
|
||||
int nWeight = 0; //- 字体粗细 范围0~1000 0表示默认
|
||||
bool bItalic = false; //- 是否斜体
|
||||
bool bUnderline = false; //- 是否下划线
|
||||
bool bStrikeOut = false; //- 是否删除线
|
||||
|
||||
bool operator!=(const ControlText& text);
|
||||
ControlText& operator=(const ControlText& text);
|
||||
};
|
||||
bool operator!=(const ControlText& text);
|
||||
ControlText& operator=(const ControlText& text);
|
||||
};
|
||||
|
||||
/**
|
||||
* @枚举名称: ControlShape
|
||||
* @功能描述: 枚举控件的不同几何样式
|
||||
*
|
||||
* @详细说明:
|
||||
* 定义了四种(有无边框算一种)不同的几何样式,可以根据具体需求
|
||||
* 自定义控件的形状。
|
||||
*
|
||||
* @取值说明:
|
||||
* RECTANGLE = 1, //有边框矩形
|
||||
* B_RECTANGLE, //无边框矩形
|
||||
* ROUND_RECTANGLE, //有边框圆角矩形
|
||||
* B_ROUND_RECTANGLE, //无边框圆角矩形
|
||||
* CIRCLE, //有边框圆形
|
||||
* B_CIRCLE, //无边框圆形
|
||||
* ELLIPSE, //有边框椭圆
|
||||
* B_ELLIPSE //无边框椭圆
|
||||
*
|
||||
* @使用示例:
|
||||
* ControlShape shape = ControlShape::ELLIPSE;
|
||||
*
|
||||
* @备注:
|
||||
* 按钮类支持所有形状,部分控件只支持部分形状,具体请参考控件类。
|
||||
*/
|
||||
enum class ControlShape
|
||||
{
|
||||
RECTANGLE = 1, //有边框矩形
|
||||
B_RECTANGLE, //无边框矩形
|
||||
ROUND_RECTANGLE, //有边框圆角矩形
|
||||
B_ROUND_RECTANGLE, //无边框圆角矩形
|
||||
CIRCLE, //有边框圆形
|
||||
B_CIRCLE, //无边框圆形
|
||||
ELLIPSE, //有边框椭圆
|
||||
B_ELLIPSE //无边框椭圆
|
||||
};
|
||||
/**
|
||||
* @枚举名称: ControlShape
|
||||
* @功能描述: 枚举控件的不同几何样式
|
||||
*
|
||||
* @详细说明:
|
||||
* 定义了四种(有无边框算一种)不同的几何样式,可以根据具体需求
|
||||
* 自定义控件的形状。
|
||||
*
|
||||
* @取值说明:
|
||||
* RECTANGLE = 1, //有边框矩形
|
||||
* B_RECTANGLE, //无边框矩形
|
||||
* ROUND_RECTANGLE, //有边框圆角矩形
|
||||
* B_ROUND_RECTANGLE, //无边框圆角矩形
|
||||
* CIRCLE, //有边框圆形
|
||||
* B_CIRCLE, //无边框圆形
|
||||
* ELLIPSE, //有边框椭圆
|
||||
* B_ELLIPSE //无边框椭圆
|
||||
*
|
||||
* @使用示例:
|
||||
* ControlShape shape = ControlShape::ELLIPSE;
|
||||
*
|
||||
* @备注:
|
||||
* 按钮类支持所有形状,部分控件只支持部分形状,具体请参考控件类。
|
||||
*/
|
||||
enum class ControlShape
|
||||
{
|
||||
RECTANGLE = 1, //有边框矩形
|
||||
B_RECTANGLE, //无边框矩形
|
||||
ROUND_RECTANGLE, //有边框圆角矩形
|
||||
B_ROUND_RECTANGLE, //无边框圆角矩形
|
||||
CIRCLE, //有边框圆形
|
||||
B_CIRCLE, //无边框圆形
|
||||
ELLIPSE, //有边框椭圆
|
||||
B_ELLIPSE //无边框椭圆
|
||||
};
|
||||
|
||||
/**
|
||||
* @枚举类名称: TextBoxmode
|
||||
* @功能描述: 定义了文本框的两种模式
|
||||
*
|
||||
* @详细说明:
|
||||
* 需要限制文本框是否接受用户输入时使用
|
||||
*
|
||||
* @取值说明:
|
||||
* INPUT_MODE, // 用户可输入模式
|
||||
* READONLY_MODE // 只读模式
|
||||
*/
|
||||
enum class TextBoxmode
|
||||
{
|
||||
INPUT_MODE, // 用户可输入模式
|
||||
READONLY_MODE // 只读模式
|
||||
};
|
||||
/**
|
||||
* @枚举类名称: TextBoxmode
|
||||
* @功能描述: 定义了文本框的三种模式
|
||||
*
|
||||
* @详细说明:
|
||||
* 需要限制文本框是否接受用户输入时使用
|
||||
*
|
||||
* @取值说明:
|
||||
* INPUT_MODE, // 用户可输入模式
|
||||
* READONLY_MODE // 只读模式
|
||||
* PASSWORD_MODE // 密码模式
|
||||
*/
|
||||
enum class TextBoxmode
|
||||
{
|
||||
INPUT_MODE, // 用户可输入模式
|
||||
READONLY_MODE, // 只读模式
|
||||
PASSWORD_MODE // 密码模式
|
||||
};
|
||||
|
||||
/**
|
||||
* @枚举名称: ButtonMode
|
||||
* @功能描述: 定义按钮的工作模式
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据按钮的工作模式,按钮可以有不同的行为。
|
||||
* 用户可以在具体情况下设置按钮的工作模式。
|
||||
*
|
||||
* @取值说明:
|
||||
* NORMAL = 1, - 普通模式,点击后触发回调,但不会保持状态。
|
||||
* TOGGLE, - 切换模式,点击后会在选中和未选中之间切换,触发不同的回调函数。
|
||||
* DISABLED - 禁用模式,按钮不可点击,显示为灰色,文本显示删除线。
|
||||
*
|
||||
* @使用示例:
|
||||
* ButtonMode mode = ButtonMode::NORMAL;
|
||||
*/
|
||||
enum class ButtonMode
|
||||
{
|
||||
NORMAL = 1, //普通模式
|
||||
TOGGLE, //切换模式
|
||||
DISABLED //禁用模式
|
||||
};
|
||||
/**
|
||||
* @枚举名称: ButtonMode
|
||||
* @功能描述: 定义按钮的工作模式
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据按钮的工作模式,按钮可以有不同的行为。
|
||||
* 用户可以在具体情况下设置按钮的工作模式。
|
||||
*
|
||||
* @取值说明:
|
||||
* NORMAL = 1, - 普通模式,点击后触发回调,但不会保持状态。
|
||||
* TOGGLE, - 切换模式,点击后会在选中和未选中之间切换,触发不同的回调函数。
|
||||
* DISABLED - 禁用模式,按钮不可点击,显示为灰色,文本显示删除线。
|
||||
*
|
||||
* @使用示例:
|
||||
* ButtonMode mode = ButtonMode::NORMAL;
|
||||
*/
|
||||
enum class ButtonMode
|
||||
{
|
||||
NORMAL = 1, //普通模式
|
||||
TOGGLE, //切换模式
|
||||
DISABLED //禁用模式
|
||||
};
|
||||
|
||||
/**
|
||||
* @结构体名称: RouRectangle
|
||||
* @功能描述: 定义了控件圆角矩形样式时圆角的椭圆尺寸
|
||||
*
|
||||
* @详细说明:
|
||||
* 需要修改控件圆角矩形样式时的圆角椭圆。
|
||||
*
|
||||
* @成员说明:
|
||||
* int ROUND_RECTANGLEwidth = 20; //构成圆角矩形的圆角的椭圆的宽度。
|
||||
* int ROUND_RECTANGLEheight = 20; //构成圆角矩形的圆角的椭圆的高度。
|
||||
*/
|
||||
struct RouRectangle
|
||||
{
|
||||
int ROUND_RECTANGLEwidth = 20; //构成圆角矩形的圆角的椭圆的宽度。
|
||||
int ROUND_RECTANGLEheight = 20; //构成圆角矩形的圆角的椭圆的高度。
|
||||
};
|
||||
/**
|
||||
* @结构体名称: RouRectangle
|
||||
* @功能描述: 定义了控件圆角矩形样式时圆角的椭圆尺寸
|
||||
*
|
||||
* @详细说明:
|
||||
* 需要修改控件圆角矩形样式时的圆角椭圆。
|
||||
*
|
||||
* @成员说明:
|
||||
* int ROUND_RECTANGLEwidth = 20; //构成圆角矩形的圆角的椭圆的宽度。
|
||||
* int ROUND_RECTANGLEheight = 20; //构成圆角矩形的圆角的椭圆的高度。
|
||||
*/
|
||||
struct RouRectangle
|
||||
{
|
||||
int ROUND_RECTANGLEwidth = 20; //构成圆角矩形的圆角的椭圆的宽度。
|
||||
int ROUND_RECTANGLEheight = 20; //构成圆角矩形的圆角的椭圆的高度。
|
||||
};
|
||||
|
||||
// 消息框类型
|
||||
enum class MessageBoxType
|
||||
{
|
||||
OK, // 只有确定按钮
|
||||
OKCancel, // 确定和取消按钮
|
||||
YesNo, // 是和否按钮
|
||||
YesNoCancel, // 是、否和取消按钮
|
||||
RetryCancel, // 重试和取消按钮
|
||||
AbortRetryIgnore, // 中止、重试和忽略按钮
|
||||
};
|
||||
// 消息框类型
|
||||
enum class MessageBoxType
|
||||
{
|
||||
OK, // 只有确定按钮
|
||||
OKCancel, // 确定和取消按钮
|
||||
YesNo, // 是和否按钮
|
||||
YesNoCancel, // 是、否和取消按钮
|
||||
RetryCancel, // 重试和取消按钮
|
||||
AbortRetryIgnore, // 中止、重试和忽略按钮
|
||||
};
|
||||
|
||||
// 消息框返回值
|
||||
enum class MessageBoxResult
|
||||
{
|
||||
OK = 1, // 确定按钮
|
||||
Cancel = 2, // 取消按钮
|
||||
Yes = 6, // 是按钮
|
||||
No = 7, // 否按钮
|
||||
Abort = 3, // 中止按钮
|
||||
Retry = 4, // 重试按钮
|
||||
Ignore = 5 // 忽略按钮
|
||||
};
|
||||
// 消息框返回值
|
||||
enum class MessageBoxResult
|
||||
{
|
||||
OK = 1, // 确定按钮
|
||||
Cancel = 2, // 取消按钮
|
||||
Yes = 6, // 是按钮
|
||||
No = 7, // 否按钮
|
||||
Abort = 3, // 中止按钮
|
||||
Retry = 4, // 重试按钮
|
||||
Ignore = 5 // 忽略按钮
|
||||
};
|
||||
#if 0 //布局管理器相关 —待实现—
|
||||
/*
|
||||
*
|
||||
*@枚举名称: LayoutKind
|
||||
* @功能描述 : 定义布局管理类型
|
||||
*
|
||||
*@详细说明 :
|
||||
* 根据布局管理类型,控件可以有不同的布局方式。
|
||||
* 用户可以在具体情况下设置布局管理类型。
|
||||
*
|
||||
* @取值说明 :
|
||||
* Absolute:不管,保持子控件自己的坐标(向后兼容)。
|
||||
* HBox: 水平方向排队;支持固定宽、权重分配、对齐、拉伸。
|
||||
* VBox: 竖直方向排队;同上。
|
||||
* Grid(网格):按行列摆;支持固定/自适应/权重行列;支持跨行/跨列;单元内对齐/拉伸。
|
||||
*
|
||||
*/
|
||||
// 布局类型
|
||||
enum class LayoutKind
|
||||
{
|
||||
Absolute = 1,
|
||||
HBox,
|
||||
VBox,
|
||||
Grid,
|
||||
Flow,
|
||||
Stack
|
||||
};
|
||||
/*
|
||||
*
|
||||
*@枚举名称: LayoutKind
|
||||
* @功能描述 : 定义布局管理类型
|
||||
*
|
||||
*@详细说明 :
|
||||
* 根据布局管理类型,控件可以有不同的布局方式。
|
||||
* 用户可以在具体情况下设置布局管理类型。
|
||||
*
|
||||
* @取值说明 :
|
||||
* Absolute:不管,保持子控件自己的坐标(向后兼容)。
|
||||
* HBox: 水平方向排队;支持固定宽、权重分配、对齐、拉伸。
|
||||
* VBox: 竖直方向排队;同上。
|
||||
* Grid(网格):按行列摆;支持固定/自适应/权重行列;支持跨行/跨列;单元内对齐/拉伸。
|
||||
*
|
||||
*/
|
||||
// 布局类型
|
||||
enum class LayoutKind
|
||||
{
|
||||
Absolute = 1,
|
||||
HBox,
|
||||
VBox,
|
||||
Grid,
|
||||
Flow,
|
||||
Stack
|
||||
};
|
||||
|
||||
// 布局参数
|
||||
struct LayoutParams
|
||||
{
|
||||
// 边距左、右、上、下
|
||||
int marginL = 0, marginR = 0, marginT = 0, marginB = 0;
|
||||
// 固定尺寸(>=0 强制;-1 用控件当前尺寸)
|
||||
int fixedW = -1, fixedH = -1;
|
||||
// 主轴权重(HBox=宽度、VBox=高度、Grid见下)
|
||||
float weight = 0.f;
|
||||
// 对齐(非拉伸时生效)
|
||||
enum Align { Start = 0, Center = 1, End = 2, Stretch = 3 };
|
||||
int alignX = Start; // HBox: 次轴=Y;VBox: 次轴=X;Grid: 单元内
|
||||
int alignY = Start; // Grid :控制单元内垂直(HBox / VBox通常只用 alignX)
|
||||
// Grid 专用(可先不做)
|
||||
int gridRow = 0, gridCol = 0, rowSpan = 1, colSpan = 1;
|
||||
// Flow 专用(可先不做)
|
||||
int flowBreak = 0; // 1=强制换行
|
||||
};
|
||||
// 布局参数
|
||||
struct LayoutParams
|
||||
{
|
||||
// 边距左、右、上、下
|
||||
int marginL = 0, marginR = 0, marginT = 0, marginB = 0;
|
||||
// 固定尺寸(>=0 强制;-1 用控件当前尺寸)
|
||||
int fixedW = -1, fixedH = -1;
|
||||
// 主轴权重(HBox=宽度、VBox=高度、Grid见下)
|
||||
float weight = 0.f;
|
||||
// 对齐(非拉伸时生效)
|
||||
enum Align { Start = 0, Center = 1, End = 2, Stretch = 3 };
|
||||
int alignX = Start; // HBox: 次轴=Y;VBox: 次轴=X;Grid: 单元内
|
||||
int alignY = Start; // Grid :控制单元内垂直(HBox / VBox通常只用 alignX)
|
||||
// Grid 专用(可先不做)
|
||||
int gridRow = 0, gridCol = 0, rowSpan = 1, colSpan = 1;
|
||||
// Flow 专用(可先不做)
|
||||
int flowBreak = 0; // 1=强制换行
|
||||
};
|
||||
#endif
|
||||
|
||||
/*
|
||||
* @枚举名称: TabPlacement
|
||||
* @功能描述: 定义了选项卡页签的不同位置
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据选项卡页签的位置,选项卡页签可以有不同的布局方式。
|
||||
*
|
||||
* @成员说明:
|
||||
* Top, - 选项卡页签位于顶部
|
||||
* Bottom, - 选项卡页签位于底部
|
||||
* Left, - 选项卡页签位于左侧
|
||||
* Right - 选项卡页签位于右侧
|
||||
*
|
||||
* @使用示例:
|
||||
* TabPlacement placement = TabPlacement::Top;
|
||||
*/
|
||||
enum class TabPlacement
|
||||
{
|
||||
Top,
|
||||
Bottom,
|
||||
Left,
|
||||
Right
|
||||
};
|
||||
/*
|
||||
* @枚举名称: TabPlacement
|
||||
* @功能描述: 定义了选项卡页签的不同位置
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据选项卡页签的位置,选项卡页签可以有不同的布局方式。
|
||||
*
|
||||
* @成员说明:
|
||||
* Top, - 选项卡页签位于顶部
|
||||
* Bottom, - 选项卡页签位于底部
|
||||
* Left, - 选项卡页签位于左侧
|
||||
* Right - 选项卡页签位于右侧
|
||||
*
|
||||
* @使用示例:
|
||||
* TabPlacement placement = TabPlacement::Top;
|
||||
*/
|
||||
enum class TabPlacement
|
||||
{
|
||||
Top,
|
||||
Bottom,
|
||||
Left,
|
||||
Right
|
||||
};
|
||||
/*
|
||||
* @枚举名称: LayoutMode
|
||||
* @功能描述: 定义了两种布局模式
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据不同模式,在窗口拉伸时采用不同的布局策略
|
||||
*
|
||||
* @成员说明:
|
||||
* Fixed, - 固定布局
|
||||
* AnchorToEdges - 锚定布局
|
||||
*
|
||||
* @使用示例:
|
||||
* LayoutMode mode = LayoutMode::Fixed;
|
||||
*/
|
||||
enum class LayoutMode
|
||||
{
|
||||
Fixed,
|
||||
AnchorToEdges
|
||||
};
|
||||
/*
|
||||
* @枚举名称: Anchor
|
||||
* @功能描述: 定义了控件相对于窗口锚定的位置
|
||||
*
|
||||
* @详细说明:
|
||||
* 根据不同的锚定位置,有不同的拉伸策略
|
||||
*
|
||||
* @成员说明:
|
||||
* Top, - 锚定上边,控件上边与窗口上侧距离保持不变
|
||||
* Bottom, - 锚定底边,控件底边与窗口底边距离保持不变
|
||||
* Left, - 锚定左边,控件左边与窗口左侧距离保持不变
|
||||
* Right - 锚定右边,控件上边与窗口右侧距离保持不变
|
||||
*
|
||||
* @使用示例:
|
||||
* Anchor a = Anchor::Top;
|
||||
*/
|
||||
enum class Anchor
|
||||
{
|
||||
NoAnchor = 0,
|
||||
Left = 1,
|
||||
Right,
|
||||
Top,
|
||||
Bottom
|
||||
};
|
||||
}
|
||||
+13
-20
@@ -30,7 +30,7 @@
|
||||
#define titleToTextMargin 10 //标题到文本的距离
|
||||
#define textToBorderMargin 10 //文本到边框的距离
|
||||
#define BorderWidth 3 //边框宽度
|
||||
class Dialog : public Canvas
|
||||
class Dialog : public Canvas
|
||||
{
|
||||
Window& hWnd; //窗口引用
|
||||
|
||||
@@ -45,19 +45,17 @@ class Dialog : public Canvas
|
||||
std::string message; //提示信息
|
||||
std::vector<std::string> lines; //消息内容按行分割
|
||||
|
||||
|
||||
bool needsInitialization = true; //是否需要初始化
|
||||
bool needsInitialization = true; //是否需要初始化
|
||||
bool close = false; //是否关闭
|
||||
bool modal = true; //是否模态
|
||||
|
||||
COLORREF backgroundColor = RGB(240, 240, 240); //背景颜色
|
||||
COLORREF backgroundColor = RGB(240, 240, 240); //背景颜色
|
||||
COLORREF borderColor = RGB(100, 100, 100); //边框颜色
|
||||
|
||||
COLORREF buttonTrueColor = RGB(211, 190, 190); //按钮被点击颜色
|
||||
COLORREF buttonFalseColor = RGB(215, 215, 215); //按钮未被点击颜色
|
||||
COLORREF buttonHoverColor = RGB(224, 224, 224); //按钮悬浮颜色
|
||||
|
||||
|
||||
Button* closeButton = nullptr; //关闭按钮
|
||||
|
||||
StellarX::MessageBoxResult result = StellarX::MessageBoxResult::Cancel; // 对话框结果
|
||||
@@ -76,8 +74,7 @@ public:
|
||||
//获取对话框消息,用以去重
|
||||
std::string GetCaption() const;
|
||||
//获取对话框消息,用以去重
|
||||
std::string GetText() const;
|
||||
|
||||
std::string GetText() const;
|
||||
|
||||
public:
|
||||
Dialog(Window& hWnd, std::string text, std::string message = "对话框", StellarX::MessageBoxType type = StellarX::MessageBoxType::OK, bool modal = true);
|
||||
@@ -105,31 +102,27 @@ public:
|
||||
// 显示对话框
|
||||
void Show();
|
||||
// 关闭对话框
|
||||
void Close();
|
||||
void Close();
|
||||
//初始化
|
||||
void setInitialization(bool init);
|
||||
|
||||
|
||||
private:
|
||||
// 初始化按钮
|
||||
void initButtons();
|
||||
void initButtons();
|
||||
// 初始化关闭按钮
|
||||
void initCloseButton();
|
||||
void initCloseButton();
|
||||
// 初始化标题
|
||||
void initTitle();
|
||||
void initTitle();
|
||||
// 按行分割消息内容
|
||||
void splitMessageLines();
|
||||
void splitMessageLines();
|
||||
// 获取文本大小
|
||||
void getTextSize();
|
||||
void getTextSize();
|
||||
//初始化对话框尺寸
|
||||
void initDialogSize();
|
||||
void saveBackground(int x, int y, int w, int h)override;
|
||||
void initDialogSize();
|
||||
void addControl(std::unique_ptr<Control> control);
|
||||
|
||||
void restBackground()override;
|
||||
|
||||
|
||||
// 清除所有控件
|
||||
void clearControls();
|
||||
void clearControls();
|
||||
//创建对话框按钮
|
||||
std::unique_ptr<Button> createDialogButton(int x, int y, const std::string& text);
|
||||
void requestRepaint(Control* parent) override;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*******************************************************************************
|
||||
* @文件: StellarX.h
|
||||
* @摘要: 星垣(StellarX) GUI框架 - 主包含头文件
|
||||
* @版本: v2.2.1
|
||||
* @版本: v3.0.1
|
||||
* @描述:
|
||||
* 一个为Windows平台打造的轻量级、模块化C++ GUI框架。
|
||||
* 基于EasyX图形库,提供简洁易用的API和丰富的控件。
|
||||
@@ -11,7 +11,9 @@
|
||||
*
|
||||
* @作者: 我在人间做废物
|
||||
* @邮箱: [3150131407@qq.com] | [ysm3150131407@gmail.com]
|
||||
* @仓库: [https://github.com/Ysm-04/StellarX]
|
||||
* @官网:https://stellarx-gui.top/
|
||||
* @仓库: https://github.com/Ysm-04/StellarX
|
||||
* @博客:https://blog.stellarx-gui.top/
|
||||
*
|
||||
* @许可证: MIT License
|
||||
* @版权: Copyright (c) 2025 我在人间做废物
|
||||
@@ -30,6 +32,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "CoreTypes.h"
|
||||
#include "SxLog.h"
|
||||
#include "Control.h"
|
||||
#include"Canvas.h"
|
||||
#include"Window.h"
|
||||
@@ -40,3 +43,5 @@
|
||||
#include"Dialog.h"
|
||||
#include"MessageBox.h"
|
||||
#include"TabControl.h"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
#pragma once
|
||||
|
||||
/********************************************************************************
|
||||
* @文件: SxLog.h
|
||||
* @摘要: StellarX 日志系统对外接口定义(控制台/文件输出 + 级别过滤 + Tag过滤 + 中英文选择)
|
||||
* @描述:
|
||||
* 该日志系统采用“宏 + RAII(析构提交)”的方式实现:
|
||||
* - 调用端通过 SX_LOGD/SX_LOGI... 写日志
|
||||
* - 宏内部先 shouldLog 短路过滤,未命中时不构造对象、不拼接字符串
|
||||
* - 命中时构造 SxLogLine,使用 operator<< 拼接内容
|
||||
* - 语句结束时 SxLogLine 析构,统一提交到 SxLogger::logLine 输出
|
||||
*
|
||||
* 输出通道(Sink)目前提供:
|
||||
* - ConsoleSink: 写入 std::cout(不走 WinAPI 调试输出通道)
|
||||
* - FileSink: 写入文件,支持按字节阈值滚动
|
||||
*
|
||||
* @特性:
|
||||
* - 日志级别:Trace/Debug/Info/Warn/Error/Fatal/Off
|
||||
* - Tag 过滤:None/Whitelist/Blacklist
|
||||
* - 可选前缀:时间戳/级别/Tag/线程ID/源码位置
|
||||
* - 中英文选择:SX_T(zh, en) / setLanguage
|
||||
* - 文件滚动:rotateBytes > 0 时按阈值滚动
|
||||
*
|
||||
* @使用场景:
|
||||
* - 排查重绘链路、脏标记传播、Tab 切换、Table 数据刷新等时序问题
|
||||
* - 输出可复现日志,配合回归验证
|
||||
*
|
||||
* @注意:
|
||||
* - SX_T 仅做“字符串选择”,不做编码转换
|
||||
* - 控制台显示是否乱码由“终端 codepage/字体/环境”决定
|
||||
* - 该头文件只声明接口,实现位于 SxLog.cpp
|
||||
*
|
||||
* @所属框架: 星垣(StellarX) GUI框架
|
||||
* @作者: 我在人间做废物
|
||||
********************************************************************************/
|
||||
|
||||
// SxLog.h - header-only interface (implementation in SxLog.cpp)
|
||||
// Pure standard library: std::cout and optional file sink.
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef SX_LOG_ENABLE
|
||||
#define SX_LOG_ENABLE 1
|
||||
#endif
|
||||
|
||||
namespace StellarX
|
||||
{
|
||||
/* ========================= 日志级别 ========================= */
|
||||
// 说明:
|
||||
// - minLevel 表示最低输出级别,小于 minLevel 的日志会被 shouldLog 直接过滤
|
||||
// - Off 表示全局关闭
|
||||
enum class SxLogLevel : int
|
||||
{
|
||||
Trace = 0, // 最细粒度:高频路径追踪(谨慎开启)
|
||||
Debug = 1, // 调试信息:状态变化/关键分支
|
||||
Info = 2, // 业务信息:关键流程节点
|
||||
Warn = 3, // 警告:非致命但异常的情况
|
||||
Error = 4, // 错误:功能失败、需要关注
|
||||
Fatal = 5, // 致命:通常意味着无法继续运行
|
||||
Off = 6 // 关闭全部日志
|
||||
};
|
||||
|
||||
/* ========================= 语言选择 ========================= */
|
||||
// 说明:仅用于 SX_T 选择输出哪一段文本,不做编码转换
|
||||
enum class SxLogLanguage : int
|
||||
{
|
||||
ZhCN = 0, // 中文
|
||||
EnUS = 1 // 英文
|
||||
};
|
||||
|
||||
/* ========================= Tag 过滤模式 ========================= */
|
||||
// None : 不过滤,全部输出
|
||||
// Whitelist : 只输出 tagList 中包含的 tag
|
||||
// Blacklist : 输出除 tagList 以外的 tag
|
||||
enum class SxTagFilterMode : int
|
||||
{
|
||||
None = 0,
|
||||
Whitelist = 1,
|
||||
Blacklist = 2
|
||||
};
|
||||
|
||||
/* ========================= 日志配置 ========================= */
|
||||
// 说明:SxLogger 内部持有该配置,shouldLog 与 logLine 都依赖它
|
||||
struct SxLogConfig
|
||||
{
|
||||
SxLogLevel minLevel = SxLogLevel::Info; // 最低输出级别
|
||||
|
||||
bool showTimestamp = true; // 是否输出时间戳前缀
|
||||
bool showLevel = true; // 是否输出级别前缀
|
||||
bool showTag = true; // 是否输出 tag 前缀
|
||||
bool showThreadId = false; // 是否输出线程ID(排查并发时开启)
|
||||
bool showSource = false; // 是否输出源码位置(file:line func)
|
||||
bool autoFlush = true; // 每行写完是否 flush(排查问题更稳,性能略差)
|
||||
|
||||
SxTagFilterMode tagFilterMode = SxTagFilterMode::None; // Tag 过滤模式
|
||||
std::vector<std::string> tagList; // Tag 列表(白名单/黑名单)
|
||||
|
||||
bool fileEnabled = false; // 文件输出是否启用(enableFile 成功才为 true)
|
||||
std::string filePath; // 文件路径
|
||||
bool fileAppend = true; // 是否追加写入
|
||||
std::size_t rotateBytes = 0; // 滚动阈值(0 表示不滚动)
|
||||
};
|
||||
|
||||
/* ========================= Sink 接口 ========================= */
|
||||
// 说明:
|
||||
// - Sink 负责“把完整的一行日志写到某个地方”
|
||||
// - SxLogger 负责过滤/格式化/分发
|
||||
class ILogSink
|
||||
{
|
||||
public:
|
||||
virtual ~ILogSink() = default;
|
||||
|
||||
// 返回 Sink 名称,用于调试识别(例如 "console"/"file")
|
||||
virtual const char* name() const = 0;
|
||||
|
||||
// 写入一整行(调用方保证 line 已包含换行或按约定追加换行)
|
||||
virtual void writeLine(const std::string& line) = 0;
|
||||
|
||||
// 刷新缓冲(可选实现)
|
||||
virtual void flush() {}
|
||||
};
|
||||
|
||||
/* ========================= 控制台输出 Sink ========================= */
|
||||
// 作用:把日志写入指定输出流(默认用 std::cout)
|
||||
class ConsoleSink : public ILogSink
|
||||
{
|
||||
public:
|
||||
// 绑定一个输出流引用(常见用法:std::cout)
|
||||
explicit ConsoleSink(std::ostream& os) : out(os) {}
|
||||
|
||||
const char* name() const override { return "console"; }
|
||||
|
||||
// 写入一行(不自动追加换行,换行由上层统一拼接)
|
||||
void writeLine(const std::string& line) override { out << line; }
|
||||
|
||||
// 立即 flush(当 autoFlush=true 时由 SxLogger 调用)
|
||||
void flush() override { out.flush(); }
|
||||
|
||||
private:
|
||||
std::ostream& out; // 输出流引用(不负责生命周期)
|
||||
};
|
||||
|
||||
/* ========================= 文件输出 Sink ========================= */
|
||||
// 作用:把日志写入文件,支持按字节阈值滚动
|
||||
class FileSink : public ILogSink
|
||||
{
|
||||
public:
|
||||
FileSink() = default;
|
||||
|
||||
const char* name() const override { return "file"; }
|
||||
|
||||
// 打开文件
|
||||
// path : 文件路径
|
||||
// append : true 追加写;false 清空重写
|
||||
bool open(const std::string& path, bool append);
|
||||
|
||||
// 关闭文件(安全可重复调用)
|
||||
void close();
|
||||
|
||||
// 查询文件是否处于打开状态
|
||||
bool isOpen() const;
|
||||
|
||||
// 设置滚动阈值(字节)
|
||||
// bytes = 0 表示不滚动
|
||||
void setRotateBytes(std::size_t bytes) { rotateBytes = bytes; }
|
||||
|
||||
// 写入一行,并在需要时触发滚动
|
||||
void writeLine(const std::string& line) override;
|
||||
|
||||
// flush 文件缓冲
|
||||
void flush() override;
|
||||
|
||||
private:
|
||||
// 检查并执行滚动
|
||||
// 返回值:是否发生滚动(或是否重新打开)
|
||||
bool rotateIfNeeded();
|
||||
|
||||
std::ofstream ofs; // 文件输出流
|
||||
std::string filePath; // 当前文件路径
|
||||
bool appendMode = true; // 是否追加模式(用于 reopen)
|
||||
std::size_t rotateBytes = 0; // 滚动阈值
|
||||
};
|
||||
|
||||
/* ========================= 日志中心 SxLogger ========================= */
|
||||
// 作用:
|
||||
// - 保存配置(SxLogConfig)
|
||||
// - 过滤(level/tag/sink enabled)
|
||||
// - 格式化前缀(时间/级别/tag/线程/源码位置)
|
||||
// - 分发到 console/file 等 sink
|
||||
class SxLogger
|
||||
{
|
||||
public:
|
||||
// 仅用于 Windows 控制台:把 codepage 切到 GBK,解决中文乱码。
|
||||
// 不使用 WinAPI:内部通过 system("chcp 936") 实现
|
||||
// 注意:这只影响终端解释输出字节的方式,不影响源码文件编码
|
||||
static void setGBK();
|
||||
|
||||
// 获取全局单例
|
||||
// 说明:函数内静态对象,C++11 起保证线程安全初始化
|
||||
static SxLogger& Get();
|
||||
|
||||
// 设置最低输出级别
|
||||
void setMinLevel(SxLogLevel level);
|
||||
|
||||
// 获取最低输出级别
|
||||
SxLogLevel getMinLevel() const;
|
||||
|
||||
// 设置语言(用于 SX_T 选择)
|
||||
void setLanguage(SxLogLanguage lang);
|
||||
|
||||
// 获取当前语言
|
||||
SxLogLanguage getLanguage() const;
|
||||
|
||||
// 设置 Tag 过滤
|
||||
// mode: None/Whitelist/Blacklist
|
||||
// tags: 过滤列表(精确匹配)
|
||||
void setTagFilter(SxTagFilterMode mode, const std::vector<std::string>& tags);
|
||||
|
||||
// 清空 Tag 过滤(恢复 None)
|
||||
void clearTagFilter();
|
||||
|
||||
// 开关控制台输出
|
||||
void enableConsole(bool enable);
|
||||
|
||||
// 开启文件输出
|
||||
// path : 文件路径
|
||||
// append : 追加写/清空写
|
||||
// rotateBytes: 滚动阈值(0 不滚动)
|
||||
// 返回值:是否打开成功
|
||||
bool enableFile(const std::string& path, bool append = true, std::size_t rotateBytes = 0);
|
||||
|
||||
// 关闭文件输出(不影响控制台输出)
|
||||
void disableFile();
|
||||
|
||||
// 快速判定是否需要输出(宏层面的短路依赖它)
|
||||
// 说明:
|
||||
// - shouldLog 一定要“副作用为 0”
|
||||
// - 若返回 false,调用端不会创建 SxLogLine,也不会拼接字符串
|
||||
bool shouldLog(SxLogLevel level, const char* tag) const;
|
||||
|
||||
// 输出一条完整日志
|
||||
// 说明:这是统一出口,SxLogLine 析构最终会走到这里
|
||||
void logLine(
|
||||
SxLogLevel level,
|
||||
const char* tag,
|
||||
const char* file,
|
||||
int line,
|
||||
const char* func,
|
||||
const std::string& msg);
|
||||
|
||||
// 获取配置副本(避免外部直接改内部 cfg)
|
||||
SxLogConfig getConfigCopy() const;
|
||||
|
||||
// 批量设置配置(整体替换)
|
||||
void setConfig(const SxLogConfig& cfg);
|
||||
|
||||
// 工具:把级别转为字符串(用于前缀)
|
||||
static const char* levelToString(SxLogLevel level);
|
||||
|
||||
// 工具:生成本地时间戳字符串(用于前缀与文件滚动名)
|
||||
static std::string makeTimestampLocal();
|
||||
|
||||
private:
|
||||
SxLogger();
|
||||
|
||||
// 判断 tag 是否允许输出(根据 Tag 过滤模式与 tagList)
|
||||
static bool tagAllowed(const SxLogConfig& cfg, const char* tag);
|
||||
|
||||
// 生成前缀(调用方需已持有锁)
|
||||
std::string formatPrefixUnlocked(
|
||||
const SxLogConfig& cfg,
|
||||
SxLogLevel level,
|
||||
const char* tag,
|
||||
const char* file,
|
||||
int line,
|
||||
const char* func) const;
|
||||
|
||||
mutable std::mutex mtx; // 保护 cfg 与 sink 写入,确保多线程行级一致性
|
||||
SxLogConfig cfg; // 当前配置
|
||||
std::atomic<SxLogLanguage> lang; // 语言开关(仅影响 SX_T 选择)
|
||||
|
||||
std::unique_ptr<ConsoleSink> consoleSink; // 控制台 sink(enableConsole 控制)
|
||||
std::unique_ptr<FileSink> fileSink; // 文件 sink(enableFile 控制)
|
||||
};
|
||||
|
||||
/* ========================= 双语选择辅助 ========================= */
|
||||
// 说明:
|
||||
// - 只做“选择 zhCN 或 enUS”,不做编码转换
|
||||
// - 输出显示是否正常由终端环境决定
|
||||
inline const char* SxT(const char* zhCN, const char* enUS)
|
||||
{
|
||||
return (SxLogger::Get().getLanguage() == SxLogLanguage::ZhCN) ? zhCN : enUS;
|
||||
}
|
||||
|
||||
#if defined(__cpp_char8_t) && (__cpp_char8_t >= 201811L)
|
||||
// 说明:
|
||||
// - C++20 的 u8"xxx" 是 char8_t*,为了兼容调用端,这里提供重载
|
||||
// - reinterpret_cast 只是改指针类型,不做 UTF-8 -> GBK 转码
|
||||
inline const char* SxT(const char8_t* zhCN, const char* enUS)
|
||||
{
|
||||
return (SxLogger::Get().getLanguage() == SxLogLanguage::ZhCN)
|
||||
? reinterpret_cast<const char*>(zhCN)
|
||||
: enUS;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ========================= RAII 日志行对象 ========================= */
|
||||
// 作用:
|
||||
// - 构造时记录 level/tag/源码位置
|
||||
// - operator<< 拼接内容
|
||||
// - 析构时统一提交给 SxLogger::logLine 输出
|
||||
//
|
||||
// 设计意义:
|
||||
// - 避免调用端忘记写换行
|
||||
// - 保证一行日志作为整体写出
|
||||
class SxLogLine
|
||||
{
|
||||
public:
|
||||
// 构造:记录元信息(不输出)
|
||||
SxLogLine(SxLogLevel level, const char* tag, const char* file, int line, const char* func);
|
||||
|
||||
// 析构:提交输出(真正写出发生在这里)
|
||||
~SxLogLine();
|
||||
|
||||
// 拼接内容(流式写法)
|
||||
template<typename T>
|
||||
SxLogLine& operator<<(const T& v)
|
||||
{
|
||||
ss << v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
SxLogLevel lvl; // 日志级别
|
||||
const char* tg; // Tag(不拥有内存)
|
||||
const char* srcFile; // 源文件名(来自 __FILE__)
|
||||
int srcLine; // 行号(来自 __LINE__)
|
||||
const char* srcFunc; // 函数名(来自 __func__)
|
||||
std::ostringstream ss; // 内容拼接缓冲
|
||||
};
|
||||
|
||||
/* ========================= RAII 作用域计时对象 ========================= */
|
||||
// 作用:
|
||||
// - 仅在 shouldLog(Trace, tag) 为 true 时启用计时
|
||||
// - 析构时输出耗时(微秒)
|
||||
//
|
||||
// 使用建议:
|
||||
// - 只在需要定位性能瓶颈时开启 Trace
|
||||
// - name 建议传入常量字符串,便于检索
|
||||
class SxLogScope
|
||||
{
|
||||
public:
|
||||
// 构造:根据 shouldLog 决定是否启用计时
|
||||
SxLogScope(SxLogLevel level, const char* tag, const char* file, int line, const char* func, const char* name);
|
||||
|
||||
// 析构:若启用则输出耗时
|
||||
~SxLogScope();
|
||||
|
||||
private:
|
||||
bool enabled = false; // 是否启用(未启用则析构无输出)
|
||||
SxLogLevel lvl = SxLogLevel::Trace; // 级别(通常用 Trace)
|
||||
const char* tg = nullptr; // Tag
|
||||
const char* srcFile = nullptr; // 源文件
|
||||
int srcLine = 0; // 行号
|
||||
const char* srcFunc = nullptr; // 函数
|
||||
const char* scopeName = nullptr; // 作用域名
|
||||
std::chrono::steady_clock::time_point t0; // 起始时间点
|
||||
};
|
||||
|
||||
} // namespace StellarX
|
||||
|
||||
#if SX_LOG_ENABLE
|
||||
|
||||
// SX_T:双语选择宏,调用 SxT 根据当前语言选择输出
|
||||
#define SX_T(zh, en) ::StellarX::SxT(zh, en)
|
||||
|
||||
// 日志宏说明:
|
||||
// 1) 先 shouldLog 短路过滤,未命中则不会构造 SxLogLine,也不会执行 else 分支的表达式
|
||||
// 2) 命中则构造临时 SxLogLine,并允许继续使用 operator<< 拼接
|
||||
// 3) 语句结束时临时对象析构,触发真正输出
|
||||
#define SX_LOG_TRACE(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Trace, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Trace, tag, __FILE__, __LINE__, __func__)
|
||||
#define SX_LOGD(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Debug, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Debug, tag, __FILE__, __LINE__, __func__)
|
||||
#define SX_LOGI(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Info, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Info, tag, __FILE__, __LINE__, __func__)
|
||||
#define SX_LOGW(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Warn, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Warn, tag, __FILE__, __LINE__, __func__)
|
||||
#define SX_LOGE(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Error, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Error, tag, __FILE__, __LINE__, __func__)
|
||||
#define SX_LOGF(tag) if(!::StellarX::SxLogger::Get().shouldLog(::StellarX::SxLogLevel::Fatal, tag)) ; else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Fatal, tag, __FILE__, __LINE__, __func__)
|
||||
|
||||
// 作用域耗时统计宏:默认用 Trace 级别
|
||||
#define SX_TRACE_SCOPE(tag, nameLiteral) ::StellarX::SxLogScope sx_scope_##__LINE__(::StellarX::SxLogLevel::Trace, tag, __FILE__, __LINE__, __func__, nameLiteral)
|
||||
|
||||
#else
|
||||
|
||||
// 关闭日志时的兼容宏:保证调用端代码不需要改动
|
||||
#define SX_T(zh, en) (en)
|
||||
#define SX_LOG_TRACE(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_LOGD(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_LOGI(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_LOGW(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_LOGE(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_LOGF(tag) if(true) {} else ::StellarX::SxLogLine(::StellarX::SxLogLevel::Off, tag, "", 0, "")
|
||||
#define SX_TRACE_SCOPE(tag, nameLiteral) do {} while(0)
|
||||
|
||||
#endif
|
||||
@@ -21,48 +21,56 @@
|
||||
#include "CoreTypes.h"
|
||||
#include "Button.h"
|
||||
#include "Canvas.h"
|
||||
#define BUTMINHEIGHT 15
|
||||
#define BUTMINWIDTH 30
|
||||
#define BUTMINHEIGHT 15 //页签按钮最小尺寸,过小会导致显示问题
|
||||
#define BUTMINWIDTH 30 //页签按钮最小尺寸,过小会导致显示问题
|
||||
class TabControl :public Canvas
|
||||
{
|
||||
int tabBarHeight = BUTMINWIDTH; //页签栏高度
|
||||
StellarX::TabPlacement tabPlacement = StellarX::TabPlacement::Top ; //页签排列方式
|
||||
std::vector<std::pair<std::unique_ptr<Button>,std::unique_ptr<Canvas>>> controls; //页签/页列表
|
||||
int tabBarHeight = BUTMINWIDTH; //页签栏高度
|
||||
bool IsFirstDraw = true; //首次绘制标记
|
||||
int defaultActivation = -1; //默认激活页签索引
|
||||
StellarX::TabPlacement tabPlacement = StellarX::TabPlacement::Top; //页签排列方式
|
||||
std::vector<std::pair<std::unique_ptr<Button>, std::unique_ptr<Canvas>>> controls; //页签/页列表
|
||||
|
||||
private:
|
||||
using Canvas::addControl; // 禁止外部误用
|
||||
void addControl(std::unique_ptr<Control>) = delete; // 精准禁用该重载
|
||||
using Canvas::addControl; // 禁止外部误用
|
||||
void addControl(std::unique_ptr<Control>) = delete; // 精准禁用该重载
|
||||
private:
|
||||
inline void initTabBar();
|
||||
inline void initTabPage();
|
||||
// 初始化页签按钮位置和尺寸
|
||||
inline void initTabBar();
|
||||
inline void initTabPage();
|
||||
public:
|
||||
TabControl();
|
||||
TabControl(int x,int y,int width,int height);
|
||||
TabControl(int x, int y, int width, int height);
|
||||
~TabControl();
|
||||
|
||||
|
||||
//重写位置设置以适应页签和页面布局
|
||||
void setX(int x)override;
|
||||
void setY(int y)override;
|
||||
|
||||
void draw() override;
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
|
||||
//添加页签+页
|
||||
void add(std::pair<std::unique_ptr<Button> ,std::unique_ptr<Canvas>>&& control);
|
||||
//添加为某个页添加控件
|
||||
void add(std::string tabText,std::unique_ptr<Control> control);
|
||||
//设置页签位置
|
||||
void setTabPlacement(StellarX::TabPlacement placement);
|
||||
//设置页签栏高度 两侧排列时为宽度
|
||||
void setTabBarHeight(int height);
|
||||
//设置不可见后传递给子控件重写
|
||||
void setIsVisible(bool visible) override;
|
||||
void onWindowResize() override;
|
||||
//获取当前激活页签索引
|
||||
int getActiveIndex() const;
|
||||
//设置当前激活页签索引
|
||||
void setActiveIndex(int idx);
|
||||
//获取页签数量
|
||||
int count() const;
|
||||
//通过页签文本返回索引
|
||||
int indexOf(const std::string& tabText) const;
|
||||
void setDirty(bool dirty) override;
|
||||
void requestRepaint(Control* parent)override;
|
||||
};
|
||||
|
||||
//添加页签+页
|
||||
void add(std::pair<std::unique_ptr<Button>, std::unique_ptr<Canvas>>&& control);
|
||||
//添加为某个页添加控件
|
||||
void add(std::string tabText, std::unique_ptr<Control> control);
|
||||
//设置页签位置
|
||||
void setTabPlacement(StellarX::TabPlacement placement);
|
||||
//设置页签栏高度 两侧排列时为宽度
|
||||
void setTabBarHeight(int height);
|
||||
//设置不可见后传递给子控件重写
|
||||
void setIsVisible(bool visible) override;
|
||||
void onWindowResize() override;
|
||||
//获取当前激活页签索引
|
||||
int getActiveIndex() const;
|
||||
//设置当前激活页签索引
|
||||
void setActiveIndex(int idx);
|
||||
//获取页签数量
|
||||
int count() const;
|
||||
//通过页签文本返回索引
|
||||
int indexOf(const std::string& tabText) const;
|
||||
//设置脏区并请求重绘
|
||||
void setDirty(bool dirty) override;
|
||||
//请求父控件重绘
|
||||
void requestRepaint(Control* parent)override;
|
||||
};
|
||||
|
||||
+19
-21
@@ -21,28 +21,26 @@
|
||||
|
||||
class Label : public Control
|
||||
{
|
||||
std::string text; //标签文本
|
||||
COLORREF textBkColor; //标签背景颜色
|
||||
bool textBkDisap = false; //标签背景是否透明
|
||||
std::string text; //标签文本
|
||||
COLORREF textBkColor; //标签背景颜色
|
||||
bool textBkDisap = false; //标签背景是否透明
|
||||
|
||||
//标签事件处理(标签无事件)不实现具体代码
|
||||
bool handleEvent(const ExMessage& msg) override { return false; }
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
//标签事件处理(标签无事件)不实现具体代码
|
||||
bool handleEvent(const ExMessage& msg) override { return false; }
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
public:
|
||||
StellarX::ControlText textStyle; //标签文本样式
|
||||
StellarX::ControlText textStyle; //标签文本样式
|
||||
public:
|
||||
Label();
|
||||
Label(int x, int y, std::string text = "标签",COLORREF textcolor = BLACK, COLORREF bkColor= RGB(255,255,255));
|
||||
|
||||
void draw() override;
|
||||
void hide();
|
||||
//设置标签背景是否透明
|
||||
void setTextdisap(bool key);
|
||||
//设置标签背景颜色
|
||||
void setTextBkColor(COLORREF color);
|
||||
//设置标签文本
|
||||
void setText(std::string text);
|
||||
|
||||
Label();
|
||||
Label(int x, int y, std::string text = "标签", COLORREF textcolor = BLACK, COLORREF bkColor = RGB(255, 255, 255));
|
||||
|
||||
void draw() override;
|
||||
void hide();
|
||||
//设置标签背景是否透明
|
||||
void setTextdisap(bool key);
|
||||
//设置标签背景颜色
|
||||
void setTextBkColor(COLORREF color);
|
||||
//设置标签文本
|
||||
void setText(std::string text);
|
||||
};
|
||||
|
||||
|
||||
+22
-11
@@ -16,7 +16,7 @@
|
||||
* @所属框架: 星垣(StellarX) GUI框架
|
||||
* @作者: 我在人间做废物
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
#include "Control.h"
|
||||
#include "Button.h"
|
||||
@@ -49,7 +49,6 @@
|
||||
#define TABLE_STR_PAGE_MID "页/共"
|
||||
#define TABLE_STR_PAGE_SUFFIX "页"
|
||||
|
||||
|
||||
class Table :public Control
|
||||
{
|
||||
private:
|
||||
@@ -64,16 +63,17 @@ private:
|
||||
|
||||
int rowsPerPage = TABLE_DEFAULT_ROWS_PER_PAGE; // 每页显示的行数
|
||||
int currentPage = 1; // 当前页码
|
||||
int totalPages = 1; // 总页数
|
||||
int totalPages = 1; // 总页数
|
||||
|
||||
bool isShowPageButton = true; // 是否显示翻页按钮
|
||||
bool isNeedDrawHeaders = true; // 是否需要绘制表头
|
||||
bool isNeedDrawHeaders = true; // 是否需要绘制表头(暂时废弃,单做保留,后期优化可能用到)
|
||||
bool isNeedCellSize = true; // 是否需要计算单元格尺寸
|
||||
bool isNeedButtonAndPageNum = true; // 是否需要计算翻页按钮和页码信息
|
||||
|
||||
Button* prevButton = nullptr; // 上一页按钮
|
||||
Button* nextButton = nullptr; // 下一页按钮
|
||||
Label* pageNum = nullptr; //页码文本
|
||||
|
||||
Label* pageNum = nullptr; //页码文本
|
||||
|
||||
int dX = x, dY = y; // 单元格的开始坐标
|
||||
int uX = x, uY = y; // 单元格的结束坐标
|
||||
|
||||
@@ -98,7 +98,10 @@ private:
|
||||
bool model() const override { return false; };
|
||||
public:
|
||||
StellarX::ControlText textStyle; // 文本样式
|
||||
|
||||
void setX(int x) override;
|
||||
void setY(int y) override;
|
||||
void setWidth(int width) override;
|
||||
void setHeight(int height) override;
|
||||
public:
|
||||
Table(int x, int y);
|
||||
~Table();
|
||||
@@ -127,6 +130,14 @@ public:
|
||||
void setTableLineStyle(StellarX::LineStyle style);
|
||||
//设置边框宽度
|
||||
void setTableBorderWidth(int width);
|
||||
//清空表头
|
||||
void clearHeaders();
|
||||
//清空表格数据
|
||||
void clearData();
|
||||
//清空表头和数据
|
||||
void resetTable();
|
||||
//窗口变化丢快照+标脏
|
||||
void onWindowResize() override;
|
||||
|
||||
//************************** 获取属性 *****************************/
|
||||
|
||||
@@ -147,12 +158,12 @@ public:
|
||||
//获取线型
|
||||
StellarX::LineStyle getTableLineStyle() const;
|
||||
//获取表头
|
||||
std::vector<std::string> getHeaders () const;
|
||||
std::vector<std::string> getHeaders() const;
|
||||
//获取表格数据
|
||||
std::vector<std::vector<std::string>> getData() const;
|
||||
//获取表格边框宽度
|
||||
int getTableBorderWidth() const;
|
||||
|
||||
|
||||
//获取表格尺寸
|
||||
int getTableWidth() const;
|
||||
int getTableHeight() const;
|
||||
};
|
||||
|
||||
|
||||
+26
-29
@@ -18,42 +18,39 @@
|
||||
#pragma once
|
||||
#include "Control.h"
|
||||
|
||||
|
||||
class TextBox : public Control
|
||||
{
|
||||
std::string text; //文本
|
||||
StellarX::TextBoxmode mode; //模式
|
||||
StellarX::ControlShape shape; //形状
|
||||
bool click = false; //是否点击
|
||||
size_t maxCharLen = 10;//最大字符长度
|
||||
COLORREF textBoxBkClor = RGB(255, 255, 255); //背景颜色
|
||||
COLORREF textBoxBorderClor = RGB(0,0,0); //边框颜色
|
||||
StellarX::TextBoxmode mode; //模式
|
||||
StellarX::ControlShape shape; //形状
|
||||
bool click = false; //是否点击
|
||||
size_t maxCharLen = 10;//最大字符长度
|
||||
COLORREF textBoxBkClor = RGB(255, 255, 255); //背景颜色
|
||||
COLORREF textBoxBorderClor = RGB(0, 0, 0); //边框颜色
|
||||
|
||||
public:
|
||||
StellarX::ControlText textStyle; //文本样式
|
||||
StellarX::ControlText textStyle; //文本样式
|
||||
|
||||
TextBox(int x, int y, int width, int height, std::string text = "", StellarX::TextBoxmode mode = StellarX::TextBoxmode::INPUT_MODE, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
void draw() override;
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
//设置模式
|
||||
void setMode(StellarX::TextBoxmode mode);
|
||||
//设置可输入最大字符长度
|
||||
void setMaxCharLen(size_t len);
|
||||
//设置形状
|
||||
void setTextBoxshape(StellarX::ControlShape shape);
|
||||
//设置边框颜色
|
||||
void setTextBoxBorder(COLORREF color);
|
||||
//设置背景颜色
|
||||
void setTextBoxBk(COLORREF color);
|
||||
//设置文本
|
||||
void setText(std::string text);
|
||||
TextBox(int x, int y, int width, int height, std::string text = "", StellarX::TextBoxmode mode = StellarX::TextBoxmode::INPUT_MODE, StellarX::ControlShape shape = StellarX::ControlShape::RECTANGLE);
|
||||
void draw() override;
|
||||
bool handleEvent(const ExMessage& msg) override;
|
||||
//设置模式
|
||||
void setMode(StellarX::TextBoxmode mode);
|
||||
//设置可输入最大字符长度
|
||||
void setMaxCharLen(size_t len);
|
||||
//设置形状
|
||||
void setTextBoxshape(StellarX::ControlShape shape);
|
||||
//设置边框颜色
|
||||
void setTextBoxBorder(COLORREF color);
|
||||
//设置背景颜色
|
||||
void setTextBoxBk(COLORREF color);
|
||||
//设置文本
|
||||
void setText(std::string text);
|
||||
|
||||
//获取文本
|
||||
std::string getText() const;
|
||||
//获取文本
|
||||
std::string getText() const;
|
||||
|
||||
private:
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
//用来检查对话框是否模态,此控件不做实现
|
||||
bool model() const override { return false; };
|
||||
};
|
||||
|
||||
|
||||
|
||||
+74
-62
@@ -1,86 +1,98 @@
|
||||
|
||||
/**
|
||||
* Window(头文件)
|
||||
*
|
||||
* 设计目标:
|
||||
* - 提供一个基于 Win32 + EasyX 的“可拉伸且稳定不抖”的窗口容器。
|
||||
* - 通过消息过程子类化(WndProcThunk)接管关键消息(WM_SIZING/WM_SIZE/...)。
|
||||
* - 将“几何变化记录(pendingW/H)”与“统一收口重绘(needResizeDirty)”解耦。
|
||||
*
|
||||
* 关键点(与 .cpp 中实现对应):
|
||||
* - isSizing:处于交互拉伸阶段时,冻结重绘;松手后统一重绘,防止抖动。
|
||||
* - WM_SIZING:只做“最小尺寸夹紧”,不回滚矩形、不做对齐;把其余交给系统。
|
||||
* - WM_GETMINMAXINFO:按最小“客户区”换算到“窗口矩形”,提供系统层最小轨迹值。
|
||||
* - runEventLoop:只记录 WM_SIZE 的新尺寸;真正绘制放在 needResizeDirty 时集中处理。
|
||||
*/
|
||||
//fuck windows
|
||||
//fuck win32
|
||||
//fuck xiaomi
|
||||
#pragma once
|
||||
#include"Control.h"
|
||||
/*******************************************************************************
|
||||
* @类: Window
|
||||
* @摘要: 应用程序主窗口类,管理窗口生命周期和消息循环
|
||||
* @描述:
|
||||
* 创建和管理应用程序主窗口,作为所有控件的根容器。
|
||||
* 处理消息分发、事件循环和渲染调度。
|
||||
*
|
||||
* @特性:
|
||||
* - 多种窗口模式配置(双缓冲、控制台等)
|
||||
* - 背景图片和颜色支持
|
||||
* - 集成的对话框管理系统
|
||||
* - 完整的消息处理循环
|
||||
* - 控件和对话框的生命周期管理
|
||||
*
|
||||
* @使用场景: 应用程序主窗口,GUI程序的入口和核心
|
||||
* @所属框架: 星垣(StellarX) GUI框架
|
||||
* @作者: 我在人间做废物
|
||||
******************************************************************************/
|
||||
|
||||
#include "Control.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <windows.h>
|
||||
|
||||
class Window
|
||||
{
|
||||
int width; //窗口宽度
|
||||
int height; //窗口高度
|
||||
int windowMode = NULL; //窗口模式
|
||||
// —— 尺寸状态 ——(绘制尺寸与待应用尺寸分离;收口时一次性更新)
|
||||
int width; // 当前有效宽(已应用到画布/控件的客户区宽)
|
||||
int height; // 当前有效高(已应用到画布/控件的客户区高)
|
||||
int localwidth; // 基准宽(创建时的宽度)
|
||||
int localheight; // 基准高(创建是的高度)
|
||||
int pendingW; // 待应用宽(WM_SIZE/拉伸中记录用)
|
||||
int pendingH; // 待应用高
|
||||
int minClientW; // 业务设定的最小客户区宽(用于 GETMINMAXINFO 与 SIZING 夹紧)
|
||||
int minClientH; // 业务设定的最小客户区高
|
||||
int windowMode = NULL; // EasyX 初始化模式(EX_SHOWCONSOLE/EX_TOPMOST/...)
|
||||
bool needResizeDirty = false; // 统一收口重绘标志(置位后在事件环末尾处理)
|
||||
bool isSizing = false; // 是否处于拖拽阶段(ENTER/EXIT SIZEMOVE 切换)
|
||||
|
||||
// --- 尺寸变化去抖用 ---
|
||||
int pendingW;
|
||||
int pendingH;
|
||||
bool needResizeDirty = false;
|
||||
// —— 原生窗口句柄与子类化钩子 ——(子类化 EasyX 的窗口过程以拦截关键消息)
|
||||
HWND hWnd = NULL; // EasyX 初始化后的窗口句柄
|
||||
WNDPROC oldWndProc = nullptr; // 保存旧过程(CallWindowProc 回落)
|
||||
bool procHooked = false; // 避免重复子类化
|
||||
static LRESULT CALLBACK WndProcThunk(HWND h, UINT m, WPARAM w, LPARAM l); // 静态过程分发到 this
|
||||
|
||||
HWND hWnd = NULL; //窗口句柄
|
||||
std::string headline; //窗口标题
|
||||
COLORREF wBkcolor = BLACK; //窗口背景
|
||||
IMAGE* background = nullptr; //窗口背景图片
|
||||
std::string bkImageFile; //窗口背景图片文件名
|
||||
std::vector<std::unique_ptr<Control>> controls; //控件管理
|
||||
std::vector<std::unique_ptr<Control>> dialogs; //对话框管理
|
||||
// —— 绘制相关 ——(是否使用合成双缓冲、窗口标题、背景等)
|
||||
bool useComposited = true; // 是否启用 WS_EX_COMPOSITED(部分机器可能增加一帧观感延迟)
|
||||
std::string headline; // 窗口标题文本
|
||||
COLORREF wBkcolor = BLACK; // 纯色背景(无背景图时使用)
|
||||
IMAGE* background = nullptr; // 背景图对象指针(存在时优先绘制)
|
||||
std::string bkImageFile; // 背景图文件路径(loadimage 用)
|
||||
|
||||
// —— 控件/对话框 ——(容器内的普通控件与非模态对话框)
|
||||
std::vector<std::unique_ptr<Control>> controls;
|
||||
std::vector<std::unique_ptr<Control>> dialogs;
|
||||
|
||||
public:
|
||||
bool dialogClose = false; //是否有对话框关闭
|
||||
bool dialogClose = false; // 项目内使用的状态位,对话框关闭标志
|
||||
mutable bool dialogOpen = false; // 项目内使用的状态位,对话框打开标志
|
||||
|
||||
// —— 构造/析构 ——(仅初始化成员;实际样式与子类化在 draw() 中完成)
|
||||
Window(int width, int height, int mode);
|
||||
Window(int width, int height, int mode, COLORREF bkcloc);
|
||||
Window(int width, int height, int mode , COLORREF bkcloc, std::string headline = "窗口");
|
||||
Window(int width, int height, int mode, COLORREF bkcloc, std::string headline);
|
||||
~Window();
|
||||
//绘制窗口
|
||||
void draw();
|
||||
void draw(std::string pImgFile);
|
||||
//事件循环
|
||||
int runEventLoop();
|
||||
//设置窗口背景图片
|
||||
|
||||
// —— 绘制与事件循环 ——(draw* 完成一次全量绘制;runEventLoop 驱动事件与统一收口)
|
||||
void draw(); // 纯色背景版本
|
||||
void draw(std::string pImgFile); // 背景图版本
|
||||
int runEventLoop(); // 主事件循环(PeekMessage + 统一收口重绘)
|
||||
|
||||
// —— 背景/标题设置 ——(更换背景、背景色与标题;立即触发一次批量绘制)
|
||||
void setBkImage(std::string pImgFile);
|
||||
//设置窗口背景颜色
|
||||
void setBkcolor(COLORREF c);
|
||||
//设置窗口标题
|
||||
void setHeadline(std::string headline);
|
||||
//添加控件
|
||||
|
||||
// —— 控件/对话框管理 ——(添加到容器,或做存在性判断)
|
||||
void addControl(std::unique_ptr<Control> control);
|
||||
//添加对话框
|
||||
void addDialog(std::unique_ptr<Control> dialogs);
|
||||
//检查是否已有对话框显示用于去重,防止工厂模式调用非模态对话框,多次打开污染对话框背景快照
|
||||
void addDialog(std::unique_ptr<Control> dialogs);
|
||||
bool hasNonModalDialogWithCaption(const std::string& caption, const std::string& message) const;
|
||||
|
||||
//获取窗口句柄
|
||||
HWND getHwnd() const;
|
||||
//获取窗口宽度
|
||||
int getWidth() const;
|
||||
//获取窗口高度
|
||||
int getHeight() const;
|
||||
//获取窗口标题
|
||||
// —— 访问器 ——(只读接口,供外部查询当前窗口/标题/背景等)
|
||||
HWND getHwnd() const;
|
||||
int getWidth() const;
|
||||
int getHeight() const;
|
||||
std::string getHeadline() const;
|
||||
//获取窗口背景颜色
|
||||
COLORREF getBkcolor() const;
|
||||
//获取窗口背景图片
|
||||
COLORREF getBkcolor() const;
|
||||
IMAGE* getBkImage() const;
|
||||
//获取窗口背景图片文件名
|
||||
std::string getBkImageFile() const;
|
||||
//获取控件管理
|
||||
std::vector<std::unique_ptr<Control>>& getControls();
|
||||
|
||||
// —— 尺寸调整 ——(供内部与外部调用的尺寸变化处理)
|
||||
void pumpResizeIfNeeded(); // 执行一次统一收口重绘
|
||||
void scheduleResizeFromModal(int w, int h);
|
||||
private:
|
||||
void adaptiveLayout(std::unique_ptr<Control>& c, const int finalH, const int finalW);
|
||||
};
|
||||
|
||||
|
||||
|
||||
+85
-90
@@ -1,4 +1,5 @@
|
||||
#include "Button.h"
|
||||
#include "SxLog.h"
|
||||
|
||||
Button::Button(int x, int y, int width, int height, const std::string text, StellarX::ButtonMode mode, StellarX::ControlShape shape)
|
||||
: Control(x, y, width, height)
|
||||
@@ -22,7 +23,7 @@ static inline int gbk_char_len(const std::string& s, size_t i)
|
||||
{
|
||||
unsigned char b = (unsigned char)s[i];
|
||||
if (b <= 0x7F) return 1; // ASCII
|
||||
if (b >= 0x81 && b <= 0xFE && i + 1 < s.size())
|
||||
if (b >= 0x81 && b <= 0xFE && i + 1 < s.size())
|
||||
{
|
||||
unsigned char b2 = (unsigned char)s[i + 1];
|
||||
if (b2 >= 0x40 && b2 <= 0xFE && b2 != 0x7F) return 2; // 合法双字节
|
||||
@@ -30,10 +31,10 @@ static inline int gbk_char_len(const std::string& s, size_t i)
|
||||
return 1; // 容错
|
||||
}
|
||||
|
||||
static inline void rtrim_spaces_gbk(std::string& s)
|
||||
static inline void rtrim_spaces_gbk(std::string& s)
|
||||
{
|
||||
while (!s.empty() && s.back() == ' ') s.pop_back(); // ASCII 空格
|
||||
while (s.size() >= 2)
|
||||
while (s.size() >= 2)
|
||||
{ // 全角空格 A1 A1
|
||||
unsigned char a = (unsigned char)s[s.size() - 2];
|
||||
unsigned char b = (unsigned char)s[s.size() - 1];
|
||||
@@ -42,26 +43,26 @@ static inline void rtrim_spaces_gbk(std::string& s)
|
||||
}
|
||||
}
|
||||
|
||||
static inline bool is_ascii_only(const std::string& s)
|
||||
static inline bool is_ascii_only(const std::string& s)
|
||||
{
|
||||
for (unsigned char c : s) if (c > 0x7F) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static inline bool is_word_boundary_char(unsigned char c)
|
||||
static inline bool is_word_boundary_char(unsigned char c)
|
||||
{
|
||||
return c == ' ' || c == '-' || c == '_' || c == '/' || c == '\\' || c == '.' || c == ':';
|
||||
}
|
||||
|
||||
// 英文优先策略:优先在“词边界”回退,再退化到逐字符;省略号为 "..."
|
||||
static std::string ellipsize_ascii_pref(const std::string& text, int maxW)
|
||||
static std::string ellipsize_ascii_pref(const std::string& text, int maxW)
|
||||
{
|
||||
if (maxW <= 0) return "";
|
||||
if (textwidth(LPCTSTR(text.c_str())) <= maxW) return text;
|
||||
|
||||
const std::string ell = "...";
|
||||
int ellW = textwidth(LPCTSTR(ell.c_str()));
|
||||
if (ellW > maxW)
|
||||
if (ellW > maxW)
|
||||
{ // 连 ... 都放不下
|
||||
std::string e = ell;
|
||||
while (!e.empty() && textwidth(LPCTSTR(e.c_str())) > maxW) e.pop_back();
|
||||
@@ -71,7 +72,7 @@ static std::string ellipsize_ascii_pref(const std::string& text, int maxW)
|
||||
|
||||
// 先找到能放下的最长前缀
|
||||
size_t i = 0, lastFit = 0;
|
||||
while (i < text.size())
|
||||
while (i < text.size())
|
||||
{
|
||||
int clen = gbk_char_len(text, i);
|
||||
size_t j = text.size() < i + (size_t)clen ? text.size() : i + (size_t)clen;
|
||||
@@ -83,7 +84,7 @@ static std::string ellipsize_ascii_pref(const std::string& text, int maxW)
|
||||
|
||||
// 在已适配前缀范围内,向左找最近的词边界
|
||||
size_t cutPos = lastFit;
|
||||
for (size_t k = lastFit; k > 0; --k)
|
||||
for (size_t k = lastFit; k > 0; --k)
|
||||
{
|
||||
unsigned char c = (unsigned char)text[k - 1];
|
||||
if (c <= 0x7F && is_word_boundary_char(c)) { cutPos = k - 1; break; }
|
||||
@@ -96,14 +97,14 @@ static std::string ellipsize_ascii_pref(const std::string& text, int maxW)
|
||||
}
|
||||
|
||||
// 中文优先策略:严格逐“字符”(1/2字节)回退;省略号用全角 "…"
|
||||
static std::string ellipsize_cjk_pref(const std::string& text, int maxW, const char* ellipsis = "…")
|
||||
static std::string ellipsize_cjk_pref(const std::string& text, int maxW, const char* ellipsis = "…")
|
||||
{
|
||||
if (maxW <= 0) return "";
|
||||
if (textwidth(LPCTSTR(text.c_str())) <= maxW) return text;
|
||||
|
||||
std::string ell = ellipsis ? ellipsis : "…";
|
||||
int ellW = textwidth(LPCTSTR(ell.c_str()));
|
||||
if (ellW > maxW)
|
||||
if (ellW > maxW)
|
||||
{ // 连省略号都放不下
|
||||
std::string e = ell;
|
||||
while (!e.empty() && textwidth(LPCTSTR(e.c_str())) > maxW) e.pop_back();
|
||||
@@ -112,7 +113,7 @@ static std::string ellipsize_cjk_pref(const std::string& text, int maxW, const c
|
||||
const int limit = maxW - ellW;
|
||||
|
||||
size_t i = 0, lastFit = 0;
|
||||
while (i < text.size())
|
||||
while (i < text.size())
|
||||
{
|
||||
int clen = gbk_char_len(text, i);
|
||||
size_t j = text.size() < i + (size_t)clen ? text.size() : i + (size_t)clen;
|
||||
@@ -163,11 +164,10 @@ void Button::initButton(const std::string text, StellarX::ButtonMode mode, Stell
|
||||
tipLabel.textStyle = this->textStyle; // 复用按钮字体样式
|
||||
}
|
||||
|
||||
|
||||
Button::~Button()
|
||||
{
|
||||
if (buttonFileIMAGE)
|
||||
delete buttonFileIMAGE;
|
||||
if (buttonFileIMAGE)
|
||||
delete buttonFileIMAGE;
|
||||
buttonFileIMAGE = nullptr;
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ void Button::draw()
|
||||
//设置按钮填充模式
|
||||
setfillstyle((int)buttonFillMode, (int)buttonFillIma, buttonFileIMAGE);
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
saveBackground(this->x, this->y, (this->width + bordWith), (this->height + bordHeight));
|
||||
// 恢复背景(清除旧内容)
|
||||
restBackground();
|
||||
//根据按钮形状绘制
|
||||
@@ -274,7 +274,6 @@ void Button::draw()
|
||||
|
||||
restoreStyle();//恢复默认字体样式和颜色
|
||||
dirty = false; //标记按钮不需要重绘
|
||||
|
||||
}
|
||||
// 处理鼠标事件,检测点击和悬停状态
|
||||
// 根据按钮模式和形状进行不同的处理
|
||||
@@ -283,8 +282,9 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
if (!show)
|
||||
return false;
|
||||
|
||||
bool oldHover = hover;
|
||||
bool oldHover = hover;// 注意:只在状态变化时记录,避免 WM_MOUSEMOVE 刷屏
|
||||
bool oldClick = click;
|
||||
|
||||
bool consume = false;//是否消耗事件
|
||||
// 记录鼠标位置(用于tip定位)
|
||||
if (msg.message == WM_MOUSEMOVE)
|
||||
@@ -310,14 +310,20 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
hover = isMouseInEllipse(msg.x, msg.y, x, y, x + width, y + height);
|
||||
break;
|
||||
}
|
||||
|
||||
if (hover != oldHover)
|
||||
{
|
||||
SX_LOGD("Button") << SX_T("悬停变化: ","hover change: ") << "id=" << id
|
||||
<< " text= " << text
|
||||
<< " " << (oldHover ? 1 : 0) << "->" << (hover ? 1 : 0);
|
||||
}
|
||||
// 处理鼠标点击事件
|
||||
if (msg.message == WM_LBUTTONDOWN && hover && mode != StellarX::ButtonMode::DISABLED)
|
||||
{
|
||||
|
||||
if (mode == StellarX::ButtonMode::NORMAL)
|
||||
{
|
||||
click = true;
|
||||
SX_LOGD("Button") << SX_T("被点击: ","lbtn - down:")<< "id = " << id <<" text = "<<text << " mode = " << (int)mode;
|
||||
|
||||
dirty = true;
|
||||
consume = true;
|
||||
}
|
||||
@@ -327,13 +333,15 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
}
|
||||
}
|
||||
// NORMAL 模式:鼠标在按钮上释放时才触发点击回调,如果移出区域则取消点击状态。
|
||||
// TOGGLE 模式:在释放时切换状态,并触发相应的开/关回调。
|
||||
// TOGGLE 模式:在释放时切换状态,并触发相应的开/关回调。
|
||||
else if (msg.message == WM_LBUTTONUP && hover && mode != StellarX::ButtonMode::DISABLED)
|
||||
{
|
||||
hideTooltip(); // 隐藏悬停提示
|
||||
if (mode == StellarX::ButtonMode::NORMAL && click)
|
||||
{
|
||||
if (onClickCallback) onClickCallback();
|
||||
SX_LOGI("Button") << "click: id=" << id << " (NORMAL) callback=" << (onClickCallback ? "Y" : "N");
|
||||
|
||||
click = false;
|
||||
dirty = true;
|
||||
consume = true;
|
||||
@@ -346,10 +354,15 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
click = !click;
|
||||
if (click && onToggleOnCallback) onToggleOnCallback();
|
||||
else if (!click && onToggleOffCallback) onToggleOffCallback();
|
||||
SX_LOGI("Button") << "toggle: id=" << id
|
||||
<< " " << (oldClick ? 1 : 0) << "->" << (click ? 1 : 0)
|
||||
<< " onCb=" << (onToggleOnCallback ? "Y" : "N")
|
||||
<< " offCb=" << (onToggleOffCallback ? "Y" : "N");
|
||||
|
||||
dirty = true;
|
||||
consume = true;
|
||||
refreshTooltipTextForState();
|
||||
hideTooltip();
|
||||
hideTooltip();
|
||||
// 清除消息队列中积压的鼠标和键盘消息,防止本次点击事件被重复处理
|
||||
flushmessage(EX_MOUSE | EX_KEY);
|
||||
}
|
||||
@@ -367,24 +380,26 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
if (tipEnabled)
|
||||
if (tipEnabled)
|
||||
{
|
||||
if (hover && !oldHover)
|
||||
if (hover && !oldHover)
|
||||
{
|
||||
// 刚刚进入悬停:开计时,暂不显示
|
||||
tipHoverTick = GetTickCount64();
|
||||
tipVisible = false;
|
||||
}
|
||||
if (!hover && oldHover)
|
||||
if (!hover && oldHover)
|
||||
{
|
||||
// 刚移出:立即隐藏
|
||||
hideTooltip();
|
||||
}
|
||||
if (hover && !tipVisible)
|
||||
if (hover && !tipVisible)
|
||||
{
|
||||
// 到点就显示
|
||||
if (GetTickCount64() - tipHoverTick >= (ULONGLONG)tipDelayMs)
|
||||
if (GetTickCount64() - tipHoverTick >= (ULONGLONG)tipDelayMs)
|
||||
{
|
||||
SX_LOGD("Button") << SX_T("提示信息显示: ","tooltip show:")<<" id = " << id <<SX_T("延时时间: ", " delayMs = ") << tipDelayMs;
|
||||
|
||||
tipVisible = true;
|
||||
|
||||
// 定位(跟随鼠标 or 相对按钮)
|
||||
@@ -420,18 +435,18 @@ bool Button::handleEvent(const ExMessage& msg)
|
||||
|
||||
if (tipEnabled && tipVisible)
|
||||
tipLabel.draw();
|
||||
|
||||
|
||||
return consume;
|
||||
}
|
||||
|
||||
void Button::setOnClickListener(const std::function<void()>&& callback)
|
||||
{
|
||||
this->onClickCallback = callback;
|
||||
this->onClickCallback = callback;
|
||||
}
|
||||
|
||||
void Button::setOnToggleOnListener(const std::function<void()>&& callback)
|
||||
{
|
||||
this->onToggleOnCallback = callback;
|
||||
this->onToggleOnCallback = callback;
|
||||
}
|
||||
void Button::setOnToggleOffListener(const std::function<void()>&& callback)
|
||||
{
|
||||
@@ -443,37 +458,36 @@ void Button::setbuttonMode(StellarX::ButtonMode mode)
|
||||
if (this->mode == StellarX::ButtonMode::DISABLED && mode != StellarX::ButtonMode::DISABLED)
|
||||
textStyle.bStrikeOut = false;
|
||||
//取值范围参考 buttMode的枚举注释
|
||||
this->mode = mode;
|
||||
this->mode = mode;
|
||||
dirty = true; // 标记需要重绘
|
||||
}
|
||||
|
||||
void Button::setROUND_RECTANGLEwidth(int width)
|
||||
{
|
||||
rouRectangleSize.ROUND_RECTANGLEwidth = width;
|
||||
rouRectangleSize.ROUND_RECTANGLEwidth = width;
|
||||
this->dirty = true; // 标记需要重绘
|
||||
|
||||
}
|
||||
|
||||
void Button::setROUND_RECTANGLEheight(int height)
|
||||
{
|
||||
rouRectangleSize.ROUND_RECTANGLEheight = height;
|
||||
rouRectangleSize.ROUND_RECTANGLEheight = height;
|
||||
this->dirty = true; // 标记需要重绘
|
||||
}
|
||||
|
||||
bool Button::isClicked() const
|
||||
{
|
||||
return this->click;
|
||||
return this->click;
|
||||
}
|
||||
|
||||
void Button::setFillMode(StellarX::FillMode mode)
|
||||
{
|
||||
this->buttonFillMode = mode;
|
||||
this->buttonFillMode = mode;
|
||||
this->dirty = true; // 标记需要重绘
|
||||
}
|
||||
|
||||
void Button::setFillIma(StellarX::FillStyle ima)
|
||||
{
|
||||
buttonFillIma = ima;
|
||||
buttonFillIma = ima;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
@@ -484,16 +498,15 @@ void Button::setFillIma(std::string imaNAme)
|
||||
delete buttonFileIMAGE;
|
||||
buttonFileIMAGE = nullptr;
|
||||
}
|
||||
buttonFileIMAGE = new IMAGE;
|
||||
loadimage(buttonFileIMAGE, imaNAme.c_str(),width,height);
|
||||
buttonFileIMAGE = new IMAGE;
|
||||
loadimage(buttonFileIMAGE, imaNAme.c_str(), width, height);
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
|
||||
void Button::setButtonBorder(COLORREF Border)
|
||||
{
|
||||
buttonBorderColor = Border;
|
||||
this->dirty = true;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void Button::setButtonFalseColor(COLORREF color)
|
||||
@@ -504,7 +517,7 @@ void Button::setButtonFalseColor(COLORREF color)
|
||||
|
||||
void Button::setButtonText(const char* text)
|
||||
{
|
||||
this->text = std::string(text);
|
||||
this->text = std::string(text);
|
||||
this->text_width = textwidth(LPCTSTR(this->text.c_str()));
|
||||
this->text_height = textheight(LPCTSTR(this->text.c_str()));
|
||||
this->dirty = true;
|
||||
@@ -526,7 +539,7 @@ void Button::setButtonText(std::string text)
|
||||
|
||||
void Button::setButtonShape(StellarX::ControlShape shape)
|
||||
{
|
||||
this->shape = shape;
|
||||
this->shape = shape;
|
||||
this->dirty = true;
|
||||
this->needCutText = true;
|
||||
}
|
||||
@@ -535,7 +548,7 @@ void Button::setButtonShape(StellarX::ControlShape shape)
|
||||
void Button::setButtonClick(BOOL click)
|
||||
{
|
||||
this->click = click;
|
||||
|
||||
|
||||
if (mode == StellarX::ButtonMode::NORMAL && click)
|
||||
{
|
||||
if (onClickCallback) onClickCallback();
|
||||
@@ -550,7 +563,7 @@ void Button::setButtonClick(BOOL click)
|
||||
else if (!click && onToggleOffCallback) onToggleOffCallback();
|
||||
dirty = true;
|
||||
refreshTooltipTextForState();
|
||||
hideTooltip();
|
||||
hideTooltip();
|
||||
// 清除消息队列中积压的鼠标和键盘消息,防止本次点击事件被重复处理
|
||||
flushmessage(EX_MOUSE | EX_KEY);
|
||||
}
|
||||
@@ -558,76 +571,63 @@ void Button::setButtonClick(BOOL click)
|
||||
requestRepaint(parent);
|
||||
}
|
||||
|
||||
|
||||
std::string Button::getButtonText() const
|
||||
{
|
||||
return this->text;
|
||||
return this->text;
|
||||
}
|
||||
|
||||
const char* Button::getButtonText_c() const
|
||||
{
|
||||
return this->text.c_str();
|
||||
return this->text.c_str();
|
||||
}
|
||||
|
||||
StellarX::ButtonMode Button::getButtonMode() const
|
||||
{
|
||||
return this->mode;
|
||||
return this->mode;
|
||||
}
|
||||
|
||||
StellarX::ControlShape Button::getButtonShape() const
|
||||
{
|
||||
return this->shape;
|
||||
return this->shape;
|
||||
}
|
||||
|
||||
StellarX::FillMode Button::getFillMode() const
|
||||
{
|
||||
return this->buttonFillMode;
|
||||
return this->buttonFillMode;
|
||||
}
|
||||
|
||||
StellarX::FillStyle Button::getFillIma() const
|
||||
{
|
||||
return this->buttonFillIma;
|
||||
return this->buttonFillIma;
|
||||
}
|
||||
|
||||
IMAGE* Button::getFillImaImage() const
|
||||
{
|
||||
return this->buttonFileIMAGE;
|
||||
return this->buttonFileIMAGE;
|
||||
}
|
||||
|
||||
COLORREF Button::getButtonBorder() const
|
||||
{
|
||||
return this->buttonBorderColor;
|
||||
return this->buttonBorderColor;
|
||||
}
|
||||
|
||||
COLORREF Button::getButtonTextColor() const
|
||||
{
|
||||
return this->textStyle.color;
|
||||
return this->textStyle.color;
|
||||
}
|
||||
|
||||
StellarX::ControlText Button::getButtonTextStyle() const
|
||||
{
|
||||
return this->textStyle;
|
||||
return this->textStyle;
|
||||
}
|
||||
|
||||
int Button::getButtonWidth() const
|
||||
{
|
||||
return this->width;
|
||||
}
|
||||
|
||||
int Button::getButtonHeight() const
|
||||
{
|
||||
return this->height;
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool Button::isMouseInCircle(int mouseX, int mouseY, int x, int y, int radius)
|
||||
{
|
||||
double dis = sqrt(pow(mouseX - x, 2) + pow(mouseY - y, 2));
|
||||
if (dis <= radius)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
double dis = sqrt(pow(mouseX - x, 2) + pow(mouseY - y, 2));
|
||||
if (dis <= radius)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Button::isMouseInEllipse(int mouseX, int mouseY, int x, int y, int width, int height)
|
||||
@@ -636,15 +636,15 @@ bool Button::isMouseInEllipse(int mouseX, int mouseY, int x, int y, int width, i
|
||||
int centerY = (y + height) / 2;
|
||||
int majorAxis = (width - x) / 2;
|
||||
int minorAxis = (height - y) / 2;
|
||||
double dx = mouseX - centerX;
|
||||
double dy = mouseY - centerY;
|
||||
double normalizedDistance = (dx * dx) / (majorAxis * majorAxis) + (dy * dy) / (minorAxis * minorAxis);
|
||||
double dx = mouseX - centerX;
|
||||
double dy = mouseY - centerY;
|
||||
double normalizedDistance = (dx * dx) / (majorAxis * majorAxis) + (dy * dy) / (minorAxis * minorAxis);
|
||||
|
||||
// 判断鼠标是否在椭圆内
|
||||
if (normalizedDistance <= 1.0)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
// 判断鼠标是否在椭圆内
|
||||
if (normalizedDistance <= 1.0)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void Button::cutButtonText()
|
||||
@@ -659,18 +659,16 @@ void Button::cutButtonText()
|
||||
}
|
||||
|
||||
// 放不下:按语言偏好裁切(ASCII→词边界;CJK→逐字符,不撕裂双字节)
|
||||
if (is_ascii_only(this->text))
|
||||
if (is_ascii_only(this->text))
|
||||
{
|
||||
cutText = ellipsize_ascii_pref(this->text, contentW); // "..."
|
||||
}
|
||||
else
|
||||
{
|
||||
cutText = ellipsize_cjk_pref(this->text, contentW, "…"); // 全角省略号
|
||||
|
||||
}
|
||||
isUseCutText = true;
|
||||
needCutText = false;
|
||||
|
||||
}
|
||||
|
||||
void Button::hideTooltip()
|
||||
@@ -686,11 +684,8 @@ void Button::hideTooltip()
|
||||
void Button::refreshTooltipTextForState()
|
||||
{
|
||||
if (tipUserOverride) return; // 用户显式设置过 tipText,保持不变
|
||||
if(mode==StellarX::ButtonMode::NORMAL)
|
||||
if (mode == StellarX::ButtonMode::NORMAL)
|
||||
tipLabel.setText(tipTextClick);
|
||||
else if(mode==StellarX::ButtonMode::TOGGLE)
|
||||
else if (mode == StellarX::ButtonMode::TOGGLE)
|
||||
tipLabel.setText(click ? tipTextOn : tipTextOff);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+295
-28
@@ -1,4 +1,10 @@
|
||||
#include "Canvas.h"
|
||||
#include "SxLog.h"
|
||||
|
||||
static bool SxIsNoisyMsg(UINT m)
|
||||
{
|
||||
return m == WM_MOUSEMOVE;
|
||||
}
|
||||
|
||||
Canvas::Canvas()
|
||||
:Control(0, 0, 100, 100)
|
||||
@@ -7,36 +13,81 @@ Canvas::Canvas()
|
||||
}
|
||||
|
||||
Canvas::Canvas(int x, int y, int width, int height)
|
||||
:Control(x, y, width, height)
|
||||
:Control(x, y, width, height)
|
||||
{
|
||||
this->id = "Canvas";
|
||||
}
|
||||
|
||||
void Canvas::setX(int x)
|
||||
{
|
||||
this->x = x;
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c->onWindowResize();
|
||||
c->setX(c->getLocalX() + this->x);
|
||||
}
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void Canvas::setY(int y)
|
||||
{
|
||||
this->y = y;
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c->onWindowResize();
|
||||
c->setY(c->getLocalY() + this->y);
|
||||
}
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void Canvas::clearAllControls()
|
||||
{
|
||||
controls.clear();
|
||||
}
|
||||
|
||||
|
||||
void Canvas::draw()
|
||||
{
|
||||
if (!dirty||!show)return;
|
||||
if (!dirty || !show)
|
||||
{
|
||||
for (auto& control : controls)
|
||||
if (auto c = dynamic_cast<Table*>(control.get()))
|
||||
c->draw();
|
||||
return;
|
||||
}
|
||||
saveStyle();
|
||||
|
||||
setlinecolor(canvasBorderClor);//设置线色
|
||||
setfillcolor(canvasBkClor);//设置填充色
|
||||
if (StellarX::FillMode::Null != canvasFillMode)
|
||||
setfillcolor(canvasBkClor);//设置填充色
|
||||
setfillstyle((int)canvasFillMode);//设置填充模式
|
||||
setlinestyle((int)canvasLineStyle, canvaslinewidth);
|
||||
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(x, y, width, height);
|
||||
// 恢复背景(清除旧内容)
|
||||
|
||||
// 在绘制画布之前,先恢复并更新背景快照:
|
||||
// 1. 如果已有快照,则先回贴旧快照以清除之前的内容。
|
||||
// 2. 当坐标或尺寸变化,或缓存图像无效时,丢弃旧快照并重新抓取新的背景。
|
||||
int margin = canvaslinewidth > 1 ? canvaslinewidth : 1;
|
||||
if (hasSnap)
|
||||
{
|
||||
// 恢复旧快照,清除上一次绘制
|
||||
restBackground();
|
||||
// 如果位置或尺寸变了,或没有有效缓存,则重新抓取
|
||||
if (!saveBkImage || saveBkX != this->x - margin || saveBkY != this->y - margin || saveWidth != this->width + margin * 2 || saveHeight != this->height + margin * 2)
|
||||
{
|
||||
discardBackground();
|
||||
saveBackground(this->x - margin, this->y - margin, this->width + margin * 2, this->height + margin * 2);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 首次绘制或没有快照时直接抓取背景
|
||||
saveBackground(this->x - margin, this->y - margin, this->width + margin * 2, this->height + margin * 2);
|
||||
}
|
||||
// 再次恢复最新快照,确保绘制区域干净
|
||||
restBackground();
|
||||
//根据画布形状绘制
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
fillrectangle(x,y,x+width,y+height);//有边框填充矩形
|
||||
fillrectangle(x, y, x + width, y + height);//有边框填充矩形
|
||||
break;
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
solidrectangle(x, y, x + width, y + height);//无边框填充矩形
|
||||
@@ -54,29 +105,64 @@ void Canvas::draw()
|
||||
control->setDirty(true);
|
||||
control->draw();
|
||||
}
|
||||
|
||||
|
||||
restoreStyle();
|
||||
dirty = false; //标记画布不需要重绘
|
||||
}
|
||||
|
||||
bool Canvas::handleEvent(const ExMessage& msg)
|
||||
{
|
||||
if (!show)return false;
|
||||
if (!show) return false;
|
||||
|
||||
bool consumed = false;
|
||||
bool anyDirty = false;
|
||||
Control* firstConsumer = nullptr;
|
||||
|
||||
for (auto it = controls.rbegin(); it != controls.rend(); ++it)
|
||||
{
|
||||
consumed |= it->get()->handleEvent(msg);
|
||||
if (it->get()->isDirty()) anyDirty = true;
|
||||
Control* c = it->get();
|
||||
bool cConsumed = c->handleEvent(msg);
|
||||
|
||||
if (cConsumed && !firstConsumer) firstConsumer = c;
|
||||
consumed |= cConsumed;
|
||||
|
||||
if (c->isDirty()) anyDirty = true;
|
||||
}
|
||||
if (anyDirty) requestRepaint(parent);
|
||||
|
||||
if (firstConsumer && !SxIsNoisyMsg(msg.message))
|
||||
{
|
||||
SX_LOGD("Event") << SX_T("Canvas 消耗消息: ","Canvas consumed: msg=") << msg.message
|
||||
<< SX_T("子控件"," by child")<<" id=" << firstConsumer->getId();
|
||||
}
|
||||
|
||||
if (anyDirty)
|
||||
{
|
||||
if (!SxIsNoisyMsg(msg.message))
|
||||
SX_LOGD("Dirty") << SX_T("Canvas检测有控件为脏状态 -> 请求重绘, ","Canvas anyDirty -> requestRepaint, ")<<"id = " << id;
|
||||
requestRepaint(parent);
|
||||
}
|
||||
|
||||
return consumed;
|
||||
}
|
||||
|
||||
|
||||
void Canvas::addControl(std::unique_ptr<Control> control)
|
||||
{
|
||||
|
||||
//坐标转化
|
||||
control->setX(control->getLocalX() + this->x);
|
||||
control->setY(control->getLocalY() + this->y);
|
||||
control->setParent(this);
|
||||
SX_LOGI("Canvas")
|
||||
<< SX_T("添加子控件:父=Canvas 子id=", "addControl: parent=Canvas childId=")
|
||||
<< control->getId()
|
||||
<< SX_T(" 相对坐标=(", " local=(")
|
||||
<< control->getLocalX() << "," << control->getLocalY()
|
||||
<< SX_T(") 绝对坐标=(", ") abs=(")
|
||||
<< control->getX() << "," << control->getY()
|
||||
<< ")";
|
||||
|
||||
|
||||
controls.push_back(std::move(control));
|
||||
dirty = true;
|
||||
}
|
||||
@@ -116,7 +202,7 @@ void Canvas::setBorderColor(COLORREF color)
|
||||
|
||||
void Canvas::setCanvasBkColor(COLORREF color)
|
||||
{
|
||||
this->canvasBkClor = color;
|
||||
this->canvasBkClor = color;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
@@ -126,7 +212,6 @@ void Canvas::setCanvasLineStyle(StellarX::LineStyle style)
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
|
||||
void Canvas::setLinewidth(int width)
|
||||
{
|
||||
this->canvaslinewidth = width;
|
||||
@@ -140,7 +225,6 @@ void Canvas::setIsVisible(bool visible)
|
||||
for (auto& control : controls)
|
||||
{
|
||||
control->setIsVisible(visible);
|
||||
control->setDirty(true);
|
||||
}
|
||||
if (!visible)
|
||||
this->updateBackground();
|
||||
@@ -149,31 +233,214 @@ void Canvas::setIsVisible(bool visible)
|
||||
void Canvas::setDirty(bool dirty)
|
||||
{
|
||||
this->dirty = dirty;
|
||||
for(auto& control : controls)
|
||||
for (auto& control : controls)
|
||||
control->setDirty(dirty);
|
||||
}
|
||||
|
||||
void Canvas::onWindowResize()
|
||||
{
|
||||
Control::onWindowResize(); // 先处理自己
|
||||
for (auto& ch : controls) // 再转发给所有子控件
|
||||
// 首先处理自身的快照等逻辑
|
||||
Control::onWindowResize();
|
||||
|
||||
// 记录父容器原始尺寸(用于计算子控件的右/下边距)
|
||||
int origParentW = this->localWidth;
|
||||
int origParentH = this->localHeight;
|
||||
|
||||
// 当前容器的新尺寸
|
||||
int finalW = this->width;
|
||||
int finalH = this->height;
|
||||
|
||||
// 当前容器的新坐标(全局坐标)
|
||||
int parentX = this->x;
|
||||
int parentY = this->y;
|
||||
|
||||
// 调整每个子控件在 AnchorToEdges 模式下的位置与尺寸
|
||||
for (auto& ch : controls)
|
||||
{
|
||||
// Only adjust when using anchor-to-edges layout
|
||||
if (ch->getLayoutMode() == StellarX::LayoutMode::AnchorToEdges)
|
||||
{
|
||||
// Determine whether this child is a Table; tables keep their height constant
|
||||
bool isTable = (dynamic_cast<Table*>(ch.get()) != nullptr);
|
||||
|
||||
// Unpack anchors
|
||||
auto a1 = ch->getAnchor_1();
|
||||
auto a2 = ch->getAnchor_2();
|
||||
|
||||
bool anchorLeft = (a1 == StellarX::Anchor::Left || a2 == StellarX::Anchor::Left);
|
||||
bool anchorRight = (a1 == StellarX::Anchor::Right || a2 == StellarX::Anchor::Right);
|
||||
bool anchorTop = (a1 == StellarX::Anchor::Top || a2 == StellarX::Anchor::Top);
|
||||
bool anchorBottom = (a1 == StellarX::Anchor::Bottom || a2 == StellarX::Anchor::Bottom);
|
||||
|
||||
// If it's a table, treat as anchored left and right horizontally and anchored top vertically by default.
|
||||
if (isTable)
|
||||
{
|
||||
anchorLeft = true;
|
||||
anchorRight = true;
|
||||
// If no explicit vertical anchor was provided, default to top.
|
||||
if (!(anchorTop || anchorBottom))
|
||||
{
|
||||
anchorTop = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Compute new X and width
|
||||
int newX = ch->getX();
|
||||
int newWidth = ch->getWidth();
|
||||
if (anchorLeft && anchorRight)
|
||||
{
|
||||
// Scale horizontally relative to parent's size.
|
||||
if (origParentW > 0)
|
||||
{
|
||||
// Maintain proportional position and size based on original local values.
|
||||
double scaleW = static_cast<double>(finalW) / static_cast<double>(origParentW);
|
||||
newX = parentX + static_cast<int>(ch->getLocalX() * scaleW + 0.5);
|
||||
newWidth = static_cast<int>(ch->getLocalWidth() * scaleW + 0.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback: keep original
|
||||
newX = parentX + ch->getLocalX();
|
||||
newWidth = ch->getLocalWidth();
|
||||
}
|
||||
}
|
||||
else if (anchorLeft && !anchorRight)
|
||||
{
|
||||
// Only left anchored: keep original width and left margin.
|
||||
newWidth = ch->getLocalWidth();
|
||||
newX = parentX + ch->getLocalX();
|
||||
}
|
||||
else if (!anchorLeft && anchorRight)
|
||||
{
|
||||
// Only right anchored: keep original width and right margin.
|
||||
newWidth = ch->getLocalWidth();
|
||||
int origRightDist = origParentW - (ch->getLocalX() + ch->getLocalWidth());
|
||||
newX = parentX + finalW - origRightDist - newWidth;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No horizontal anchor: position relative to parent's left and width unchanged.
|
||||
newWidth = ch->getLocalWidth();
|
||||
newX = parentX + ch->getLocalX();
|
||||
}
|
||||
ch->setX(newX);
|
||||
ch->setWidth(newWidth);
|
||||
|
||||
// Compute new Y and height
|
||||
int newY = ch->getY();
|
||||
int newHeight = ch->getHeight();
|
||||
if (isTable)
|
||||
{
|
||||
// Table: Height remains constant; adjust Y based on anchors.
|
||||
newHeight = ch->getLocalHeight();
|
||||
if (anchorTop && anchorBottom)
|
||||
{
|
||||
// If both top and bottom anchored, scale Y but keep height.
|
||||
if (origParentH > 0)
|
||||
{
|
||||
double scaleH = static_cast<double>(finalH) / static_cast<double>(origParentH);
|
||||
newY = parentY + static_cast<int>(ch->getLocalY() * scaleH + 0.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
newY = parentY + ch->getLocalY();
|
||||
}
|
||||
}
|
||||
else if (anchorTop && !anchorBottom)
|
||||
{
|
||||
// Top anchored only
|
||||
newY = parentY + ch->getLocalY();
|
||||
}
|
||||
else if (!anchorTop && anchorBottom)
|
||||
{
|
||||
// Bottom anchored only
|
||||
int origBottomDist = origParentH - (ch->getLocalY() + ch->getLocalHeight());
|
||||
newY = parentY + finalH - origBottomDist - newHeight;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No vertical anchor: default to top
|
||||
newY = parentY + ch->getLocalY();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (anchorTop && anchorBottom)
|
||||
{
|
||||
// Scale vertically relative to parent's size.
|
||||
if (origParentH > 0)
|
||||
{
|
||||
double scaleH = static_cast<double>(finalH) / static_cast<double>(origParentH);
|
||||
newY = parentY + static_cast<int>(ch->getLocalY() * scaleH + 0.5);
|
||||
newHeight = static_cast<int>(ch->getLocalHeight() * scaleH + 0.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
newY = parentY + ch->getLocalY();
|
||||
newHeight = ch->getLocalHeight();
|
||||
}
|
||||
}
|
||||
else if (anchorTop && !anchorBottom)
|
||||
{
|
||||
// Top anchored only: keep height constant
|
||||
newHeight = ch->getLocalHeight();
|
||||
newY = parentY + ch->getLocalY();
|
||||
}
|
||||
else if (!anchorTop && anchorBottom)
|
||||
{
|
||||
// Bottom anchored only: keep height and adjust Y relative to bottom
|
||||
newHeight = ch->getLocalHeight();
|
||||
int origBottomDist = origParentH - (ch->getLocalY() + ch->getLocalHeight());
|
||||
newY = parentY + finalH - origBottomDist - newHeight;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No vertical anchor: position relative to parent's top, height constant.
|
||||
newHeight = ch->getLocalHeight();
|
||||
newY = parentY + ch->getLocalY();
|
||||
}
|
||||
}
|
||||
ch->setY(newY);
|
||||
ch->setHeight(newHeight);
|
||||
}
|
||||
// Always forward the window resize event to the child (recursively).
|
||||
ch->onWindowResize();
|
||||
}
|
||||
}
|
||||
|
||||
void Canvas::requestRepaint(Control* parent)
|
||||
{
|
||||
if (this == parent)
|
||||
{
|
||||
if (!show)
|
||||
return;
|
||||
|
||||
// 关键护栏:
|
||||
// - Canvas 自己是脏的 / 没有快照 / 缓存图为空
|
||||
// => 禁止局部重绘,直接升级为一次完整 draw(先把 dirty 置真,避免 draw() 早退)
|
||||
if (dirty || !hasSnap || !saveBkImage)
|
||||
{
|
||||
SX_LOGD("Dirty")
|
||||
<< SX_T("Canvas 局部重绘降级为全量重绘: id=", "Canvas partial->full draw: id=")
|
||||
<< id
|
||||
<< " dirty=" << (dirty ? 1 : 0)
|
||||
<< " hasSnap=" << (hasSnap ? 1 : 0);
|
||||
|
||||
this->dirty = true;
|
||||
this->draw();
|
||||
return;
|
||||
}
|
||||
|
||||
SX_LOGD("Dirty") << SX_T("Canvas 请求局部重绘:id=", "Canvas::requestRepaint(partial): id=") << id;
|
||||
|
||||
for (auto& control : controls)
|
||||
if (control->isDirty() && control->IsVisible())
|
||||
{
|
||||
control->draw();
|
||||
break;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
else
|
||||
onRequestRepaintAsRoot();
|
||||
|
||||
SX_LOGD("Dirty") << SX_T("Canvas 请求根级重绘:id=", "Canvas::requestRepaint(root): id=") << id;
|
||||
onRequestRepaintAsRoot();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
+76
-4
@@ -1,4 +1,5 @@
|
||||
#include "Control.h"
|
||||
#include "SxLog.h"
|
||||
#include<assert.h>
|
||||
|
||||
StellarX::ControlText& StellarX::ControlText::operator=(const ControlText& text)
|
||||
@@ -44,16 +45,59 @@ bool StellarX::ControlText::operator!=(const ControlText& text)
|
||||
}
|
||||
void Control::setIsVisible(bool show)
|
||||
{
|
||||
if (!show)
|
||||
this->updateBackground();
|
||||
SX_LOGD("Control") << SX_T("重置可见状态: id=", "setIsVisible: id=")
|
||||
<< id
|
||||
<< " show=" << (show ? 1 : 0);
|
||||
|
||||
if (this->show == show)
|
||||
return;
|
||||
|
||||
this->show = show;
|
||||
this->dirty = true;
|
||||
|
||||
if (!show)
|
||||
{
|
||||
// 隐藏:擦除自己在屏幕上的内容,并释放快照
|
||||
this->updateBackground();
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示:不在这里 requestRepaint(避免父容器快照未就绪时子控件抢跑 draw,污染快照)
|
||||
// 仅向上标脏,让事件收口阶段由容器统一重绘。
|
||||
if (parent)
|
||||
parent->setDirty(true);
|
||||
}
|
||||
|
||||
void Control::onWindowResize()
|
||||
{
|
||||
SX_LOGD("Layout") << SX_T("尺寸变化:id=", "onWindowResize: id=") << id
|
||||
<< SX_T(" -> 丢背景快照 + 标脏", " -> discardSnap + dirty");
|
||||
|
||||
// 自己:丢快照 + 标脏
|
||||
discardBackground();
|
||||
setDirty(true);
|
||||
}
|
||||
void Control::setLayoutMode(StellarX::LayoutMode layoutMode_)
|
||||
{
|
||||
this->layoutMode = layoutMode_;
|
||||
}
|
||||
void Control::setAnchor(StellarX::Anchor anchor_1, StellarX::Anchor anchor_2)
|
||||
{
|
||||
this->anchor_1 = anchor_1;
|
||||
this->anchor_2 = anchor_2;
|
||||
}
|
||||
StellarX::Anchor Control::getAnchor_1() const
|
||||
{
|
||||
return this->anchor_1;
|
||||
}
|
||||
StellarX::Anchor Control::getAnchor_2() const
|
||||
{
|
||||
return this->anchor_2;
|
||||
}
|
||||
StellarX::LayoutMode Control::getLayoutMode() const
|
||||
{
|
||||
return this->layoutMode;
|
||||
}
|
||||
// 保存当前的绘图状态(字体、颜色、线型等)
|
||||
// 在控件绘制前调用,确保不会影响全局绘图状态
|
||||
void Control::saveStyle()
|
||||
@@ -79,12 +123,34 @@ void Control::restoreStyle()
|
||||
|
||||
void Control::requestRepaint(Control* parent)
|
||||
{
|
||||
if (parent) parent->requestRepaint(parent); // 向上冒泡
|
||||
else onRequestRepaintAsRoot(); // 到根控件/窗口兜底
|
||||
// 说明:
|
||||
// - 常规路径:子控件调用 requestRepaint(this->parent),然后 parent 负责局部重绘(Canvas/TabControl override)
|
||||
// - 兜底路径:如果某个“容器控件”没 override requestRepaint,就会出现 parent==this 的递归风险
|
||||
// 此时我们改为向更上层冒泡,直到根重绘。
|
||||
if (parent == this)
|
||||
{
|
||||
SX_LOGW("Dirty")
|
||||
<< SX_T("requestRepaint(默认容器兜底):id=", "requestRepaint(default-container-fallback): id=")
|
||||
<< id
|
||||
<< SX_T(",parent==this,向上层 parent 继续冒泡", " parent==this, bubble to upper parent");
|
||||
|
||||
if (this->parent) this->parent->requestRepaint(this->parent);
|
||||
else onRequestRepaintAsRoot();
|
||||
return;
|
||||
}
|
||||
|
||||
SX_LOGD("Dirty") << SX_T("请求重绘:id=","requestRepaint: id=") << id << " parent=" << (parent ? parent->getId() : "null");
|
||||
|
||||
if (parent) parent->requestRepaint(parent); // 交给容器处理(容器可局部重绘)
|
||||
else onRequestRepaintAsRoot(); // 根兜底
|
||||
}
|
||||
|
||||
void Control::onRequestRepaintAsRoot()
|
||||
{
|
||||
SX_LOGI("Dirty")
|
||||
<< SX_T("触发根重绘:id=", "onRequestRepaintAsRoot: id=") << id
|
||||
<< SX_T("(从根节点开始重画)", " (root repaint)");
|
||||
|
||||
|
||||
discardBackground();
|
||||
setDirty(true);
|
||||
@@ -101,9 +167,13 @@ void Control::saveBackground(int x, int y, int w, int h)
|
||||
//尺寸变了才重建,避免反复 new/delete
|
||||
if (saveBkImage->getwidth() != w || saveBkImage->getheight() != h)
|
||||
{
|
||||
SX_LOGD("Snap") <<SX_T("重新保存背景快照:id=", "saveBackground rebuild: id=") << id << " size=(" << w << "x" << h << ")";
|
||||
|
||||
delete saveBkImage; saveBkImage = nullptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
SX_LOGD("Snap") << SX_T("保存背景快照:id=", "saveBackground rebuild: id=") << id << " size=(" << w << "x" << h << ")";
|
||||
if (!saveBkImage) saveBkImage = new IMAGE(w, h);
|
||||
|
||||
SetWorkingImage(nullptr); // ★抓屏幕
|
||||
@@ -123,6 +193,8 @@ void Control::discardBackground()
|
||||
{
|
||||
if (saveBkImage)
|
||||
{
|
||||
restBackground();
|
||||
SX_LOGD("Snap") << SX_T("丢弃背景快照:id=","discardBackground: id=") << id << " hasSnap=" << (hasSnap ? 1 : 0);
|
||||
delete saveBkImage;
|
||||
saveBkImage = nullptr;
|
||||
}
|
||||
|
||||
+164
-142
@@ -1,21 +1,20 @@
|
||||
#include "Dialog.h"
|
||||
#include "SxLog.h"
|
||||
|
||||
Dialog::Dialog(Window& h,std::string text,std::string message, StellarX::MessageBoxType type, bool modal)
|
||||
: Canvas(),message(message), type(type), modal(modal), hWnd(h), titleText(text)
|
||||
Dialog::Dialog(Window& h, std::string text, std::string message, StellarX::MessageBoxType type, bool modal)
|
||||
: Canvas(), message(message), type(type), modal(modal), hWnd(h), titleText(text)
|
||||
{
|
||||
this->id = "Dialog";
|
||||
show = false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Dialog::~Dialog()
|
||||
{
|
||||
}
|
||||
|
||||
void Dialog::draw()
|
||||
{
|
||||
if(!show)
|
||||
if (!show)
|
||||
{
|
||||
// 如果对话框不可见且需要清理,执行清理
|
||||
if (pendingCleanup && !isCleaning)
|
||||
@@ -24,16 +23,16 @@ void Dialog::draw()
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 如果需要初始化,则执行初始化
|
||||
if (needsInitialization && show)
|
||||
{
|
||||
initDialogSize();
|
||||
needsInitialization = false;
|
||||
}
|
||||
// 如果需要初始化,则执行初始化
|
||||
if (needsInitialization && show)
|
||||
{
|
||||
initDialogSize();
|
||||
needsInitialization = false;
|
||||
}
|
||||
|
||||
if (dirty && show)
|
||||
{
|
||||
// 保存当前绘图状态
|
||||
if (dirty && show)
|
||||
{
|
||||
// 保存当前绘图状态
|
||||
saveStyle();
|
||||
|
||||
Canvas::setBorderColor(this->borderColor);
|
||||
@@ -41,12 +40,6 @@ void Dialog::draw()
|
||||
Canvas::setCanvasBkColor(this->backgroundColor);
|
||||
Canvas::setShape(StellarX::ControlShape::ROUND_RECTANGLE);
|
||||
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
//设置所有控件为脏状态
|
||||
/*for(auto& c :this->controls)
|
||||
c->setDirty(true);*/
|
||||
restBackground();
|
||||
Canvas::draw();
|
||||
|
||||
//绘制消息文本
|
||||
@@ -56,25 +49,22 @@ void Dialog::draw()
|
||||
settextstyle(textStyle.nHeight, textStyle.nWidth, textStyle.lpszFace,
|
||||
textStyle.nEscapement, textStyle.nOrientation, textStyle.nWeight,
|
||||
textStyle.bItalic, textStyle.bUnderline, textStyle.bStrikeOut);
|
||||
|
||||
|
||||
|
||||
int ty = y + closeButtonHeight + titleToTextMargin; // 文本起始Y坐标
|
||||
for (auto line:lines)
|
||||
for (auto& line : lines)
|
||||
{
|
||||
int tx = this->x + ((this->width - textwidth(line.c_str())) / 2); // 文本起始X坐标
|
||||
outtextxy(tx, ty, LPCTSTR(line.c_str()));
|
||||
ty = ty + textheight(LPCTSTR(line.c_str())) + 5; // 每行文本高度加5像素间距
|
||||
}
|
||||
|
||||
// 恢复绘图状态
|
||||
restoreStyle();
|
||||
// 恢复绘图状态
|
||||
restoreStyle();
|
||||
|
||||
dirty = false;
|
||||
}
|
||||
dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool Dialog::handleEvent(const ExMessage& msg)
|
||||
{
|
||||
bool consume = false;
|
||||
@@ -86,22 +76,22 @@ bool Dialog::handleEvent(const ExMessage& msg)
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// 如果正在清理或标记为待清理,则不处理事件
|
||||
if (pendingCleanup || isCleaning)
|
||||
return false;
|
||||
// 模态对话框不允许点击外部区域
|
||||
// 模态对话框:点击对话框外部区域时,发出提示音(\a)并吞噬该事件,不允许操作背景内容。
|
||||
if (modal && msg.message == WM_LBUTTONUP &&
|
||||
(msg.x < x || msg.x > x + width || msg.y < y || msg.y > y + height))
|
||||
{
|
||||
std::cout << "\a" << std::endl;
|
||||
// 模态对话框不允许点击外部区域
|
||||
return true;
|
||||
}
|
||||
|
||||
// 将事件传递给子控件处理
|
||||
if (!consume)
|
||||
consume = Canvas::handleEvent(msg);
|
||||
if (!consume)
|
||||
consume = Canvas::handleEvent(msg);
|
||||
|
||||
// 每次事件处理后检查是否需要执行延迟清理
|
||||
if (pendingCleanup && !isCleaning)
|
||||
@@ -140,7 +130,6 @@ void Dialog::SetModal(bool modal)
|
||||
this->modal = modal;
|
||||
}
|
||||
|
||||
|
||||
void Dialog::SetResult(StellarX::MessageBoxResult result)
|
||||
{
|
||||
this->result = result;
|
||||
@@ -160,6 +149,7 @@ void Dialog::Show()
|
||||
{
|
||||
if (pendingCleanup)
|
||||
performDelayedCleanup();
|
||||
SX_LOGI("Dialog") << SX_T("对话框弹出:是否模态=","Dialog::Show: modal=") << (modal ? 1 : 0);
|
||||
|
||||
show = true;
|
||||
dirty = true;
|
||||
@@ -167,36 +157,77 @@ void Dialog::Show()
|
||||
close = false;
|
||||
shouldClose = false;
|
||||
|
||||
hWnd.dialogOpen = true;// 通知窗口有对话框打开
|
||||
|
||||
if (modal)
|
||||
{
|
||||
{
|
||||
// 模态对话框需要阻塞当前线程直到对话框关闭
|
||||
while (show && !close)
|
||||
if (modal)
|
||||
{
|
||||
|
||||
// 处理消息
|
||||
ExMessage msg;
|
||||
if (peekmessage(&msg, EX_MOUSE | EX_KEY))
|
||||
{
|
||||
handleEvent(msg);
|
||||
// 记录当前窗口客户区尺寸,供轮询对比
|
||||
RECT rc0;
|
||||
GetClientRect(hWnd.getHwnd(), &rc0);
|
||||
int lastW = rc0.right - rc0.left;
|
||||
int lastH = rc0.bottom - rc0.top;
|
||||
|
||||
// 检查是否需要关闭
|
||||
if (shouldClose)
|
||||
while (show && !close)
|
||||
{
|
||||
// ① 轮询窗口尺寸(不依赖 WM_SIZE)
|
||||
RECT rc;
|
||||
GetClientRect(hWnd.getHwnd(), &rc);
|
||||
const int cw = rc.right - rc.left;
|
||||
const int ch = rc.bottom - rc.top;
|
||||
|
||||
if (cw != lastW || ch != lastH)
|
||||
{
|
||||
Close();
|
||||
break;
|
||||
lastW = cw;
|
||||
lastH = ch;
|
||||
SX_LOGD("Resize") <<SX_T("模态对话框检测到窗口大小变化:(", "Modal dialog detected window size change: (") << cw << "x" << ch << ")";
|
||||
|
||||
// 通知父窗口:有新尺寸 → 标记 needResizeDirty
|
||||
hWnd.scheduleResizeFromModal(cw, ch);
|
||||
|
||||
// 立即统一收口:父窗重绘 背景+普通控件(不会画到这只模态)
|
||||
hWnd.pumpResizeIfNeeded();
|
||||
|
||||
// 这只模态在新尺寸下重建布局 / 重抓背景 → 本帧要画自己
|
||||
setInitialization(true);
|
||||
setDirty(true);
|
||||
}
|
||||
|
||||
// ② 处理这只对话框的鼠标/键盘(沿用原来 EX_MOUSE | EX_KEY)
|
||||
ExMessage msg;
|
||||
if (peekmessage(&msg, EX_MOUSE | EX_KEY))
|
||||
{
|
||||
handleEvent(msg);
|
||||
if (shouldClose)
|
||||
{
|
||||
Close();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 最后一笔:只画这只模态,保证永远在最上层
|
||||
if (dirty)
|
||||
{
|
||||
BeginBatchDraw();
|
||||
this->draw(); // 注意:不要 requestRepaint(parent),只画自己
|
||||
EndBatchDraw();
|
||||
dirty = false;
|
||||
}
|
||||
|
||||
Sleep(10);
|
||||
}
|
||||
|
||||
// 重绘
|
||||
if (dirty)
|
||||
{
|
||||
requestRepaint(parent);
|
||||
FlushBatchDraw();
|
||||
}
|
||||
|
||||
// 避免CPU占用过高
|
||||
Sleep(10);
|
||||
if (pendingCleanup && !isCleaning)
|
||||
performDelayedCleanup();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 非模态仍由主循环托管
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
// 模态对话框关闭后执行清理
|
||||
if (pendingCleanup && !isCleaning)
|
||||
performDelayedCleanup();
|
||||
@@ -206,8 +237,6 @@ void Dialog::Show()
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Dialog::Close()
|
||||
{
|
||||
if (!show) return;
|
||||
@@ -216,13 +245,10 @@ void Dialog::Close()
|
||||
close = true;
|
||||
dirty = true;
|
||||
pendingCleanup = true; // 只标记需要清理,不立即执行
|
||||
|
||||
|
||||
// 工厂模式下非模态触发回调 返回结果
|
||||
if (resultCallback&& !modal)
|
||||
if (resultCallback && !modal)
|
||||
resultCallback(this->result);
|
||||
|
||||
|
||||
}
|
||||
|
||||
void Dialog::setInitialization(bool init)
|
||||
@@ -231,10 +257,10 @@ void Dialog::setInitialization(bool init)
|
||||
{
|
||||
initDialogSize();
|
||||
saveBackground((x - BorderWidth), (y - BorderWidth), (width + 2 * BorderWidth), (height + 2 * BorderWidth));
|
||||
this->dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Dialog::initButtons()
|
||||
{
|
||||
controls.clear();
|
||||
@@ -246,48 +272,49 @@ void Dialog::initButtons()
|
||||
auto okbutton = createDialogButton((this->x + (this->width - (functionButtonWidth * buttonNum + buttonMargin * (buttonNum - 1))) / 2),
|
||||
((this->y + (this->height - buttonAreaHeight)) + (buttonAreaHeight - functionButtonHeight) / 2),
|
||||
"确定"
|
||||
);
|
||||
);
|
||||
okbutton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::OK);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
|
||||
okbutton->textStyle = this->textStyle;
|
||||
|
||||
|
||||
this->addControl(std::move(okbutton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case StellarX::MessageBoxType::OKCancel: // 确定和取消按钮
|
||||
{
|
||||
auto okButton = createDialogButton(
|
||||
(this->x + (this->width - (functionButtonWidth * buttonNum + buttonMargin * (buttonNum - 1))) / 2),
|
||||
((this->y + (this->height - buttonAreaHeight)) + (buttonAreaHeight - functionButtonHeight) / 2),
|
||||
"确定"
|
||||
);
|
||||
((this->y + (this->height - buttonAreaHeight)) + (buttonAreaHeight - functionButtonHeight) / 2),
|
||||
"确定"
|
||||
);
|
||||
okButton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::OK);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
auto cancelButton = createDialogButton(
|
||||
(okButton.get()->getX() + okButton.get()->getButtonWidth() + buttonMargin),
|
||||
okButton.get()->getY(),
|
||||
(okButton.get()->getX() + okButton.get()->getWidth() + buttonMargin),
|
||||
okButton.get()->getY(),
|
||||
"取消"
|
||||
);
|
||||
cancelButton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Cancel);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
|
||||
this->Close(); });
|
||||
|
||||
okButton->textStyle = this->textStyle;
|
||||
cancelButton->textStyle = this->textStyle;
|
||||
|
||||
this->addControl(std::move(okButton));
|
||||
this->addControl(std::move(cancelButton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case StellarX::MessageBoxType::YesNo: // 是和否按钮
|
||||
{
|
||||
auto yesButton = createDialogButton(
|
||||
@@ -299,10 +326,10 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Yes);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
auto noButton = createDialogButton(
|
||||
(yesButton.get()->getX() + yesButton.get()->getButtonWidth() + buttonMargin),
|
||||
(yesButton.get()->getX() + yesButton.get()->getWidth() + buttonMargin),
|
||||
yesButton.get()->getY(),
|
||||
"否"
|
||||
);
|
||||
@@ -310,7 +337,7 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::No);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
yesButton->textStyle = this->textStyle;
|
||||
noButton->textStyle = this->textStyle;
|
||||
@@ -318,7 +345,7 @@ void Dialog::initButtons()
|
||||
this->addControl(std::move(yesButton));
|
||||
this->addControl(std::move(noButton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case StellarX::MessageBoxType::YesNoCancel: // 是、否和取消按钮
|
||||
{
|
||||
auto yesButton = createDialogButton(
|
||||
@@ -330,21 +357,21 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Yes);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
auto noButton = createDialogButton(
|
||||
yesButton.get()->getX() + yesButton.get()->getButtonWidth() + buttonMargin,
|
||||
yesButton.get()->getY(),
|
||||
yesButton.get()->getX() + yesButton.get()->getWidth() + buttonMargin,
|
||||
yesButton.get()->getY(),
|
||||
"否"
|
||||
);
|
||||
noButton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::No);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
auto cancelButton = createDialogButton(
|
||||
noButton.get()->getX() + noButton.get()->getButtonWidth() + buttonMargin,
|
||||
noButton.get()->getX() + noButton.get()->getWidth() + buttonMargin,
|
||||
noButton.get()->getY(),
|
||||
"取消"
|
||||
);
|
||||
@@ -352,18 +379,17 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Cancel);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
yesButton->textStyle = this->textStyle;
|
||||
noButton->textStyle = this->textStyle;
|
||||
cancelButton->textStyle = this->textStyle;
|
||||
|
||||
|
||||
this->addControl(std::move(yesButton));
|
||||
this->addControl(std::move(noButton));
|
||||
this->addControl(std::move(cancelButton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case StellarX::MessageBoxType::RetryCancel: // 重试和取消按钮
|
||||
{
|
||||
auto retryButton = createDialogButton(
|
||||
@@ -375,18 +401,18 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Retry);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
|
||||
this->Close(); });
|
||||
|
||||
auto cancelButton = createDialogButton(
|
||||
retryButton.get()->getX() + retryButton.get()->getButtonWidth() + buttonMargin,
|
||||
retryButton.get()->getY(),
|
||||
retryButton.get()->getX() + retryButton.get()->getWidth() + buttonMargin,
|
||||
retryButton.get()->getY(),
|
||||
"取消"
|
||||
);
|
||||
cancelButton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Cancel);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
this->Close(); });
|
||||
|
||||
retryButton->textStyle = this->textStyle;
|
||||
cancelButton->textStyle = this->textStyle;
|
||||
@@ -394,11 +420,11 @@ void Dialog::initButtons()
|
||||
this->addControl(std::move(retryButton));
|
||||
this->addControl(std::move(cancelButton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case StellarX::MessageBoxType::AbortRetryIgnore: // 中止、重试和忽略按钮
|
||||
{
|
||||
auto abortButton = createDialogButton(
|
||||
(this->x + (this->width - (functionButtonWidth * buttonNum + buttonMargin* (buttonNum-1))) / 2),
|
||||
(this->x + (this->width - (functionButtonWidth * buttonNum + buttonMargin * (buttonNum - 1))) / 2),
|
||||
((this->y + (this->height - buttonAreaHeight)) + (buttonAreaHeight - functionButtonHeight) / 2),
|
||||
"中止"
|
||||
);
|
||||
@@ -406,21 +432,21 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Abort);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close();
|
||||
this->Close();
|
||||
});
|
||||
auto retryButton = createDialogButton(
|
||||
abortButton.get()->getX() + abortButton.get()->getButtonWidth() + buttonMargin,
|
||||
abortButton.get()->getY(),
|
||||
abortButton.get()->getX() + abortButton.get()->getWidth() + buttonMargin,
|
||||
abortButton.get()->getY(),
|
||||
"重试"
|
||||
);
|
||||
retryButton->setOnClickListener([this]()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Retry);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close();
|
||||
this->Close();
|
||||
});
|
||||
auto ignoreButton = createDialogButton(
|
||||
retryButton.get()->getX() + retryButton.get()->getButtonWidth() + buttonMargin,
|
||||
retryButton.get()->getX() + retryButton.get()->getWidth() + buttonMargin,
|
||||
retryButton.get()->getY(),
|
||||
"忽略"
|
||||
);
|
||||
@@ -428,7 +454,7 @@ void Dialog::initButtons()
|
||||
{
|
||||
this->SetResult(StellarX::MessageBoxResult::Ignore);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close();
|
||||
this->Close();
|
||||
});
|
||||
|
||||
abortButton->textStyle = this->textStyle;
|
||||
@@ -439,7 +465,7 @@ void Dialog::initButtons()
|
||||
this->addControl(std::move(retryButton));
|
||||
this->addControl(std::move(ignoreButton));
|
||||
}
|
||||
break;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,7 +474,7 @@ void Dialog::initCloseButton()
|
||||
//初始化关闭按钮
|
||||
auto but = std::make_unique<Button>
|
||||
(
|
||||
(this->x + this->width - closeButtonWidth) - 3, (this->y+3), closeButtonWidth-1, closeButtonHeight,
|
||||
(this->x + this->width - closeButtonWidth) - 3, (this->y + 3), closeButtonWidth - 1, closeButtonHeight,
|
||||
"X", // 按钮文本
|
||||
RGB(255, 0, 0), // 按钮被点击颜色
|
||||
this->canvasBkClor, // 按钮背景颜色
|
||||
@@ -462,14 +488,14 @@ void Dialog::initCloseButton()
|
||||
this->SetResult(StellarX::MessageBoxResult::Cancel);
|
||||
this->hWnd.dialogClose = true;
|
||||
this->Close(); });
|
||||
|
||||
|
||||
this->closeButton = but.get();
|
||||
this->addControl(std::move(but));
|
||||
}
|
||||
|
||||
void Dialog::initTitle()
|
||||
{
|
||||
this->title = std::make_unique<Label>(this->x+5,this->y+5,titleText,textStyle.color);
|
||||
this->title = std::make_unique<Label>(this->x + 5, this->y + 5, titleText, textStyle.color);
|
||||
title->setTextdisap(true);
|
||||
title->textStyle = this->textStyle;
|
||||
|
||||
@@ -483,13 +509,13 @@ void Dialog::splitMessageLines()
|
||||
std::string currentLine;
|
||||
for (size_t i = 0; i < message.length(); i++) {
|
||||
// 处理 换行符 \r\n \n \r
|
||||
if (i + 1 < message.length() && (message[i] == '\r' || message[i] == '\n')||(message[i] == '\r' && message[i+1] == '\n'))
|
||||
if (i + 1 < message.length() && (message[i] == '\r' || message[i] == '\n') || (message[i] == '\r' && message[i + 1] == '\n'))
|
||||
{
|
||||
if (!currentLine.empty()) {
|
||||
lines.push_back(currentLine);
|
||||
currentLine.clear();
|
||||
}
|
||||
|
||||
|
||||
if (message[i] == '\r' && message[i + 1] == '\n')
|
||||
i++;
|
||||
continue;
|
||||
@@ -499,13 +525,13 @@ void Dialog::splitMessageLines()
|
||||
}
|
||||
|
||||
// 添加最后一行(如果有内容)
|
||||
if (!currentLine.empty())
|
||||
if (!currentLine.empty())
|
||||
{
|
||||
lines.push_back(currentLine);
|
||||
}
|
||||
|
||||
// 如果消息为空,至少添加一个空行
|
||||
if (lines.empty())
|
||||
if (lines.empty())
|
||||
{
|
||||
lines.push_back("");
|
||||
}
|
||||
@@ -517,7 +543,9 @@ void Dialog::getTextSize()
|
||||
settextstyle(textStyle.nHeight, textStyle.nWidth, textStyle.lpszFace,
|
||||
textStyle.nEscapement, textStyle.nOrientation, textStyle.nWeight,
|
||||
textStyle.bItalic, textStyle.bUnderline, textStyle.bStrikeOut);
|
||||
for (auto text : lines)
|
||||
int tempHeight = 0;
|
||||
int tempWidth = 0;
|
||||
for (auto& text : lines)
|
||||
{
|
||||
int w = textwidth(LPCTSTR(text.c_str()));
|
||||
int h = textheight(LPCTSTR(text.c_str()));
|
||||
@@ -526,6 +554,7 @@ void Dialog::getTextSize()
|
||||
if (this->textWidth < w)
|
||||
this->textWidth = w;
|
||||
}
|
||||
|
||||
restoreStyle();
|
||||
}
|
||||
// 计算逻辑:对话框宽度取【文本区域最大宽度】和【按钮区域总宽度】中的较大值。
|
||||
@@ -554,10 +583,10 @@ void Dialog::initDialogSize()
|
||||
|
||||
// 计算按钮区域宽度
|
||||
int buttonAreaWidth = buttonNum * functionButtonWidth +
|
||||
(buttonNum > 0 ? (buttonNum +1) * buttonMargin : 0);
|
||||
(buttonNum > 0 ? (buttonNum + 1) * buttonMargin : 0);
|
||||
|
||||
// 计算文本区域宽度(包括边距)
|
||||
int textAreaWidth = textWidth + textToBorderMargin * 2 ;
|
||||
int textAreaWidth = textWidth + textToBorderMargin * 2;
|
||||
|
||||
// 对话框宽度取两者中的较大值,并确保最小宽度
|
||||
this->width = buttonAreaWidth > textAreaWidth ? buttonAreaWidth : textAreaWidth;
|
||||
@@ -565,7 +594,7 @@ void Dialog::initDialogSize()
|
||||
|
||||
// 计算对话框高度
|
||||
// 高度 = 标题栏高度 + 文本区域高度 + 按钮区域高度 + 间距
|
||||
int textAreaHeight = textHeight * (int)lines.size() + 5*((int)lines.size()-1); // 文本行高+行间距
|
||||
int textAreaHeight = textHeight * (int)lines.size() + 5 * ((int)lines.size() - 1); // 文本行高+行间距
|
||||
this->height = closeButtonHeight + // 标题栏高度
|
||||
titleToTextMargin + // 标题到文本的间距
|
||||
textAreaHeight + // 文本区域高度
|
||||
@@ -583,30 +612,11 @@ void Dialog::initDialogSize()
|
||||
initCloseButton(); // 初始化关闭按钮
|
||||
}
|
||||
|
||||
void Dialog::saveBackground(int x, int y, int w, int h)
|
||||
void Dialog::addControl(std::unique_ptr<Control> control)
|
||||
{
|
||||
if (w <= 0 || h <= 0) return;
|
||||
saveBkX = x; saveBkY = y; saveWidth = w; saveHeight = h;
|
||||
if (saveBkImage)
|
||||
{
|
||||
//尺寸变了才重建,避免反复 new/delete
|
||||
if (saveBkImage->getwidth() != w || saveBkImage->getheight() != h)
|
||||
{
|
||||
delete saveBkImage; saveBkImage = nullptr;
|
||||
}
|
||||
}
|
||||
if (!saveBkImage) saveBkImage = new IMAGE(w + BorderWidth*2, h + BorderWidth*2);
|
||||
|
||||
SetWorkingImage(nullptr); // ★抓屏幕
|
||||
getimage(saveBkImage, x - BorderWidth, y - BorderWidth, w + BorderWidth*2, h+ BorderWidth*2);
|
||||
hasSnap = true;
|
||||
}
|
||||
void Dialog::restBackground()
|
||||
{
|
||||
if (!hasSnap || !saveBkImage) return;
|
||||
// 直接回贴屏幕(与抓取一致)
|
||||
SetWorkingImage(nullptr);
|
||||
putimage(saveBkX - BorderWidth, saveBkY - BorderWidth,saveBkImage);
|
||||
control->setParent(this);
|
||||
controls.push_back(std::move(control));
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
// 延迟清理策略:由于对话框绘制时保存了背景快照,必须在对话框隐藏后、
|
||||
@@ -621,7 +631,7 @@ void Dialog::performDelayedCleanup()
|
||||
auto& c = hWnd.getControls();
|
||||
for (auto& control : c)
|
||||
control->setDirty(true);
|
||||
|
||||
|
||||
controls.clear();
|
||||
|
||||
// 重置指针
|
||||
@@ -634,6 +644,22 @@ void Dialog::performDelayedCleanup()
|
||||
FlushBatchDraw();
|
||||
discardBackground();
|
||||
}
|
||||
if (!(saveBkImage && hasSnap))
|
||||
{
|
||||
// 没有背景快照:强制一次完整重绘,立即擦掉残影
|
||||
hWnd.pumpResizeIfNeeded(); // 如果正好有尺寸标志,顺便统一收口
|
||||
// 即使没有尺寸变化,也重绘一帧
|
||||
BeginBatchDraw();
|
||||
// 背景
|
||||
if (hWnd.getBkImage() && !hWnd.getBkImageFile().empty())
|
||||
putimage(0, 0, hWnd.getBkImage());
|
||||
else { setbkcolor(hWnd.getBkcolor()); cleardevice(); }
|
||||
// 所有普通控件
|
||||
for (auto& c : hWnd.getControls()) c->draw();
|
||||
// 其他对话框(this 已经 show=false,会早退不绘)
|
||||
EndBatchDraw();
|
||||
FlushBatchDraw();
|
||||
}
|
||||
// 重置状态
|
||||
needsInitialization = true;
|
||||
pendingCleanup = false;
|
||||
@@ -675,7 +701,7 @@ std::unique_ptr<Button> Dialog::createDialogButton(int x, int y, const std::stri
|
||||
StellarX::ButtonMode::NORMAL,
|
||||
StellarX::ControlShape::RECTANGLE
|
||||
);
|
||||
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
@@ -684,13 +710,9 @@ void Dialog::requestRepaint(Control* parent)
|
||||
if (this == parent)
|
||||
{
|
||||
for (auto& control : controls)
|
||||
if (control->isDirty()&&control->IsVisible())
|
||||
{
|
||||
if (control->isDirty() && control->IsVisible())
|
||||
control->draw();
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
onRequestRepaintAsRoot();
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -1,27 +1,32 @@
|
||||
#include "MessageBox.h"
|
||||
|
||||
#include "SxLog.h"
|
||||
namespace StellarX
|
||||
{
|
||||
MessageBoxResult MessageBox::showModal(Window& wnd,const std::string& text,const std::string& caption,
|
||||
MessageBoxResult MessageBox::showModal(Window& wnd, const std::string& text, const std::string& caption,
|
||||
MessageBoxType type)
|
||||
{
|
||||
Dialog dlg(wnd, caption, text, type, true); // 模态
|
||||
SX_LOGI("MessageBox") << "show: Message=" << dlg.GetText()
|
||||
<< " modal=" << (dlg.model() ? 1 : 0);
|
||||
|
||||
dlg.setInitialization(true);
|
||||
dlg.Show();
|
||||
return dlg.GetResult();
|
||||
}
|
||||
|
||||
void MessageBox::showAsync(Window& wnd,const std::string& text,const std::string& caption,MessageBoxType type,
|
||||
void MessageBox::showAsync(Window& wnd, const std::string& text, const std::string& caption, MessageBoxType type,
|
||||
std::function<void(MessageBoxResult)> onResult)
|
||||
{
|
||||
//去重,如果窗口内已有相同的对话框被触发,则不再创建
|
||||
if (wnd.hasNonModalDialogWithCaption(caption, text))
|
||||
{
|
||||
std::cout << "\a" << std::endl;
|
||||
std::cout << "\a" << std::endl;
|
||||
return;
|
||||
}
|
||||
auto dlg = std::make_unique<Dialog>(wnd, caption, text,
|
||||
type, false); // 非模态
|
||||
SX_LOGI("MessageBox") << "show: Message=" << dlg->GetText()
|
||||
<< " modal=" << (dlg->model() ? 1 : 0);
|
||||
Dialog* dlgPtr = dlg.get();
|
||||
dlgPtr->setInitialization(true);
|
||||
// 设置回调
|
||||
@@ -31,4 +36,4 @@ namespace StellarX
|
||||
wnd.addDialog(std::move(dlg));
|
||||
dlgPtr->Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
+443
@@ -0,0 +1,443 @@
|
||||
#include "SxLog.h"
|
||||
#include <cstdlib>
|
||||
#include <clocale>
|
||||
|
||||
/********************************************************************************
|
||||
* @文件: SxLog.cpp
|
||||
* @摘要: StellarX 日志系统实现(过滤/格式化/输出/文件滚动/RAII提交/作用域计时)
|
||||
* @描述:
|
||||
* 该实现文件主要包含 4 个关键点:
|
||||
* 1) FileSink: 文件打开、写入、flush 与按阈值滚动
|
||||
* 2) SxLogger: shouldLog 过滤、formatPrefix 前缀拼接、logLine 统一输出出口
|
||||
* 3) SxLogLine: 析构提交(RAII)确保“一条语句输出一整行”
|
||||
* 4) SxLogScope: 按需启用计时,析构输出耗时
|
||||
*
|
||||
* @实现难点提示:
|
||||
* - shouldLog 必须“零副作用”,否则宏短路会带来不可预测行为
|
||||
* - logLine 是统一出口,必须保证行级一致性,且避免在持锁状态下递归打日志
|
||||
* - 文件滚动要处理文件名安全性与跨平台 rename 行为差异
|
||||
* - 时间戳生成需要兼容 Windows 与 POSIX(localtime_s/localtime_r)
|
||||
********************************************************************************/
|
||||
|
||||
namespace StellarX
|
||||
{
|
||||
// -------- FileSink --------
|
||||
|
||||
// 打开文件输出
|
||||
// 难点:
|
||||
// - 需要支持追加与清空两种模式
|
||||
// - open 前先 close,避免重复打开导致句柄泄漏
|
||||
bool FileSink::open(const std::string& path, bool append)
|
||||
{
|
||||
close();
|
||||
filePath = path;
|
||||
appendMode = append;
|
||||
|
||||
std::ios::openmode mode = std::ios::out;
|
||||
mode |= (append ? std::ios::app : std::ios::trunc);
|
||||
|
||||
ofs.open(path.c_str(), mode);
|
||||
return ofs.is_open();
|
||||
}
|
||||
|
||||
// 关闭文件输出(可重复调用)
|
||||
void FileSink::close()
|
||||
{
|
||||
if (ofs.is_open()) ofs.close();
|
||||
}
|
||||
|
||||
// 查询是否已打开
|
||||
bool FileSink::isOpen() const
|
||||
{
|
||||
return ofs.is_open();
|
||||
}
|
||||
|
||||
// 写入一整行
|
||||
// 难点:
|
||||
// - 写入后若启用 rotateBytes,需要及时检测文件大小是否到阈值
|
||||
void FileSink::writeLine(const std::string& line)
|
||||
{
|
||||
if (!ofs.is_open()) return;
|
||||
ofs << line;
|
||||
if (rotateBytes > 0) rotateIfNeeded();
|
||||
}
|
||||
|
||||
// flush 文件缓冲
|
||||
void FileSink::flush()
|
||||
{
|
||||
if (ofs.is_open()) ofs.flush();
|
||||
}
|
||||
|
||||
// 滚动文件
|
||||
// 难点:
|
||||
// 1) tellp() 返回的是当前写指针位置,通常可近似视为文件大小
|
||||
// 2) 时间戳用于文件名时需要做字符清洗,避免出现不友好字符
|
||||
// 3) rename 行为与权限/占用有关,失败时需要保证不崩溃(此处选择“尽力而为”)
|
||||
bool FileSink::rotateIfNeeded()
|
||||
{
|
||||
if (!ofs.is_open() || rotateBytes == 0) return false;
|
||||
|
||||
const std::streampos pos = ofs.tellp();
|
||||
if (pos < 0) return false;
|
||||
|
||||
const std::size_t size = static_cast<std::size_t>(pos);
|
||||
if (size < rotateBytes) return false;
|
||||
|
||||
ofs.flush();
|
||||
ofs.close();
|
||||
|
||||
// xxx.log -> xxx.log.YYYYmmdd_HHMMSS
|
||||
// 说明:
|
||||
// - makeTimestampLocal 形如 "2026-01-09 12:34:56"
|
||||
// - 文件名中把 '-' ' ' ':' 替换为 '_',只保留数字与 '_',降低环境差异
|
||||
const std::string ts = SxLogger::makeTimestampLocal();
|
||||
std::string safeTs;
|
||||
safeTs.reserve(ts.size());
|
||||
for (char ch : ts)
|
||||
{
|
||||
if (ch >= '0' && ch <= '9') safeTs.push_back(ch);
|
||||
else if (ch == '-' || ch == ' ' || ch == ':') safeTs.push_back('_');
|
||||
}
|
||||
if (safeTs.empty()) safeTs = "rotated";
|
||||
|
||||
const std::string rotated = filePath + "." + safeTs;
|
||||
std::rename(filePath.c_str(), rotated.c_str());
|
||||
|
||||
// 重新打开新文件
|
||||
// 注意: 这里用 append=false,确保新文件从空开始
|
||||
return open(filePath, false);
|
||||
}
|
||||
|
||||
// -------- SxLogger --------
|
||||
|
||||
|
||||
|
||||
// 设置 Windows 控制台 codepage(只执行一次)
|
||||
// 难点:
|
||||
// - 只影响终端解释输出字节的方式,不影响源码文件编码
|
||||
// - 使用 once_flag 避免重复 system 调用造成噪声与性能浪费
|
||||
//
|
||||
void SxLogger::setGBK()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
static std::once_flag once;
|
||||
std::call_once(once, []() {
|
||||
// 切到chcp 936(GBK),避免中文日志在 CP936 控制台下乱码
|
||||
// 说明:这不是 WinAPI;是执行系统命令
|
||||
std::system("chcp 936 >nul");
|
||||
|
||||
// 补充说明:
|
||||
// - chcp 936 实际是设置为 CP936(GBK)
|
||||
// - 如果你的终端本身是 UTF-8 环境,调用它可能反而改变显示行为
|
||||
// - 该函数建议只在“明确需要 GBK 控制台输出”的场景调用
|
||||
|
||||
// 尝试让 C/C++ 运行库按 UTF-8 工作(对部分流输出有帮助)
|
||||
// std::setlocale(LC_ALL, ".UTF8");
|
||||
});
|
||||
#endif
|
||||
}
|
||||
|
||||
// 获取单例
|
||||
// 难点:
|
||||
// - 作为全局入口,初始化必须线程安全
|
||||
// - C++11 起函数内静态对象初始化由标准保证线程安全
|
||||
SxLogger& SxLogger::Get()
|
||||
{
|
||||
static SxLogger inst;
|
||||
return inst;
|
||||
}
|
||||
|
||||
// 构造:设置默认语言
|
||||
SxLogger::SxLogger()
|
||||
: lang(SxLogLanguage::ZhCN)
|
||||
{
|
||||
}
|
||||
|
||||
// 设置最低输出级别
|
||||
void SxLogger::setMinLevel(SxLogLevel level)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
cfg.minLevel = level;
|
||||
}
|
||||
|
||||
// 获取最低输出级别
|
||||
SxLogLevel SxLogger::getMinLevel() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
return cfg.minLevel;
|
||||
}
|
||||
|
||||
// 设置语言
|
||||
// 难点:
|
||||
// - 语言只影响 SX_T 的字符串选择
|
||||
// - 这里用 atomic relaxed,避免频繁加锁
|
||||
void SxLogger::setLanguage(SxLogLanguage l)
|
||||
{
|
||||
lang.store(l, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// 获取语言
|
||||
SxLogLanguage SxLogger::getLanguage() const
|
||||
{
|
||||
return lang.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// 设置 Tag 过滤
|
||||
// 难点:
|
||||
// - 当前实现是 vector<string> 线性匹配,适合 tag 数量不大
|
||||
// - 若未来 tag 很多,可考虑 unordered_set 优化(但会增加依赖与复杂度)
|
||||
void SxLogger::setTagFilter(SxTagFilterMode mode, const std::vector<std::string>& tags)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
cfg.tagFilterMode = mode;
|
||||
cfg.tagList = tags;
|
||||
}
|
||||
|
||||
// 清空 Tag 过滤
|
||||
void SxLogger::clearTagFilter()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
cfg.tagFilterMode = SxTagFilterMode::None;
|
||||
cfg.tagList.clear();
|
||||
}
|
||||
|
||||
// 开关控制台输出
|
||||
// 难点:
|
||||
// - ConsoleSink 持有 ostream 引用,不管理其生命周期
|
||||
void SxLogger::enableConsole(bool enable)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
if (enable)
|
||||
{
|
||||
if (!consoleSink) consoleSink.reset(new ConsoleSink(std::cout));
|
||||
}
|
||||
else
|
||||
{
|
||||
consoleSink.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// 开启文件输出
|
||||
// 难点:
|
||||
// - enableFile 成功与否决定 cfg.fileEnabled
|
||||
// - 需要把 rotateBytes 同步到 FileSink
|
||||
bool SxLogger::enableFile(const std::string& path, bool append, std::size_t rotateBytes_)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
|
||||
if (!fileSink) fileSink.reset(new FileSink());
|
||||
fileSink->setRotateBytes(rotateBytes_);
|
||||
|
||||
const bool ok = fileSink->open(path, append);
|
||||
cfg.fileEnabled = ok;
|
||||
cfg.filePath = path;
|
||||
cfg.fileAppend = append;
|
||||
cfg.rotateBytes = rotateBytes_;
|
||||
return ok;
|
||||
}
|
||||
|
||||
// 关闭文件输出
|
||||
void SxLogger::disableFile()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
if (fileSink) fileSink->close();
|
||||
cfg.fileEnabled = false;
|
||||
}
|
||||
|
||||
// 获取配置副本
|
||||
// 难点:
|
||||
// - 返回副本避免外部拿到内部引用后绕过锁修改
|
||||
SxLogConfig SxLogger::getConfigCopy() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
// 设置配置(整体替换)
|
||||
void SxLogger::setConfig(const SxLogConfig& c)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
cfg = c;
|
||||
}
|
||||
|
||||
// 级别转字符串
|
||||
const char* SxLogger::levelToString(SxLogLevel level)
|
||||
{
|
||||
switch (level)
|
||||
{
|
||||
case SxLogLevel::Trace: return "TRACE";
|
||||
case SxLogLevel::Debug: return "DEBUG";
|
||||
case SxLogLevel::Info: return "INFO ";
|
||||
case SxLogLevel::Warn: return "WARN ";
|
||||
case SxLogLevel::Error: return "ERROR";
|
||||
case SxLogLevel::Fatal: return "FATAL";
|
||||
default: return "OFF ";
|
||||
}
|
||||
}
|
||||
|
||||
// 判断 tag 是否允许输出
|
||||
// 难点:
|
||||
// - 精确匹配 tag 字符串
|
||||
// - tag==nullptr 时默认允许,避免“无 tag 日志被误杀”
|
||||
bool SxLogger::tagAllowed(const SxLogConfig& c, const char* tag)
|
||||
{
|
||||
if (c.tagFilterMode == SxTagFilterMode::None) return true;
|
||||
if (!tag) return true;
|
||||
|
||||
bool found = false;
|
||||
for (const auto& t : c.tagList)
|
||||
{
|
||||
if (t == tag) { found = true; break; }
|
||||
}
|
||||
|
||||
if (c.tagFilterMode == SxTagFilterMode::Whitelist) return found;
|
||||
if (c.tagFilterMode == SxTagFilterMode::Blacklist) return !found;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 快速判定是否需要输出(宏短路依赖)
|
||||
// 难点:
|
||||
// 1) 必须无副作用:返回 false 时调用端不会构造对象也不会拼接
|
||||
// 2) 过滤维度要完整:级别、tag、sink 是否启用
|
||||
// 3) 当前实现加锁保证 cfg 与 sink 状态一致;代价是高频路径会有锁开销
|
||||
bool SxLogger::shouldLog(SxLogLevel level, const char* tag) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
if (cfg.minLevel == SxLogLevel::Off) return false;
|
||||
if (level < cfg.minLevel) return false;
|
||||
if (!tagAllowed(cfg, tag)) return false;
|
||||
if (!consoleSink && !cfg.fileEnabled) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 生成本地时间戳字符串
|
||||
// 难点:
|
||||
// - Windows 与 POSIX 的线程安全 localtime API 不同
|
||||
std::string SxLogger::makeTimestampLocal()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const std::time_t t = system_clock::to_time_t(now);
|
||||
|
||||
std::tm tmv{};
|
||||
#if defined(_WIN32)
|
||||
localtime_s(&tmv, &t);
|
||||
#else
|
||||
localtime_r(&t, &tmv);
|
||||
#endif
|
||||
std::ostringstream oss;
|
||||
oss << std::put_time(&tmv, "%Y-%m-%d %H:%M:%S");
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
// 拼接日志前缀(调用方已持锁)
|
||||
// 难点:
|
||||
// - 前缀拼接必须与配置项严格对应,且尽量避免多余开销
|
||||
// - showSource 会输出 (file:line func),对定位时序问题很有价值
|
||||
std::string SxLogger::formatPrefixUnlocked(
|
||||
const SxLogConfig& c,
|
||||
SxLogLevel level,
|
||||
const char* tag,
|
||||
const char* file,
|
||||
int line,
|
||||
const char* func) const
|
||||
{
|
||||
std::ostringstream oss;
|
||||
|
||||
if (c.showTimestamp) oss << "[" << makeTimestampLocal() << "] ";
|
||||
if (c.showLevel) oss << "[" << levelToString(level) << "] ";
|
||||
if (c.showTag && tag) oss << "[" << tag << "] ";
|
||||
|
||||
if (c.showThreadId)
|
||||
{
|
||||
oss << "[T:" << std::this_thread::get_id() << "] ";
|
||||
}
|
||||
|
||||
if (c.showSource && file && func)
|
||||
{
|
||||
oss << "(" << file << ":" << line << " " << func << ") ";
|
||||
}
|
||||
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
// 统一输出出口
|
||||
// 难点:
|
||||
// 1) 行级一致性:必须把 prefix + msg + "\n" 当作整体写入
|
||||
// 2) 线程安全:持锁写入可避免不同线程日志互相穿插
|
||||
// 3) 避免重入:在持锁期间不要再调用 SX_LOG...(会导致死锁)
|
||||
void SxLogger::logLine(
|
||||
SxLogLevel level,
|
||||
const char* tag,
|
||||
const char* file,
|
||||
int line,
|
||||
const char* func,
|
||||
const std::string& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
|
||||
if (cfg.minLevel == SxLogLevel::Off) return;
|
||||
if (level < cfg.minLevel) return;
|
||||
if (!tagAllowed(cfg, tag)) return;
|
||||
|
||||
const std::string prefix = formatPrefixUnlocked(cfg, level, tag, file, line, func);
|
||||
const std::string lineText = prefix + msg + "\n";
|
||||
|
||||
if (consoleSink) consoleSink->writeLine(lineText);
|
||||
|
||||
if (cfg.fileEnabled && fileSink && fileSink->isOpen())
|
||||
{
|
||||
fileSink->writeLine(lineText);
|
||||
}
|
||||
|
||||
if (cfg.autoFlush)
|
||||
{
|
||||
if (consoleSink) consoleSink->flush();
|
||||
if (cfg.fileEnabled && fileSink) fileSink->flush();
|
||||
}
|
||||
}
|
||||
|
||||
// -------- SxLogLine --------
|
||||
|
||||
// 构造:只记录元信息
|
||||
SxLogLine::SxLogLine(SxLogLevel level, const char* tag, const char* file, int line, const char* func)
|
||||
: lvl(level), tg(tag), srcFile(file), srcLine(line), srcFunc(func)
|
||||
{
|
||||
}
|
||||
|
||||
// 析构:提交输出
|
||||
// 难点:
|
||||
// - 这是 RAII 设计的核心:保证语句结束时日志自动落地
|
||||
// - 也要求调用端不要把临时对象跨语句保存(宏用法本身也不支持那样做)
|
||||
SxLogLine::~SxLogLine()
|
||||
{
|
||||
SxLogger::Get().logLine(lvl, tg, srcFile, srcLine, srcFunc, ss.str());
|
||||
}
|
||||
|
||||
// -------- SxLogScope --------
|
||||
|
||||
// 构造:按需启用计时
|
||||
// 难点:
|
||||
// - 只有 shouldLog 为 true 才记录起点,避免在未输出场景做无意义计时
|
||||
SxLogScope::SxLogScope(SxLogLevel level, const char* tag, const char* file, int line, const char* func, const char* name)
|
||||
: lvl(level), tg(tag), srcFile(file), srcLine(line), srcFunc(func), scopeName(name)
|
||||
{
|
||||
enabled = SxLogger::Get().shouldLog(lvl, tg);
|
||||
if (enabled) t0 = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
// 析构:输出耗时
|
||||
// 难点:
|
||||
// - steady_clock 用于衡量耗时,避免系统时间调整造成跳变
|
||||
SxLogScope::~SxLogScope()
|
||||
{
|
||||
if (!enabled) return;
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
|
||||
|
||||
std::ostringstream oss;
|
||||
oss << "SCOPE " << (scopeName ? scopeName : "") << " cost=" << us << "us";
|
||||
SxLogger::Get().logLine(lvl, tg, srcFile, srcLine, srcFunc, oss.str());
|
||||
}
|
||||
|
||||
} // namespace StellarX
|
||||
+108
-61
@@ -1,5 +1,5 @@
|
||||
#include "TabControl.h"
|
||||
|
||||
#include "SxLog.h"
|
||||
inline void TabControl::initTabBar()
|
||||
{
|
||||
if (controls.empty())return;
|
||||
@@ -33,7 +33,7 @@ inline void TabControl::initTabBar()
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->setX(this->x + i * butW);
|
||||
c.first->setY(this->y+this->height - tabBarHeight);
|
||||
c.first->setY(this->y + this->height - tabBarHeight);
|
||||
i++;
|
||||
}
|
||||
break;
|
||||
@@ -41,18 +41,18 @@ inline void TabControl::initTabBar()
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->setX(this->x);
|
||||
c.first->setY(this->y+i* butH);
|
||||
c.first->setY(this->y + i * butH);
|
||||
i++;
|
||||
}
|
||||
break;
|
||||
case StellarX::TabPlacement::Right:
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->setX(this->x+this->width - tabBarHeight);
|
||||
c.first->setX(this->x + this->width - tabBarHeight);
|
||||
c.first->setY(this->y + i * butH);
|
||||
i++;
|
||||
}
|
||||
break;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -147,7 +147,7 @@ inline void TabControl::initTabPage()
|
||||
}
|
||||
}
|
||||
|
||||
TabControl::TabControl():Canvas()
|
||||
TabControl::TabControl() :Canvas()
|
||||
{
|
||||
this->id = "TabControl";
|
||||
}
|
||||
@@ -162,13 +162,36 @@ TabControl::~TabControl()
|
||||
{
|
||||
}
|
||||
|
||||
void TabControl::setX(int x)
|
||||
{
|
||||
this->x = x;
|
||||
initTabBar();
|
||||
initTabPage();
|
||||
dirty = true;
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->onWindowResize();
|
||||
c.second->onWindowResize();
|
||||
}
|
||||
}
|
||||
|
||||
void TabControl::setY(int y)
|
||||
{
|
||||
this->y = y;
|
||||
initTabBar();
|
||||
initTabPage();
|
||||
dirty = true;
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->onWindowResize();
|
||||
c.second->onWindowResize();
|
||||
}
|
||||
}
|
||||
|
||||
void TabControl::draw()
|
||||
{
|
||||
if (!dirty || !show)return;
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
// 恢复背景(清除旧内容)
|
||||
restBackground();
|
||||
// 绘制画布背景和基本形状及其子画布控件
|
||||
Canvas::draw();
|
||||
for (auto& c : controls)
|
||||
{
|
||||
@@ -176,13 +199,21 @@ void TabControl::draw()
|
||||
c.first->draw();
|
||||
}
|
||||
for (auto& c : controls)
|
||||
if(c.second->IsVisible())
|
||||
{
|
||||
c.second->setDirty(true);
|
||||
c.second->draw();
|
||||
}
|
||||
dirty = false;
|
||||
{
|
||||
c.second->setDirty(true);
|
||||
c.second->draw();
|
||||
}
|
||||
|
||||
// 首次绘制时处理默认激活页签
|
||||
if (IsFirstDraw)
|
||||
{
|
||||
if (defaultActivation >= 0 && defaultActivation < (int)controls.size())
|
||||
controls[defaultActivation].first->setButtonClick(true);
|
||||
else if (defaultActivation >= (int)controls.size())//索引越界则激活最后一个
|
||||
controls[controls.size() - 1].first->setButtonClick(true);
|
||||
IsFirstDraw = false;//避免重复处理
|
||||
}
|
||||
dirty = false;
|
||||
}
|
||||
|
||||
bool TabControl::handleEvent(const ExMessage& msg)
|
||||
@@ -196,7 +227,7 @@ bool TabControl::handleEvent(const ExMessage& msg)
|
||||
break;
|
||||
}
|
||||
for (auto& c : controls)
|
||||
if(c.second->IsVisible())
|
||||
if (c.second->IsVisible())
|
||||
if (c.second->handleEvent(msg))
|
||||
{
|
||||
consume = true;
|
||||
@@ -216,24 +247,39 @@ void TabControl::add(std::pair<std::unique_ptr<Button>, std::unique_ptr<Canvas>>
|
||||
controls[idx].first->setParent(this);
|
||||
controls[idx].first->enableTooltip(true);
|
||||
controls[idx].first->setbuttonMode(StellarX::ButtonMode::TOGGLE);
|
||||
controls[idx].first->setOnToggleOnListener([this,idx]()
|
||||
|
||||
controls[idx].first->setOnToggleOnListener([this, idx]()
|
||||
{
|
||||
controls[idx].second->setIsVisible(true);
|
||||
controls[idx].second->onWindowResize();
|
||||
for (auto& tab : controls)
|
||||
int prevIdx = -1;
|
||||
for (size_t i = 0; i < controls.size(); ++i)
|
||||
{
|
||||
if (tab.first->getButtonText() != controls[idx].first->getButtonText())
|
||||
if (controls[i].second->IsVisible())
|
||||
{
|
||||
tab.first->setButtonClick(false);
|
||||
tab.second->setIsVisible(false);
|
||||
prevIdx = (int)i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
dirty = true;
|
||||
});
|
||||
controls[idx].first->setOnToggleOffListener([this,idx]()
|
||||
{
|
||||
controls[idx].second->setIsVisible(false);
|
||||
for (auto& tab : controls)
|
||||
{
|
||||
if (tab.first->getButtonText() != controls[idx].first->getButtonText() && tab.first->isClicked())
|
||||
tab.first->setButtonClick(false);
|
||||
}
|
||||
|
||||
|
||||
SX_LOGI("Tab") << SX_T("激活选项卡:","activate tab: ") << prevIdx << "->" << (int)idx
|
||||
<< " text=" << controls[idx].first->getButtonText();
|
||||
controls[idx].second->onWindowResize();
|
||||
controls[idx].second->setIsVisible(true);
|
||||
dirty = true;
|
||||
|
||||
|
||||
});
|
||||
controls[idx].first->setOnToggleOffListener([this, idx]()
|
||||
{
|
||||
SX_LOGI("Tab") << SX_T("关闭选项卡:id=","deactivate tab: idx=") << (int)idx
|
||||
<< " text=" << controls[idx].first->getButtonText();
|
||||
|
||||
controls[idx].second->setIsVisible(false);
|
||||
dirty = true;
|
||||
});
|
||||
controls[idx].second->setParent(this);
|
||||
@@ -249,12 +295,11 @@ void TabControl::add(std::string tabText, std::unique_ptr<Control> control)
|
||||
if (tab.first->getButtonText() == tabText)
|
||||
{
|
||||
control->setParent(tab.second.get());
|
||||
control->setIsVisible( tab.second->IsVisible());
|
||||
control->setIsVisible(tab.second->IsVisible());
|
||||
tab.second->addControl(std::move(control));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void TabControl::setTabPlacement(StellarX::TabPlacement placement)
|
||||
@@ -263,7 +308,6 @@ void TabControl::setTabPlacement(StellarX::TabPlacement placement)
|
||||
setDirty(true);
|
||||
initTabBar();
|
||||
initTabPage();
|
||||
|
||||
}
|
||||
|
||||
void TabControl::setTabBarHeight(int height)
|
||||
@@ -277,26 +321,42 @@ void TabControl::setTabBarHeight(int height)
|
||||
void TabControl::setIsVisible(bool visible)
|
||||
{
|
||||
// 先让基类 Canvas 处理自己的回贴/丢快照逻辑
|
||||
Canvas::setIsVisible(visible); // <--- 新增
|
||||
|
||||
this->show = visible;
|
||||
Canvas::setIsVisible(visible);
|
||||
for (auto& tab : controls)
|
||||
{
|
||||
tab.first->setIsVisible(visible);
|
||||
//页也要跟着关/开,否则它们会保留旧的 saveBkImage
|
||||
tab.second->setIsVisible(visible);
|
||||
tab.second->setDirty(true);
|
||||
if(true == visible)
|
||||
{
|
||||
tab.first->setIsVisible(visible);
|
||||
//页也要跟着关/开,否则它们会保留旧的 saveBkImage
|
||||
if (tab.first->isClicked())
|
||||
tab.second->setIsVisible(true);
|
||||
else
|
||||
tab.second->setIsVisible(false);
|
||||
tab.second->setDirty(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
tab.first->setIsVisible(visible);
|
||||
tab.second->setIsVisible(visible);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TabControl::onWindowResize()
|
||||
{
|
||||
// 调用基类的窗口变化处理,丢弃快照并标记脏
|
||||
Control::onWindowResize();
|
||||
// 根据当前 TabControl 的新尺寸重新计算页签栏和页面区域
|
||||
initTabBar();
|
||||
initTabPage();
|
||||
// 转发窗口尺寸变化给所有页签按钮和页面
|
||||
for (auto& c : controls)
|
||||
{
|
||||
c.first->onWindowResize();
|
||||
c.second->onWindowResize();
|
||||
}
|
||||
// 尺寸变化后需要重绘自身
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
int TabControl::getActiveIndex() const
|
||||
@@ -308,25 +368,18 @@ int TabControl::getActiveIndex() const
|
||||
if (c.first->isClicked())
|
||||
return idx;
|
||||
}
|
||||
return idx;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void TabControl::setActiveIndex(int idx)
|
||||
{
|
||||
if (idx < 0 || idx > controls.size() - 1) return;
|
||||
if (controls[idx].first->getButtonMode() == StellarX::ButtonMode::DISABLED)return;
|
||||
if (controls[idx].first->isClicked())
|
||||
{
|
||||
if (controls[idx].second->IsVisible())
|
||||
return;
|
||||
else
|
||||
controls[idx].second->setIsVisible(true);
|
||||
}
|
||||
if (IsFirstDraw)
|
||||
defaultActivation = idx;
|
||||
else
|
||||
{
|
||||
controls[idx].first->setButtonClick(true);
|
||||
if (idx >= 0 && idx < controls.size())
|
||||
controls[idx].first->setButtonClick(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int TabControl::count() const
|
||||
@@ -337,13 +390,13 @@ int TabControl::count() const
|
||||
int TabControl::indexOf(const std::string& tabText) const
|
||||
{
|
||||
int idx = -1;
|
||||
for(auto& c : controls)
|
||||
for (auto& c : controls)
|
||||
{
|
||||
idx++;
|
||||
if (c.first->getButtonText() == tabText)
|
||||
return idx;
|
||||
}
|
||||
|
||||
|
||||
return idx;
|
||||
}
|
||||
|
||||
@@ -364,18 +417,12 @@ void TabControl::requestRepaint(Control* parent)
|
||||
for (auto& control : controls)
|
||||
{
|
||||
if (control.first->isDirty() && control.first->IsVisible())
|
||||
{
|
||||
control.first->draw();
|
||||
break;
|
||||
}
|
||||
else if (control.second->isDirty()&&control.second->IsVisible())
|
||||
{
|
||||
if (control.second->isDirty() && control.second->IsVisible())
|
||||
control.second->draw();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
onRequestRepaintAsRoot();
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -5,7 +5,7 @@ Label::Label()
|
||||
{
|
||||
this->id = "Label";
|
||||
this->text = "默认标签";
|
||||
textStyle.color = RGB(0,0,0);
|
||||
textStyle.color = RGB(0, 0, 0);
|
||||
textBkColor = RGB(255, 255, 255);; //默认白色背景
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ void Label::draw()
|
||||
this->height = textheight(text.c_str());
|
||||
}
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y,this->width,this->height);
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
// 恢复背景(清除旧内容)
|
||||
restBackground();
|
||||
outtextxy(x, y, LPCTSTR(text.c_str()));
|
||||
@@ -71,5 +71,4 @@ void Label::setText(std::string text)
|
||||
{
|
||||
this->text = text;
|
||||
this->dirty = true;
|
||||
|
||||
}
|
||||
}
|
||||
+206
-56
@@ -1,4 +1,5 @@
|
||||
#include "Table.h"
|
||||
#include "SxLog.h"
|
||||
// 绘制表格的当前页
|
||||
// 使用双循环绘制行和列,考虑分页偏移
|
||||
void Table::drawTable()
|
||||
@@ -17,7 +18,7 @@ void Table::drawTable()
|
||||
{
|
||||
for (size_t j = 0; j < data[i].size(); ++j)
|
||||
{
|
||||
uX = dX + colWidths.at(j) + TABLE_COL_GAP;
|
||||
uX = dX + colWidths.at(j) + TABLE_COL_GAP;
|
||||
fillrectangle(dX, dY, uX, uY);
|
||||
outtextxy(dX + TABLE_PAD_X, dY + TABLE_PAD_Y, LPCTSTR(data[i][j].c_str()));
|
||||
dX += colWidths.at(j) + TABLE_COL_GAP;
|
||||
@@ -26,12 +27,10 @@ void Table::drawTable()
|
||||
dY = uY;
|
||||
uY = dY + lineHeights.at(0) + TABLE_ROW_EXTRA;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void Table::drawHeader()
|
||||
{
|
||||
|
||||
const int border = tableBorderWidth > 0 ? tableBorderWidth : 0;
|
||||
// 内容区原点 = x+border, y+border
|
||||
dX = x + border;
|
||||
@@ -61,9 +60,9 @@ void Table::initTextWaH()
|
||||
lineHeights.assign(headers.size(), 0);
|
||||
|
||||
// 先看数据
|
||||
for (size_t i = 0; i < data.size(); ++i)
|
||||
for (size_t i = 0; i < data.size(); ++i)
|
||||
{
|
||||
for (size_t j = 0; j < data[i].size(); ++j)
|
||||
for (size_t j = 0; j < data[i].size(); ++j)
|
||||
{
|
||||
const int w = textwidth(LPCTSTR(data[i][j].c_str()));
|
||||
const int h = textheight(LPCTSTR(data[i][j].c_str()));
|
||||
@@ -72,7 +71,7 @@ void Table::initTextWaH()
|
||||
}
|
||||
}
|
||||
// 再用表头更新(谁大取谁)
|
||||
for (size_t j = 0; j < headers.size(); ++j)
|
||||
for (size_t j = 0; j < headers.size(); ++j)
|
||||
{
|
||||
const int w = textwidth(LPCTSTR(headers[j].c_str()));
|
||||
const int h = textheight(LPCTSTR(headers[j].c_str()));
|
||||
@@ -82,16 +81,20 @@ void Table::initTextWaH()
|
||||
|
||||
// 用“所有列的最大行高”作为一行的基准高度
|
||||
int maxLineH = 0;
|
||||
|
||||
for (int h : lineHeights)
|
||||
if (h > maxLineH)
|
||||
|
||||
for (int h : lineHeights)
|
||||
if (h > maxLineH)
|
||||
maxLineH = h;
|
||||
|
||||
// 列的像素宽 = 内容宽 + 左右 padding
|
||||
// 列宽包含左右 padding:在计算完最大文本宽度后,加上 2*padX 作为单元格内边距
|
||||
for (size_t j = 0; j < colWidths.size(); ++j) {
|
||||
colWidths[j] += 2 * padX;
|
||||
}
|
||||
|
||||
// 表内容总宽 = Σ(列宽 + 列间距)
|
||||
int contentW = 0;
|
||||
for (size_t j = 0; j < colWidths.size(); ++j)
|
||||
contentW += (colWidths[j] + 2 * padX) + colGap;
|
||||
contentW += colWidths[j] + colGap;
|
||||
|
||||
// 表头高 & 行高(与 drawHeader/drawTable 内部一致:+上下 padding)
|
||||
const int headerH = maxLineH + 2 * padY;
|
||||
@@ -109,6 +112,9 @@ void Table::initTextWaH()
|
||||
// 最终表宽/高:内容 + 对称边框
|
||||
this->width = contentW + (border << 1);
|
||||
this->height = headerH + rowsH + footerH + (border << 1);
|
||||
// 记录原始宽高用于锚点布局的参考;此处仅在初始化单元尺寸时重置
|
||||
this->localWidth = this->width;
|
||||
this->localHeight = this->height;
|
||||
}
|
||||
|
||||
void Table::initButton()
|
||||
@@ -124,7 +130,6 @@ void Table::initButton()
|
||||
int prevW = textwidth(LPCTSTR(TABLE_STR_PREV)) + padH * 2;
|
||||
int nextW = textwidth(LPCTSTR(TABLE_STR_NEXT)) + padH * 2;
|
||||
int btnH = lblH + padV * 2;
|
||||
|
||||
|
||||
// 基于“页码标签”的矩形来摆放:
|
||||
// prev 在页码左侧 gap 处;next 在右侧 gap 处;Y 对齐 pY
|
||||
@@ -153,24 +158,40 @@ void Table::initButton()
|
||||
prevButton->setFillMode(tableFillMode);
|
||||
nextButton->setFillMode(tableFillMode);
|
||||
|
||||
prevButton->setOnClickListener([this]()
|
||||
prevButton->setOnClickListener([this]()
|
||||
{
|
||||
if (currentPage > 1)
|
||||
{
|
||||
--currentPage;
|
||||
dirty = true;
|
||||
if (pageNum) pageNum->setDirty(true);
|
||||
}
|
||||
int oldPage = currentPage;
|
||||
if (currentPage > 1)
|
||||
{
|
||||
--currentPage;
|
||||
SX_LOGI("Table")
|
||||
<< SX_T("翻页:id=", "page change: id=") << id
|
||||
<< " " << oldPage << "->" << currentPage
|
||||
<< SX_T(" 总页数=", " total=") << totalPages
|
||||
<< SX_T(" 行数=", " rows=") << (int)data.size();
|
||||
|
||||
|
||||
dirty = true;
|
||||
if (pageNum) pageNum->setDirty(true);
|
||||
}
|
||||
});
|
||||
nextButton->setOnClickListener([this]()
|
||||
nextButton->setOnClickListener([this]()
|
||||
{
|
||||
if (currentPage < totalPages)
|
||||
{
|
||||
++currentPage;
|
||||
dirty = true;
|
||||
if (pageNum) pageNum->setDirty(true);
|
||||
}
|
||||
int oldPage = currentPage;
|
||||
if (currentPage < totalPages)
|
||||
{
|
||||
++currentPage;
|
||||
SX_LOGI("Table")
|
||||
<< SX_T("翻页:id=", "page change: id=") << id
|
||||
<< " " << oldPage << "->" << currentPage
|
||||
<< SX_T(" 总页数=", " total=") << totalPages
|
||||
<< SX_T(" 行数=", " rows=") << (int)data.size();
|
||||
|
||||
dirty = true;
|
||||
if (pageNum) pageNum->setDirty(true);
|
||||
}
|
||||
});
|
||||
isNeedButtonAndPageNum = false;
|
||||
}
|
||||
|
||||
void Table::initPageNum()
|
||||
@@ -191,11 +212,11 @@ void Table::initPageNum()
|
||||
// 按理来说 x + (this->width - textW) / 2;就可以
|
||||
// 但是在绘制时,发现控件偏右,因此减去40
|
||||
int textW = textwidth(LPCTSTR(pageNumtext.c_str()));
|
||||
pX = x + TABLE_PAGE_TEXT_OFFSET_X +(this->width - textW) / 2;
|
||||
pX = x + TABLE_PAGE_TEXT_OFFSET_X + (this->width - textW) / 2;
|
||||
|
||||
if (!pageNum)
|
||||
if (!pageNum)
|
||||
pageNum = new Label(pX, pY, pageNumtext);
|
||||
else
|
||||
else
|
||||
{
|
||||
pageNum->setX(pX);
|
||||
pageNum->setY(pY);
|
||||
@@ -208,25 +229,23 @@ void Table::initPageNum()
|
||||
|
||||
void Table::drawPageNum()
|
||||
{
|
||||
|
||||
pageNumtext = "第";
|
||||
pageNumtext+= std::to_string(currentPage);
|
||||
pageNumtext += std::to_string(currentPage);
|
||||
pageNumtext += "页/共";
|
||||
pageNumtext += std::to_string(totalPages);
|
||||
pageNumtext += "页";
|
||||
if (nullptr == pageNum)
|
||||
if (nullptr == pageNum || isNeedButtonAndPageNum)
|
||||
initPageNum();
|
||||
pageNum->setText(pageNumtext);
|
||||
pageNum->textStyle = this->textStyle;
|
||||
if (StellarX::FillMode::Null == tableFillMode)
|
||||
pageNum->setTextdisap(true);
|
||||
pageNum->draw();
|
||||
|
||||
}
|
||||
|
||||
void Table::drawButton()
|
||||
{
|
||||
if (nullptr == prevButton || nullptr == nextButton)
|
||||
if ((nullptr == prevButton || nullptr == nextButton) || isNeedButtonAndPageNum)
|
||||
initButton();
|
||||
|
||||
this->prevButton->textStyle = this->textStyle;
|
||||
@@ -239,7 +258,59 @@ void Table::drawButton()
|
||||
this->nextButton->setDirty(true);
|
||||
prevButton->draw();
|
||||
nextButton->draw();
|
||||
}
|
||||
|
||||
void Table::setX(int x)
|
||||
{
|
||||
this->x = x;
|
||||
isNeedButtonAndPageNum = true;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void Table::setY(int y)
|
||||
{
|
||||
this->y = y;
|
||||
isNeedButtonAndPageNum = true;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void Table::setWidth(int width)
|
||||
{
|
||||
// 调整列宽以匹配新的表格总宽度。不修改 localWidth,避免累计误差。
|
||||
// 当 width 与当前 width 不同时,根据差值平均分配到各列,余数依次累加/扣减。
|
||||
const int ncols = static_cast<int>(colWidths.size());
|
||||
if (ncols <= 0) {
|
||||
this->width = width;
|
||||
isNeedButtonAndPageNum = true;
|
||||
return;
|
||||
}
|
||||
int diff = width - this->width;
|
||||
// 基础增量:整除部分
|
||||
int baseChange = diff / ncols;
|
||||
int remainder = diff % ncols;
|
||||
for (int i = 0; i < ncols; ++i) {
|
||||
int change = baseChange;
|
||||
if (remainder > 0) {
|
||||
change += 1;
|
||||
remainder -= 1;
|
||||
}
|
||||
else if (remainder < 0) {
|
||||
change -= 1;
|
||||
remainder += 1;
|
||||
}
|
||||
int newWidth = colWidths[i] + change;
|
||||
// 限制最小宽度为 1,防止出现负值
|
||||
if (newWidth < 1) newWidth = 1;
|
||||
colWidths[i] = newWidth;
|
||||
}
|
||||
this->width = width;
|
||||
// 需要重新布局页脚元素
|
||||
isNeedButtonAndPageNum = true;
|
||||
}
|
||||
|
||||
void Table::setHeight(int height)
|
||||
{
|
||||
//高度不变
|
||||
}
|
||||
|
||||
Table::Table(int x, int y)
|
||||
@@ -317,18 +388,30 @@ void Table::draw()
|
||||
setfillstyle((int)tableFillMode);
|
||||
setbkmode(TRANSPARENT);
|
||||
}
|
||||
//确保在绘制任何表格内容之前捕获背景
|
||||
// 临时恢复样式,确保捕获正确的背景
|
||||
if ((!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height)||!saveBkImage)
|
||||
// 在绘制前先恢复并更新背景快照:
|
||||
// 如果已有快照且尺寸发生变化,先恢复旧快照以清除上一次绘制,然后丢弃旧快照再重新抓取新的区域。
|
||||
if (hasSnap)
|
||||
{
|
||||
// 始终先恢复旧背景,清除上一帧内容
|
||||
restBackground();
|
||||
// 当尺寸变化或缓存图像无效时,需要重新截图
|
||||
if (!saveBkImage || saveWidth != this->width || saveHeight != this->height)
|
||||
{
|
||||
discardBackground();
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 首次绘制时无背景缓存,直接抓取
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
// 恢复背景(清除旧内容)
|
||||
}
|
||||
// 恢复最新的背景,保证绘制区域干净
|
||||
restBackground();
|
||||
// 绘制表头
|
||||
|
||||
dX = x;
|
||||
dY = y;
|
||||
drawHeader();
|
||||
this->isNeedDrawHeaders = false;
|
||||
//if (!headers.empty())
|
||||
drawHeader();
|
||||
// 绘制当前页
|
||||
drawTable();
|
||||
// 绘制页码标签
|
||||
@@ -337,7 +420,6 @@ void Table::draw()
|
||||
// 绘制翻页按钮
|
||||
if (this->isShowPageButton)
|
||||
drawButton();
|
||||
|
||||
|
||||
// 恢复绘图状态
|
||||
restoreStyle();
|
||||
@@ -347,14 +429,14 @@ void Table::draw()
|
||||
|
||||
bool Table::handleEvent(const ExMessage& msg)
|
||||
{
|
||||
if(!show)return false;
|
||||
if (!show)return false;
|
||||
bool consume = false;
|
||||
if(!this->isShowPageButton)
|
||||
if (!this->isShowPageButton)
|
||||
return consume;
|
||||
else
|
||||
{
|
||||
if(prevButton)consume = prevButton->handleEvent(msg);
|
||||
if (nextButton&&!consume)
|
||||
if (prevButton)consume = prevButton->handleEvent(msg);
|
||||
if (nextButton && !consume)
|
||||
consume = nextButton->handleEvent(msg);
|
||||
}
|
||||
if (dirty)
|
||||
@@ -365,43 +447,61 @@ bool Table::handleEvent(const ExMessage& msg)
|
||||
void Table::setHeaders(std::initializer_list<std::string> headers)
|
||||
{
|
||||
this->headers.clear();
|
||||
for (auto lis : headers)
|
||||
for (auto& lis : headers)
|
||||
this->headers.push_back(lis);
|
||||
SX_LOGI("Table") << SX_T("设置表头:id=","setHeaders: id=") << id << SX_T("总数="," count=") << (int)this->headers.size();
|
||||
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
|
||||
isNeedDrawHeaders = true; // 标记需要重新绘制表头
|
||||
dirty = true;
|
||||
|
||||
}
|
||||
|
||||
void Table::setData( std::vector<std::string> data)
|
||||
void Table::setData(std::vector<std::string> data)
|
||||
{
|
||||
if (data.size() < headers.size())
|
||||
for (int i = 0; data.size() <= headers.size(); i++)
|
||||
data.push_back("");
|
||||
while (data.size() < headers.size())
|
||||
data.push_back("");
|
||||
|
||||
this->data.push_back(data);
|
||||
|
||||
totalPages = ((int)this->data.size() + rowsPerPage - 1) / rowsPerPage;
|
||||
if (totalPages < 1)
|
||||
totalPages = 1;
|
||||
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
|
||||
|
||||
isNeedCellSize = true;
|
||||
dirty = true;
|
||||
|
||||
SX_LOGI("Table")
|
||||
<< SX_T("新增Data:id=", "appendRow: id=") << id
|
||||
<< SX_T(" 本行列数=", " cols=") << (int)data.size()
|
||||
<< SX_T(" 数据总行数=", " totalRows=") << (int)this->data.size()
|
||||
<< SX_T(" 总页数=", " totalPages=") << totalPages;
|
||||
}
|
||||
|
||||
void Table::setData( std::initializer_list<std::vector<std::string>> data)
|
||||
|
||||
void Table::setData(std::initializer_list<std::vector<std::string>> data)
|
||||
{
|
||||
for (auto lis : data)
|
||||
if (lis.size() < headers.size())
|
||||
{
|
||||
for (size_t i = lis.size(); i< headers.size(); i++)
|
||||
for (size_t i = lis.size(); i < headers.size(); i++)
|
||||
lis.push_back("");
|
||||
this->data.push_back(lis);
|
||||
}
|
||||
else
|
||||
this->data.push_back(lis);
|
||||
|
||||
|
||||
totalPages = ((int)this->data.size() + rowsPerPage - 1) / rowsPerPage;
|
||||
if (totalPages < 1)
|
||||
totalPages = 1;
|
||||
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
|
||||
dirty = true;
|
||||
SX_LOGI("Table")
|
||||
<< SX_T("新增Data:id=", "appendRow: id=") << id
|
||||
<< SX_T(" 本行列数=", " cols=") << (int)data.size()
|
||||
<< SX_T(" 数据总行数=", " totalRows=") << (int)this->data.size()
|
||||
<< SX_T(" 总页数=", " totalPages=") << totalPages;
|
||||
|
||||
|
||||
}
|
||||
|
||||
void Table::setRowsPerPage(int rows)
|
||||
@@ -464,6 +564,45 @@ void Table::setTableBorderWidth(int width)
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void Table::clearHeaders()
|
||||
{
|
||||
this->headers.clear();
|
||||
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
|
||||
isNeedDrawHeaders = true; // 标记需要重新绘制表头
|
||||
isNeedButtonAndPageNum = true;// 标记需要重新计算翻页按钮和页码信息
|
||||
dirty = true;
|
||||
SX_LOGI("Table") << SX_T("清除表头:id=","clearHeaders: id=" )<< id;
|
||||
|
||||
}
|
||||
|
||||
void Table::clearData()
|
||||
{
|
||||
this->data.clear();
|
||||
this->currentPage = 1;
|
||||
this->totalPages = 1;
|
||||
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
|
||||
isNeedButtonAndPageNum = true;// 标记需要重新计算翻页按钮和页码信息
|
||||
dirty = true;
|
||||
SX_LOGI("Table") << SX_T("清除表格数据:id=","clearData: id=") << id;
|
||||
}
|
||||
|
||||
void Table::resetTable()
|
||||
{
|
||||
clearHeaders();
|
||||
clearData();
|
||||
}
|
||||
|
||||
void Table::onWindowResize()
|
||||
{
|
||||
Control::onWindowResize(); // 先处理自己
|
||||
if (this->prevButton && this->nextButton && this->pageNum)
|
||||
{
|
||||
prevButton->onWindowResize();
|
||||
nextButton->onWindowResize();
|
||||
pageNum->onWindowResize();
|
||||
}
|
||||
}
|
||||
|
||||
int Table::getCurrentPage() const
|
||||
{
|
||||
return this->currentPage;
|
||||
@@ -519,4 +658,15 @@ int Table::getTableBorderWidth() const
|
||||
return this->tableBorderWidth;
|
||||
}
|
||||
|
||||
int Table::getTableWidth() const
|
||||
{
|
||||
int temp = 0;
|
||||
for (auto& w : colWidths)
|
||||
temp += w;
|
||||
return temp;
|
||||
}
|
||||
|
||||
int Table::getTableHeight() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
+194
-111
@@ -1,161 +1,244 @@
|
||||
// TextBox.cpp
|
||||
#include "TextBox.h"
|
||||
|
||||
#include "SxLog.h"
|
||||
|
||||
TextBox::TextBox(int x, int y, int width, int height, std::string text, StellarX::TextBoxmode mode, StellarX::ControlShape shape)
|
||||
:Control(x,y,width,height),text(text), mode(mode), shape(shape)
|
||||
:Control(x, y, width, height), text(text), mode(mode), shape(shape)
|
||||
{
|
||||
this->id = "TextBox";
|
||||
this->id = "TextBox";
|
||||
}
|
||||
|
||||
void TextBox::draw()
|
||||
{
|
||||
if (dirty && show)
|
||||
{
|
||||
saveStyle();
|
||||
setfillcolor(textBoxBkClor);
|
||||
setlinecolor(textBoxBorderClor);
|
||||
if (textStyle.nHeight > height)
|
||||
textStyle.nHeight = height;
|
||||
if (textStyle.nWidth > width)
|
||||
textStyle.nWidth = width;
|
||||
settextstyle(textStyle.nHeight, textStyle.nWidth, textStyle.lpszFace,
|
||||
textStyle.nEscapement, textStyle.nOrientation, textStyle.nWeight,
|
||||
textStyle.bItalic, textStyle.bUnderline, textStyle.bStrikeOut);
|
||||
|
||||
settextcolor(textStyle.color);
|
||||
setbkmode(TRANSPARENT);
|
||||
int text_width = textwidth(LPCTSTR(text.c_str()));
|
||||
int text_height = textheight(LPCTSTR(text.c_str()));
|
||||
if (dirty && show)
|
||||
{
|
||||
saveStyle();
|
||||
setfillcolor(textBoxBkClor);
|
||||
setlinecolor(textBoxBorderClor);
|
||||
if (textStyle.nHeight > height)
|
||||
textStyle.nHeight = height;
|
||||
if (textStyle.nWidth > width)
|
||||
textStyle.nWidth = width;
|
||||
settextstyle(textStyle.nHeight, textStyle.nWidth, textStyle.lpszFace,
|
||||
textStyle.nEscapement, textStyle.nOrientation, textStyle.nWeight,
|
||||
textStyle.bItalic, textStyle.bUnderline, textStyle.bStrikeOut);
|
||||
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
// 恢复背景(清除旧内容)
|
||||
restBackground();
|
||||
//根据形状绘制
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
fillrectangle(x,y,x+width,y+height);//有边框填充矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(text.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
solidrectangle(x, y, x + width, y + height);//无边框填充矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(text.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
fillroundrect(x, y, x + width, y + height, rouRectangleSize.ROUND_RECTANGLEwidth, rouRectangleSize.ROUND_RECTANGLEheight);//有边框填充圆角矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(text.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
solidroundrect(x, y, x + width, y + height, rouRectangleSize.ROUND_RECTANGLEwidth, rouRectangleSize.ROUND_RECTANGLEheight);//无边框填充圆角矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(text.c_str()));
|
||||
break;
|
||||
}
|
||||
settextcolor(textStyle.color);
|
||||
setbkmode(TRANSPARENT);
|
||||
|
||||
int text_width = 0;
|
||||
int text_height = 0;
|
||||
std::string pwdText;
|
||||
std::string displayText; // 用于显示的文本(可能被截断)
|
||||
bool isTextTruncated = false; // 标记文本是否被截断
|
||||
|
||||
if (StellarX::TextBoxmode::PASSWORD_MODE == mode)
|
||||
{
|
||||
for (size_t i = 0; i < text.size(); ++i)
|
||||
pwdText += '*';
|
||||
displayText = pwdText;
|
||||
}
|
||||
else
|
||||
{
|
||||
displayText = text;
|
||||
}
|
||||
|
||||
// 计算可用宽度(留出左右边距)
|
||||
int availableWidth = width - 20; // 左右各10像素边距
|
||||
|
||||
// 截断文本以适应可用宽度
|
||||
int currentWidth = textwidth(LPCTSTR(displayText.c_str()));
|
||||
if (currentWidth > availableWidth && availableWidth > 0)
|
||||
{
|
||||
// 需要截断文本,预留空间放置省略号
|
||||
int ellipsisWidth = textwidth("...");
|
||||
int truncatedWidth = availableWidth - ellipsisWidth;
|
||||
|
||||
std::string truncatedText = displayText;
|
||||
while (truncatedText.size() > 0 && textwidth(LPCTSTR(truncatedText.c_str())) > truncatedWidth)
|
||||
{
|
||||
truncatedText.pop_back();
|
||||
}
|
||||
displayText = truncatedText + "...";
|
||||
isTextTruncated = true;
|
||||
currentWidth = textwidth(LPCTSTR(displayText.c_str()));
|
||||
}
|
||||
|
||||
text_width = currentWidth;
|
||||
text_height = textheight(LPCTSTR(displayText.c_str()));
|
||||
|
||||
if ((saveBkX != this->x) || (saveBkY != this->y) || (!hasSnap) || (saveWidth != this->width) || (saveHeight != this->height) || !saveBkImage)
|
||||
saveBackground(this->x, this->y, this->width, this->height);
|
||||
// 恢复背景(清除旧内容)
|
||||
restBackground();
|
||||
//根据形状绘制
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
fillrectangle(x, y, x + width, y + height);//有边框填充矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(displayText.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
solidrectangle(x, y, x + width, y + height);//无边框填充矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(displayText.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
fillroundrect(x, y, x + width, y + height, rouRectangleSize.ROUND_RECTANGLEwidth, rouRectangleSize.ROUND_RECTANGLEheight);//有边框填充圆角矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(displayText.c_str()));
|
||||
break;
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
solidroundrect(x, y, x + width, y + height, rouRectangleSize.ROUND_RECTANGLEwidth, rouRectangleSize.ROUND_RECTANGLEheight);//无边框填充圆角矩形
|
||||
outtextxy(x + 10, (y + (height - text_height) / 2), LPCTSTR(displayText.c_str()));
|
||||
break;
|
||||
}
|
||||
restoreStyle();
|
||||
dirty = false; //标记不需要重绘
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
bool TextBox::handleEvent(const ExMessage& msg)
|
||||
{
|
||||
bool hover = false;
|
||||
bool oldClick = click;
|
||||
bool consume = false;
|
||||
if (!show) return false;
|
||||
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
hover = (msg.x > x && msg.x < (x + width) && msg.y > y && msg.y < (y + height));//判断鼠标是否在矩形按钮内
|
||||
consume = false;
|
||||
break;
|
||||
}
|
||||
if (hover && msg.message == WM_LBUTTONUP)
|
||||
{
|
||||
click = true;
|
||||
if(StellarX::TextBoxmode::INPUT_MODE == mode)
|
||||
bool hover = false;
|
||||
bool oldClick = click;
|
||||
bool consume = false;
|
||||
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
hover = (msg.x > x && msg.x < (x + width) && msg.y > y && msg.y < (y + height));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (hover && msg.message == WM_LBUTTONUP)
|
||||
{
|
||||
click = true;
|
||||
|
||||
const size_t oldLen = text.size();
|
||||
SX_LOGI("TextBox") << SX_T("激活:id=","activate: id=") << id << " mode=" << (int)mode << " oldLen=" << oldLen;
|
||||
|
||||
if (StellarX::TextBoxmode::INPUT_MODE == mode)
|
||||
{
|
||||
dirty = InputBox(LPTSTR(text.c_str()), (int)maxCharLen, "输入框", NULL, text.c_str(), NULL, NULL, false);
|
||||
char* temp = new char[maxCharLen + 1];
|
||||
dirty = InputBox(temp, (int)maxCharLen + 1, "输入框", NULL, text.c_str(), NULL, NULL, false);
|
||||
if (dirty) text = temp;
|
||||
delete[] temp;
|
||||
consume = true;
|
||||
}
|
||||
else if (StellarX::TextBoxmode::READONLY_MODE == mode)
|
||||
{
|
||||
dirty = false;
|
||||
InputBox(NULL, (int)maxCharLen, "输出框(输入无效!)", NULL, text.c_str(), NULL, NULL, false);
|
||||
consume = true;
|
||||
}
|
||||
else if (StellarX::TextBoxmode::PASSWORD_MODE == mode)
|
||||
{
|
||||
char* temp = new char[maxCharLen + 1];
|
||||
// 不记录明文,只记录长度变化
|
||||
dirty = InputBox(temp, (int)maxCharLen + 1, "输入框\n不可见输入,覆盖即可", NULL, NULL, NULL, NULL, false);
|
||||
if (dirty) text = temp;
|
||||
delete[] temp;
|
||||
consume = true;
|
||||
}
|
||||
else if (StellarX::TextBoxmode::READONLY_MODE == mode)
|
||||
{
|
||||
dirty = false;
|
||||
InputBox(NULL, (int)maxCharLen, "输出框(输入无效!)", NULL, text.c_str(), NULL, NULL, false);
|
||||
consume = true;
|
||||
}
|
||||
flushmessage(EX_MOUSE | EX_KEY);
|
||||
}
|
||||
if (dirty)
|
||||
requestRepaint(parent);
|
||||
|
||||
if (click)
|
||||
click = false;
|
||||
return consume;
|
||||
if (dirty)
|
||||
{
|
||||
SX_LOGI("TextBox") << SX_T("文本已更改: id=","text changed: id=") << id
|
||||
<< " oldLen=" << oldLen << " newLen=" << text.size();
|
||||
}
|
||||
else
|
||||
{
|
||||
SX_LOGD("TextBox") << SX_T("文本无变化:id=","no change: id=") << id;
|
||||
}
|
||||
|
||||
flushmessage(EX_MOUSE | EX_KEY);
|
||||
}
|
||||
|
||||
if (dirty)
|
||||
requestRepaint(parent);
|
||||
|
||||
if (click)
|
||||
click = false;
|
||||
|
||||
return consume;
|
||||
}
|
||||
|
||||
|
||||
void TextBox::setMode(StellarX::TextBoxmode mode)
|
||||
{
|
||||
this->mode = mode;
|
||||
this->dirty = true;
|
||||
this->mode = mode;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void TextBox::setMaxCharLen(size_t len)
|
||||
{
|
||||
if (len > 0)
|
||||
maxCharLen = len;
|
||||
this->dirty = true;
|
||||
if (len > 0)
|
||||
maxCharLen = len;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void TextBox::setTextBoxshape(StellarX::ControlShape shape)
|
||||
{
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
this->shape = shape;
|
||||
this->dirty = true;
|
||||
break;
|
||||
switch (shape)
|
||||
{
|
||||
case StellarX::ControlShape::RECTANGLE:
|
||||
case StellarX::ControlShape::B_RECTANGLE:
|
||||
case StellarX::ControlShape::ROUND_RECTANGLE:
|
||||
case StellarX::ControlShape::B_ROUND_RECTANGLE:
|
||||
this->shape = shape;
|
||||
this->dirty = true;
|
||||
break;
|
||||
case StellarX::ControlShape::CIRCLE:
|
||||
case StellarX::ControlShape::B_CIRCLE:
|
||||
case StellarX::ControlShape::ELLIPSE:
|
||||
case StellarX::ControlShape::B_ELLIPSE:
|
||||
this->shape = StellarX::ControlShape::RECTANGLE;
|
||||
this->dirty = true;
|
||||
break;
|
||||
}
|
||||
case StellarX::ControlShape::B_CIRCLE:
|
||||
case StellarX::ControlShape::ELLIPSE:
|
||||
case StellarX::ControlShape::B_ELLIPSE:
|
||||
this->shape = StellarX::ControlShape::RECTANGLE;
|
||||
this->dirty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void TextBox::setTextBoxBorder(COLORREF color)
|
||||
{
|
||||
textBoxBorderClor = color;
|
||||
this->dirty = true;
|
||||
textBoxBorderClor = color;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void TextBox::setTextBoxBk(COLORREF color)
|
||||
{
|
||||
textBoxBkClor = color;
|
||||
this->dirty = true;
|
||||
textBoxBkClor = color;
|
||||
this->dirty = true;
|
||||
}
|
||||
|
||||
void TextBox::setText(std::string text)
|
||||
{
|
||||
if(text.size() > maxCharLen)
|
||||
text = text.substr(0, maxCharLen);
|
||||
this->text = text;
|
||||
this->dirty = true;
|
||||
draw();
|
||||
if(text == this->text)
|
||||
return; // 文本未改变,无需更新和重绘
|
||||
if (text.size() > maxCharLen)
|
||||
text = text.substr(0, maxCharLen);
|
||||
this->text = text;
|
||||
this->dirty = true; // 标记需要重绘,不论是否窗口图形上下文是否已初始化,等第一次绘制时由窗口真正调用 draw() 来重绘显示文本
|
||||
|
||||
//有父控件时请求父控件重绘,无父控件时直接重绘,确保文本更新后界面正确刷新显示
|
||||
if (nullptr != parent)
|
||||
{
|
||||
//通过hasSnap是否持有有效快照,判断控件是否已经绘制过,避免在控件未绘制前/窗口图形上下文未初始化调用draw()导致的错误
|
||||
if (hasSnap)
|
||||
requestRepaint(parent);
|
||||
}
|
||||
else
|
||||
if (hasSnap)
|
||||
draw();
|
||||
|
||||
}
|
||||
|
||||
std::string TextBox::getText() const
|
||||
{
|
||||
return this->text;
|
||||
}
|
||||
|
||||
|
||||
return this->text;
|
||||
}
|
||||
+701
-172
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,687 @@
|
||||
# StellarX GUI Framework API Documentation (中英双语)
|
||||
|
||||
## CoreTypes(基础类型)
|
||||
|
||||
**CoreTypes** 模块定义了 StellarX 框架中使用的所有基础枚举和结构体类型,以确保类型一致性(Core types module defines all fundamental enums and structs used in the StellarX framework to ensure type consistency)。主要包括以下内容:
|
||||
|
||||
- **FillStyle(填充图案样式)**:定义控件填充图案的枚举类型。例如 Horizontal 表示水平线填充,Vertical 表示垂直线,FDiagonal 表示反斜线,BDiagonal 表示正斜线,Cross 表示十字,DiagCross 表示网格。(Defines patterns for filling control backgrounds. For example, Horizontal for horizontal lines, Vertical for vertical lines, FDiagonal for forward diagonal lines, BDiagonal for backward diagonal lines, Cross for crosshatch, DiagCross for grid pattern.)默认填充图案为水平线 (The default pattern is horizontal line)。
|
||||
|
||||
- **FillMode(填充模式)**:定义控件背景的填充模式,包括纯色、无填充、图案填充、自定义图案、自定义图片填充等。(Defines how control backgrounds are filled: solid color, no fill, hatched pattern, custom pattern, or custom image fill, etc.)例如 Solid(固实填充),Null(不填充),Hatched(图案填充),Pattern(自定义图案),DibPattern(自定义图像)。默认填充模式为 Solid 固实填充 (default is solid fill)。
|
||||
|
||||
- **LineStyle(线型样式)**:定义控件边框的线型风格枚举。例如 Solid 表示实线,Dash 表示虚线,Dot 表示点线,DashDot 表示点划线,DashDotDot 表示双点划线,Null 表示无边框线。(Defines line style for control borders. For example, Solid for solid line, Dash for dashed line, Dot for dotted line, DashDot for dash-dot line, DashDotDot for double dash-dot, Null for no border line.)默认边框线型为实线 (default line style is solid)。
|
||||
|
||||
- **ControlShape(控件形状)**:定义控件的几何形状类型,共提供矩形、圆角矩形、圆形、椭圆,每种形状分别有“有边框”和“无边框”两种版本。(Enumerates geometric shape types for controls: rectangle, rounded rectangle, circle, and ellipse – each in bordered and borderless variants.)例如 RECTANGLE(有边框矩形)、B_RECTANGLE(无边框矩形)、ROUND_RECTANGLE(有边框圆角矩形)、B_ROUND_RECTANGLE(无边框圆角矩形)、CIRCLE(有边框圆形)、B_CIRCLE(无边框圆形)、ELLIPSE(有边框椭圆)、B_ELLIPSE(无边框椭圆)。按钮类支持所有形状,而某些控件可能只支持部分形状(Button supports all shapes, while some controls only support a subset of shapes)。
|
||||
|
||||
- **TextBoxmode(文本框模式)**:定义文本框控件的工作模式枚举,包括 `INPUT_MODE`(用户可输入模式)、`READONLY_MODE`(只读模式)和 `PASSWORD_MODE`(密码模式)。这允许设置文本框是否可输入、仅显示或以密码形式显示。(Defines the operating mode of a TextBox control: `INPUT_MODE` for editable text input, `READONLY_MODE` for read-only display, and `PASSWORD_MODE` for password input mode, allowing configuration of whether the text box accepts input or is display-only or masked as password input.)
|
||||
|
||||
- **ButtonMode(按钮模式)**:定义按钮控件的工作模式枚举,包括 `NORMAL`(普通模式)、`TOGGLE`(切换模式)和 `DISABLED`(禁用模式)。普通模式下按钮每次点击触发回调但不保持状态;切换模式下按钮在选中/未选中之间切换,并触发不同回调;禁用模式下按钮不可点击,显示灰化且文本带删除线。(Defines the working mode of a Button: `NORMAL` mode triggers a callback on each click without maintaining state; `TOGGLE` mode toggles between pressed and unpressed states and triggers different callbacks for each; `DISABLED` mode makes the button non-clickable, typically grayed out with strikethrough text to indicate disabled state.)
|
||||
|
||||
- **MessageBoxType(消息框类型)**:枚举标准消息框的按钮组合类型,包括 OK(只有“确定”按钮)、OKCancel(“确定”和“取消”)、YesNo(“是”和“否”)、YesNoCancel(“是”“否”“取消”)、RetryCancel(“重试”和“取消”)、AbortRetryIgnore(“中止”“重试”“忽略”)等类型。(Enumerates the standard combinations of buttons for a message box: e.g., OK (OK button only), OKCancel (OK and Cancel), YesNo, YesNoCancel, RetryCancel, AbortRetryIgnore, etc.)开发者可根据需要选择消息框包含的按钮组合 (Developers can select the appropriate set of buttons for the message box as needed)。
|
||||
|
||||
- **MessageBoxResult(消息框结果)**:枚举消息框的返回结果类型,与 MessageBoxType 相对应,包括 OK(确定)、Cancel(取消)、Yes(是)、No(否)、Abort(中止)、Retry(重试)、Ignore(忽略)等。(Enumerates the possible results of a message box, corresponding to which button was pressed: OK, Cancel, Yes, No, Abort, Retry, Ignore, etc.)模态消息框会返回这些枚举值表示用户选择 (Modal message boxes return one of these values to indicate the user's choice)。
|
||||
|
||||
- **LayoutMode(布局模式)**:定义窗口拉伸时控件的布局策略,包括 `Fixed`(固定布局)和 `AnchorToEdges`(锚定布局)。(Defines how controls behave when the window is resized: `Fixed` for no resizing (controls maintain their size/position), and `AnchorToEdges` for anchoring controls to container edges so they stretch or move accordingly.)通过 **Control** 的接口可以设置控件的布局模式 (The layout mode for a control can be set via the **Control** class’s interface)。
|
||||
|
||||
- **Anchor(锚点位置)**:定义控件相对于父窗口的锚定边缘位置,用于 AnchorToEdges 布局模式。包括 Left(左锚定)、Right(右锚定)、Top(上锚定)、Bottom(下锚定)以及 NoAnchor(不锚定)。可以组合两个锚点来固定控件的两个方向。(Defines which edges of the parent container a control is anchored to (used when layout mode is AnchorToEdges). Options include Left, Right, Top, Bottom, plus NoAnchor for no anchoring. Two anchors (horizontal and vertical) are typically used together to lock the control’s position in both directions.)
|
||||
|
||||
- **TabPlacement(选项卡位置)**:定义 TabControl 选项卡标签栏的位置,包括 Top(页签在顶部)、Bottom(在底部)、Left(在左侧)、Right(在右侧)。选择不同值会将选项卡的标签(按钮)放置在容器的不同边缘。(Defines the placement of the tab headers in a TabControl: Top, Bottom, Left, or Right. The chosen value determines on which edge of the TabControl the tab buttons are displayed.)
|
||||
|
||||
- **RouRectangle(圆角矩形参数)**:用于定义控件圆角矩形形状时圆角的椭圆尺寸的结构体。包含两个整数成员 ROUND_RECTANGLEwidth 和 ROUND_RECTANGLEheight,默认值均为 20,表示圆角矩形拐角处椭圆的宽度和高度。(A struct defining the ellipse size of the corners for rounded rectangle shapes. It has two int members, ROUND_RECTANGLEwidth and ROUND_RECTANGLEheight (both default to 20), which represent the width and height of the ellipse used for the rounded corners of a rectangle.)通过修改这个结构体,可以调整控件圆角的弧度 (By modifying these values, one can adjust the curvature of a control’s rounded corners).
|
||||
|
||||
- **ControlText(控件文本样式)**:定义控件字体和文本颜色样式的结构体。它包含多个字段用于描述文本外观:
|
||||
|
||||
- `nHeight`:字体高度(像素值)(font height in pixels)
|
||||
- `nWidth`:字体宽度(像素值,如果为0则自动适配高度)(font width in pixels; 0 means auto-adjust to height)
|
||||
- `lpszFace`:字体名称,默认“微软雅黑” (font face name, default is "微软雅黑" font)
|
||||
- `color`:文字颜色,默认黑色 (text color, default RGB(0,0,0) black)
|
||||
- `nEscapement`:字符串整体旋转角度(单位0.1度,如900表示90度)(text escapement angle for the entire string, in tenths of degrees, e.g., 900 means 90°)
|
||||
- `nOrientation`:单个字符旋转角度(单位0.1度)(orientation angle of individual characters, also in tenths of degrees)
|
||||
- `nWeight`:字体粗细(字重),0表示默认,范围0~1000 (font weight/thickness, 0 means default; range 0~1000)
|
||||
- `bItalic`:是否斜体 (italic flag)
|
||||
- `bUnderline`:是否下划线 (underline flag)
|
||||
- `bStrikeOut`:是否删除线 (strikethrough flag)
|
||||
|
||||
此结构可用于控件的文本样式自定义,如 **Button**、**Label** 等控件都有 `textStyle` 成员使用该结构。(This struct is used to customize text appearance for controls. For example, **Button**, **Label**, etc., include a `textStyle` member of this type to specify font and text style.)
|
||||
|
||||
## Control(控件基类)
|
||||
|
||||
**类名**:`Control`
|
||||
**中文简要说明**:所有控件的抽象基类,定义通用接口和基础功能,不直接实例化。(*Abstract base class for all UI controls, defining common interfaces and fundamental functionality. It is not meant to be instantiated directly*。)
|
||||
|
||||
**继承关系**:无(Control 为顶级基类)(None. Control is the top-level base class for all controls).
|
||||
|
||||
**功能摘要**: Control 提供控件的基本属性(如位置、尺寸)和通用方法,并实现绘图状态保存/恢复机制,确保控件绘制不影响全局状态。它还声明了一些纯虚方法供子类实现,例如 `draw()` 和 `handleEvent()`。(*The Control class provides basic properties (position, size, visibility) and common methods for controls. It implements mechanisms for saving and restoring drawing state to ensure control rendering does not disturb global graphics state. It also declares abstract methods like `draw()` and `handleEvent()` that subclasses must implement.*)
|
||||
|
||||
**公共方法 (Public Methods)**:
|
||||
|
||||
- `draw()` – **纯虚函数**,由子类实现,用于绘制控件内容 (pure virtual; draws the control’s appearance, implemented by each concrete control subclass).
|
||||
- `bool handleEvent(const ExMessage& msg)` – **纯虚函数**,由子类实现,处理输入事件消息,返回事件是否被控件消费 (pure virtual; handles input events for the control and returns true if the event is consumed)。
|
||||
- `void setIsVisible(bool show)` – 设置控件的可见性。传入 `false` 将隐藏控件,`true` 将显示控件。默认实现改变内部 `show` 状态并将控件标记为需要重绘 (Sets the control’s visibility. False to hide the control, true to show it. The base implementation updates the internal `show` flag and marks the control as needing redraw)。**(说明**:某些复合控件会重载此方法以同步子控件,例如 **TabControl** 对该方法进行了重载,实现显示/隐藏所有选项卡页) (Note: Some composite controls override this to also affect their children – e.g. **TabControl** overrides setIsVisible to show/hide all tab pages).
|
||||
- `void setDirty(bool dirty)` – 将控件标记为“脏”,表示需要重绘 (Marks the control as dirty, i.e., requiring a redraw). 默认实现设置内部标志,并**对容器控件**会将所有子控件一起标记 (Base implementation sets the internal flag; container controls like Canvas also mark child controls dirty).
|
||||
- `void setParent(Control* parent)` – 设置控件的父容器指针 (Assigns a parent control container to this control). 用于建立控件层次关系 (Used to establish parent-child relationship for nested controls).
|
||||
- `bool IsVisible() const` – 返回控件当前是否处于可见状态 (Checks if the control is currently set to be visible).
|
||||
- `std::string getId() const` – 获取控件的标识字符串ID (Returns the string identifier of the control).
|
||||
- `bool isDirty() const` – 判断控件是否被标记为需要重绘 (Returns whether the control is marked as dirty (needing redraw)).
|
||||
- `void setX(int x), setY(int y)` – 设置控件左上角的位置坐标 (Sets the control’s top-left position). 基类实现更新位置并将控件标记为脏,需要重绘 (Base implementation updates the coordinate and marks the control dirty)。某些容器控件(如 **Canvas**)会重载这些方法,以便在移动自身时同步更新子控件位置 (Some container controls like **Canvas** override these to also adjust children’s positions when the container moves).
|
||||
- `void setWidth(int w), setHeight(int h)` – 设置控件尺寸宽度和高度 (Sets the control’s width and height). 基类实现更新尺寸并将控件标记为需要重绘 (Base implementation updates the size and marks the control dirty)。
|
||||
- `int getX() const, getY() const, getWidth() const, getHeight() const` – 获取控件当前的全局坐标位置及宽高 (Returns the control’s current absolute X, Y coordinates and its width and height)。
|
||||
- `int getRight() const, getBottom() const` – 获取控件右边缘和下边缘的全局坐标 (Returns the coordinate of the control’s right edge (x+width) and bottom edge (y+height)).
|
||||
- `int getLocalX() const, getLocalY() const, getLocalWidth() const, getLocalHeight() const` – 获取控件相对于父容器的坐标和尺寸 (Returns the control’s position and size in its parent’s local coordinate space).
|
||||
- `int getLocalRight() const, getLocalBottom() const` – 获取控件右边缘和下边缘相对于父容器坐标系的位置 (Returns the local-space coordinates of the control’s right and bottom edges).
|
||||
- **布局相关方法 (Layout-related)**:
|
||||
- `void setLayoutMode(StellarX::LayoutMode mode)` – 设置控件的布局模式,如固定或锚定布局 (Sets the control’s layout mode (e.g., Fixed or AnchorToEdges)). 基类存储所选模式,窗口大小变化时会参考此设置调整控件 (The base class stores the mode; on window resize, this informs how the control should adjust, if at all).
|
||||
- `void setAnchor(StellarX::Anchor anchor1, StellarX::Anchor anchor2)` – 设置控件在锚定布局模式下的水平和垂直锚点 (Sets the horizontal and vertical anchor positions for AnchorToEdges layout mode). 例如可以将控件锚定在左上(Top+Left)以保持与窗口左上角的距离不变 (For example, anchoring Top+Left keeps the control’s top-left distance to the container constant).
|
||||
- `StellarX::Anchor getAnchor_1() const, getAnchor_2() const` – 获取当前设置的水平和垂直锚点值 (Returns the currently configured primary and secondary anchor).
|
||||
- `StellarX::LayoutMode getLayoutMode() const` – 获取当前布局模式 (Gets the current layout mode).
|
||||
- `void onWindowResize()` – 虚函数,窗口尺寸变化时由系统或父容器调用,用于让控件丢弃过期的背景缓存并适应新尺寸。基类实现默认丢弃背景快照并标记控件为脏,需要重绘 (Virtual function called when the window or parent container is resized. The base implementation discards any saved background snapshot and marks the control dirty for redraw)。大多数控件使用基类行为,但容器控件会在重载中调整子控件布局 (Most controls use the base behavior, but container controls override this to adjust child layouts).
|
||||
- **其他方法 (Other methods)**:
|
||||
- `void updateBackground()` – 主动释放旧背景快照并重新保存当前背景,用于在控件尺寸变化后更新缓存以防止显示错位。调用该方法会抓取控件当前位置的新背景 (This forces the control to discard any old background image and capture a new background snapshot, typically used after resizing to avoid misalignment of cached content).
|
||||
- `virtual bool model() const = 0` – **纯虚函数**,用于对话框控件检查自身是否为模态。非对话框类可实现为简单返回 false。(*Pure virtual function to indicate if the control is a modal dialog. Non-dialog controls implement this to always return false; only dialog-related classes override it to reflect modal state*).
|
||||
|
||||
**保护方法 (Protected Methods)**:*(通常供控件内部或子类使用)*
|
||||
|
||||
- `void requestRepaint(Control* parent)` – 向上请求父容器重绘。本控件或其子控件需要重绘时调用,遍历到最顶层容器触发实际重绘。基础实现为:如果存在父容器则递归通知父容器重绘,否则(无父,已到窗口根)调用 `onRequestRepaintAsRoot()` (Requests the parent to schedule a repaint of this control. Called when this control (or one of its children) becomes dirty and needs redraw. The base implementation propagates the request up the chain: if a parent exists, call parent’s requestRepaint, otherwise if at the root, call `onRequestRepaintAsRoot()` to trigger a top-level redraw).
|
||||
- `void onRequestRepaintAsRoot()` – 当控件是最顶层且需要重绘时,由框架调用以执行实际的刷新动作。典型实现是在窗口事件循环中检测到需要重绘时调用 (Called when the control is the root (no parent) and a repaint has been requested, to perform the actual redraw. In practice, the framework calls this during the window’s event loop when it detects a repaint is needed).
|
||||
- `void saveBackground(int x, int y, int w, int h)` – 保存控件区域在屏幕上的背景图像快照,用于实现擦除重绘时不留下残影。在控件首次绘制或移动/隐藏时抓取其背景 (Saves a snapshot of the background under the control’s area (at position x,y with size w×h) to facilitate restoring the background when the control is moved or removed, preventing ghosting artifacts).
|
||||
- `void restBackground()` – 恢复先前保存的背景快照,将其绘制回控件区域,从而擦除控件上一次绘制的内容。(Restores the previously saved background image to the control’s area, effectively erasing the control’s last drawn appearance. Typically used at the start of a redraw to clear old content.)
|
||||
- `void discardBackground()` – 丢弃并释放当前保存的背景快照。当控件或窗口尺寸变化、控件销毁时需要调用以防止使用失效的背景缓存。(Discards the stored background snapshot (if any). Called when the control or window size changes, or when the control is destroyed, to avoid using an outdated background cache.)
|
||||
- `void saveStyle()` / `void restoreStyle()` – 保存当前全局绘图状态(颜色、线型、填充等)并在绘制完成后恢复,以防止控件绘制改变全局状态。Control 基类实现了对 EasyX 图形状态的保存和恢复,每个控件在 `draw()` 开始时应调用 `saveStyle()`,结束时调用 `restoreStyle()` (Saves the current global drawing state (colors, line style, fill style, etc.) and restores it after drawing, to ensure the control’s drawing doesn’t alter the global state. The Control base provides these to wrap drawing code: call `saveStyle()` at the start of `draw()`, and `restoreStyle()` at the end).
|
||||
|
||||
**成员变量 (Member Variables)** *(除特殊说明外,均为 `protected` 访问权限 — Protected unless otherwise noted)*:
|
||||
|
||||
- `std::string id` – 控件的字符串ID标识符 (String identifier for the control). 可能用于调试或控件查找 (Often used for debugging or identifying controls).
|
||||
|
||||
- `int x, y` – 控件左上角的**全局**坐标 (X and Y coordinates of the control’s top-left corner in the **global (window) coordinate space**).
|
||||
|
||||
- `int width, height` – 控件当前的宽度和高度 (Current width and height of the control).
|
||||
|
||||
- `int localx, localy` – 控件左上角相对于父控件的局部坐标 (Local X, Y position relative to its parent control’s origin). 对于顶级控件(如窗口直接子控件),local 坐标通常与全局相同 (For top-level controls (children of the window), local coordinates are typically the same as global).
|
||||
|
||||
- `int localWidth, localHeight` – 控件在父容器坐标系下的尺寸大小 (Width and height of the control in the parent’s coordinate system). 初始化时等于控件自身宽高,但在父容器缩放或布局时可能用于计算 (Initialized to the control’s own width/height; used in layout calculations if needed).
|
||||
|
||||
- `Control* parent` – 父控件指针 (Pointer to the parent control). 为 `nullptr` 则表示本控件无父(可能是顶层元素)(If `nullptr`, this control has no parent, i.e., it’s a root element).
|
||||
|
||||
- `bool dirty` – 控件重绘标记。如果为 true 表示控件内容已改变或无效,需要在下一个周期重新绘制 (Dirty flag indicating the control needs to be redrawn. True means the control’s content has changed or invalidated and should be redrawn on the next cycle). 绘制完成后通常将 dirty 重置为 false (After drawing, this is reset to false until something changes again).
|
||||
|
||||
- `bool show` – 控件可见性标志。true 表示控件应显示,false 则控件被隐藏,绘制时应跳过 (Visibility flag: true if the control should be visible, false if hidden. Hidden controls are skipped during rendering).
|
||||
|
||||
- **布局属性 (Layout-related)**:
|
||||
|
||||
- `StellarX::LayoutMode layoutMode` – 控件的布局模式(Fixed 或 AnchorToEdges),决定窗口大小变化时的位置调整策略 (Specifies the control’s layout mode (Fixed or AnchorToEdges), determining how it behaves when the window is resized). 默认为 Fixed 固定布局。
|
||||
- `StellarX::Anchor anchor_1, anchor_2` – 控件相对父容器的锚点设置(如 Top/Bottom/Left/Right)。当 layoutMode 为 AnchorToEdges 时使用,表示控件的哪个边固定在父容器的哪个边上 (Anchor positions (primary and secondary) relative to parent container, used when layoutMode is AnchorToEdges. Determines which side(s) of the control remain fixed to which side of the parent). 例如 anchor_1=Top, anchor_2=Right 表示控件上边和右边相对父窗口距离保持不变 (e.g., Top + Right means the control’s top and right edges maintain constant distance from the parent’s top and right edges).
|
||||
|
||||
- **背景快照属性 (Background snapshot)**:
|
||||
|
||||
- `IMAGE* saveBkImage` – 保存的背景图像指针,用于在控件重绘前恢复覆盖区域背景 (Pointer to an IMAGE storing the snapshot of the background behind the control). 如果不为空,表示当前持有一份有效的背景缓存 (If not null, a valid background image is stored).
|
||||
- `int saveBkX, saveBkY` – 背景快照在屏幕上的保存起始坐标 (The X, Y coordinates of where the background snapshot was taken).
|
||||
- `int saveWidth, saveHeight` – 背景快照区域的宽度和高度 (The width and height of the saved background area).
|
||||
- `bool hasSnap` – 标记当前是否有有效的背景快照 (Flag indicating whether a valid background snapshot is currently stored).
|
||||
|
||||
- `StellarX::RouRectangle rouRectangleSize` – 控件圆角矩形参数。当控件形状为圆角矩形时,使用该结构决定圆角的大小 (Stores the control’s rounded rectangle corner sizes. Used when the control’s shape is a rounded rectangle to determine the curvature radii)。默认圆角宽高为20 (Defaults to 20 for both width and height, as defined in RouRectangle).
|
||||
|
||||
- **绘图状态缓存 (Drawing state caches)**: 为了在控件绘制时保存并恢复全局绘图状态,每个控件维护以下当前状态指针:
|
||||
|
||||
- `LOGFONT* currentFont` – 当前字体样式的备份指针 (Pointer to a LOGFONT storing the current font style before control drawing).
|
||||
- `COLORREF* currentColor` – 当前文本绘制颜色的备份 (Pointer storing current text color).
|
||||
- `COLORREF* currentBkColor` – 当前背景填充颜色的备份 (Pointer storing current background fill color).
|
||||
- `COLORREF* currentBorderColor` – 当前边框颜色的备份 (Pointer storing current border color).
|
||||
- `LINESTYLE* currentLineStyle` – 当前线型样式的备份 (Pointer storing current line style settings).
|
||||
|
||||
以上指针在控件销毁时会删除以释放资源。调用 `saveStyle()` 时,这些指针会指向保存的全局状态;`restoreStyle()` 则将全局绘图状态恢复并重置这些指针 (These are allocated to hold copies of global drawing settings; they are deleted in the Control destructor to free resources. When `saveStyle()` is called, the current global drawing settings are stored in these objects, and `restoreStyle()` reapplies them and resets the pointers).
|
||||
|
||||
- **禁用复制和移动 (Deleted copy/move)**: 为防止误用,Control 明确删除了复制构造和赋值运算符,以及移动构造和赋值 (Copy constructor and assignment operator, as well as move constructor and move assignment, are deleted to prevent copying or moving of controls)。控件对象不可被复制,只能以指针或智能指针方式管理 (Control objects cannot be copied; they should be managed via pointers or smart pointers).
|
||||
|
||||
- **构造函数与析构函数 (Constructors & Destructor)**:
|
||||
|
||||
- `Control(int x, int y, int width, int height)` – **受保护构造函数**,使用指定的位置和尺寸初始化控件基本属性。被派生类调用,用于设置控件初始的 local/global 坐标和宽高 (Protected constructor used by subclasses to initialize the control’s position (both local and global) and size).
|
||||
- `Control()` – **受保护默认构造函数**,初始化控件位置为 (0,0),宽高为 (100,100)。通常不会显式使用,除非子类需要默认大小的控件 (Initializes the control at origin (0,0) with a default size of 100×100. Typically invoked by subclass default constructors if needed).
|
||||
- `virtual ~Control()` – 析构函数,基类析构确保清理分配的资源。它删除并释放上述 `currentFont` 等绘图状态缓存指针,并调用 `discardBackground()` 释放背景快照 (Base destructor cleans up allocated resources, deleting the stored font, color, and line style objects, setting them to null, and calling `discardBackground()` to release any saved background image)。
|
||||
|
||||
**依赖关系 (Dependencies)**:
|
||||
|
||||
- **操作系统/图形库**:Control 使用 Win32 API 数据类型(如 `HWND`、`COLORREF` 等)以及 EasyX 图形库进行绘图管理。因此需要 Windows 平台支持 (The Control class includes Windows headers and depends on EasyX graphics library for drawing operations, hence it runs on Windows platform).
|
||||
- **框架核心类型**:Control 依赖 `CoreTypes.h` 中定义的 StellarX 命名空间枚举和结构,如 LayoutMode、Anchor、ControlShape、RouRectangle、ControlText 等,用于自身属性 (It relies on types defined in CoreTypes, such as LayoutMode, Anchor, ControlShape, RouRectangle, and ControlText for its properties and behavior).
|
||||
- **子类关系**:Control 是所有具体控件(按钮、标签、文本框、表格等)的基类。比如 **Button**, **Label**, **TextBox**, **Table** 等类都公开继承自 Control (All concrete control classes like Button, Label, TextBox, Table, etc., publicly inherit from Control). Control 提供的接口(draw、handleEvent等)由子类实现,实现各自的外观和行为 (The interfaces provided by Control (draw, handleEvent, etc.) are overridden by these subclasses to implement their specific appearance and behavior).
|
||||
- **容器关系**:尽管 Control 本身不包含子控件列表,但其派生的容器类(如 **Canvas**、**Window** 等)利用继承的接口管理子控件集合 (Control itself does not store child controls, but derived container classes like Canvas or Window use Control’s interface to manage child controls).
|
||||
|
||||
## 派生控件(Derived Controls)
|
||||
|
||||
以下类均继承自 **Control** 基类,表示常见的可视控件组件。这些控件实现了 Control 定义的接口,并根据需要添加自己的属性和方法。每个控件的继承关系和特定功能如下: *(The following classes all derive from the **Control** base class, representing common UI components. They implement the interfaces defined by Control and add their own properties and methods as needed. Each control’s inheritance and specific features are detailed below:)*
|
||||
|
||||
### Button(按钮控件)
|
||||
|
||||
**类名**:`Button`
|
||||
**继承**:继承自 Control (`class Button : public Control`)
|
||||
|
||||
**简要说明**:多功能按钮控件,支持多种状态和样式。提供完整的按钮交互,包括普通点击、切换开关、禁用等模式,并支持自定义外观(颜色、形状、填充)和鼠标悬停提示等。(*A versatile button control supporting multiple states and styles. It provides full button functionality including normal click, toggle (on/off) mode, and disabled state. The Button supports extensive customization of appearance (colors, shape, fill patterns) and features such as hover tooltips.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Button(int x, int y, int width, int height, const std::string& text, StellarX::ButtonMode mode = NORMAL, StellarX::ControlShape shape = RECTANGLE)` – **构造函数**,创建按钮,指定位置尺寸、显示文本,以及可选的按钮模式和形状。将按钮初始化为默认颜色配置 (Constructs a button at given position and size with the specified label text, and optional ButtonMode and shape. Initializes the button with default color settings for its states).
|
||||
- `Button(int x, int y, int width, int height, const std::string& text, COLORREF ct, COLORREF cf, StellarX::ButtonMode mode = NORMAL, StellarX::ControlShape shape = RECTANGLE)` – **构造函数**,创建具有自定义“按下/未按”颜色的按钮。参数 `ct` 为按钮被点击时颜色,`cf` 为按钮未点击时颜色 (Constructor to create a button with custom colors for the pressed (`ct`) and unpressed (`cf`) states).
|
||||
- `Button(int x, int y, int width, int height, const std::string& text, COLORREF ct, COLORREF cf, COLORREF ch, StellarX::ButtonMode mode = NORMAL, StellarX::ControlShape shape = RECTANGLE)` – **构造函数**,创建具有自定义“按下/未按/悬停”颜色的按钮。额外参数 `ch` 指定鼠标悬停时的按钮背景颜色 (Constructor to create a button with custom pressed (`ct`), unpressed (`cf`), and hover (`ch`) colors).
|
||||
- `~Button()` – **析构函数**,销毁按钮时释放可能加载的图像资源。例如如果按钮使用了自定义填充图像,将在析构时清理 (Releases any resources such as loaded images when the button is destroyed).
|
||||
- `void draw() override` – 绘制按钮外观。实现包括根据按钮状态(正常、悬停、按下、禁用)设置颜色和填充,并绘制按钮边框和文本等。按钮绘制支持多种形状,如果是圆形或椭圆按钮,会进行鼠标区域判定的特殊处理 (Renders the button. The implementation sets the appropriate colors/fill based on button state (normal, hover, pressed, disabled), draws the button’s border and filled shape, and then draws the text centered on the button. Different shapes (rectangle, rounded rect, circle, ellipse) are handled, including special hit-testing for circular/elliptical shapes).
|
||||
- `bool handleEvent(const ExMessage& msg) override` – 处理按钮的鼠标事件。包括检测鼠标按下、释放、移入、移出等,以更新按钮的 `click`(按下状态)和 `hover`(悬停状态),并触发相应回调 (Handles mouse events for the button. This includes detecting mouse down/up to update the `click` state (pressed or not), tracking mouse enter/leave to set the `hover` state, and triggering the appropriate callbacks when clicked or toggled).
|
||||
- 回调设置方法 (Callback setters):
|
||||
- `void setOnClickListener(std::function<void()>&& callback)` – 设置按钮在 NORMAL 模式下点击时执行的回调函数。当按钮每次被点击(鼠标按下然后松开)且模式为 NORMAL 时调用此回调 (Assigns a callback to be invoked when the button is clicked in NORMAL mode).
|
||||
- `void setOnToggleOnListener(std::function<void()>&& callback)` – 设置按钮在 TOGGLE 模式下从未选中切换为选中状态时的回调。当按钮切换到“按下/选中”状态时调用 (Sets the callback for when a toggle-mode button is toggled on (pressed state)).
|
||||
- `void setOnToggleOffListener(std::function<void()>&& callback)` – 设置按钮在 TOGGLE 模式下从选中切换为未选中状态时的回调。当按钮从按下恢复为弹起状态时调用 (Sets the callback for when a toggle-mode button is toggled off (released state)).
|
||||
- 模式和形状设置 (Mode/Shape settings):
|
||||
- `void setbuttonMode(StellarX::ButtonMode mode)` – 设置按钮的工作模式(NORMAL/TOGGLE/DISABLED)。更改模式会影响按钮行为:设置 TOGGLE 会使按钮保持按下状态,设置 DISABLED 会使按钮不可点击 (Changes the button’s operating mode; e.g., setting TOGGLE makes the button stay pressed when clicked, setting DISABLED grays it out and disables interaction).
|
||||
- `void setButtonShape(StellarX::ControlShape shape)` – 设置按钮形状(矩形、圆角矩形、圆形、椭圆等)。修改形状会影响按钮绘制的轮廓和鼠标命中区域 (Sets the geometric shape of the button. This changes how the button is drawn (e.g., with rounded corners or as a circle) and how hover/click hit-testing is calculated).
|
||||
- 外观属性设置 (Appearance setters):
|
||||
- `void setROUND_RECTANGLEwidth(int width)` / `void setROUND_RECTANGLEheight(int height)` – 若按钮形状为圆角矩形,设置其圆角椭圆的宽度或高度。用于调整圆角大小 (If the button’s shape is a rounded rectangle, these adjust the horizontal/vertical radius of the corner’s ellipse to change the corner roundness).
|
||||
- `void setFillMode(StellarX::FillMode mode)` – 设置按钮背景的填充模式。例如纯色填充、图案填充等 (Sets the fill mode for the button’s background, e.g., solid color, hatched pattern, image pattern, etc.).
|
||||
- `void setFillIma(StellarX::FillStyle style)` – 设置按钮背景填充的图案样式。只有当 FillMode 为 Hatched 有效,用于选择具体的填充图案 (Sets the hatched fill pattern for the button’s background, effective if FillMode is set to Hatched. Chooses which hatch style to use).
|
||||
- `void setFillIma(std::string imageName)` – 设置按钮背景填充为指定文件的图像。这会加载给定路径的图像用于填充按钮背景(FillMode 应设为 Pattern/DibPattern)(Uses an external image file to fill the button background. This will load the image from the given file path; the FillMode should be set to Pattern or DibPattern to use the image fill).
|
||||
- `void setButtonBorder(COLORREF color)` – 设置按钮边框颜色。更改边框绘制使用的颜色 (Sets the border color of the button’s outline).
|
||||
- `void setButtonFalseColor(COLORREF color)` – 设置按钮未被按下时的背景颜色。即按钮处于弹起状态的填充色 (Sets the background color for the button’s unpressed (false) state).
|
||||
- `void setButtonText(const char* text)` / `void setButtonText(std::string text)` – 设置按钮显示的文本标签。更改按钮上显示的文字内容 (Sets the label text displayed on the button).
|
||||
- `void setButtonClick(BOOL clicked)` – 强制设置按钮按下状态。传 true 则使按钮显示为按下状态,false 则恢复未按状态;通常用于程序控制 TOGGLE 模式按钮的状态 (Forces the button’s pressed state. True makes the button appear pressed (selected), false makes it unpressed. This is mainly useful for programmatically controlling the state of a TOGGLE mode button).
|
||||
- 查询方法 (Getters):
|
||||
- `bool isClicked() const` – 返回按钮当前是否处于按下(选中)状态。TOGGLE 模式下按下一次后该状态会保持,NORMAL 模式下每次点击会短暂为 true (Indicates whether the button is currently in the pressed state. In TOGGLE mode, this stays true after being clicked until toggled off; in NORMAL mode it is true only during the click).
|
||||
- `std::string getButtonText() const` / `const char* getButtonText_c() const` – 获取按钮的文本标签内容。提供 std::string 和 C 字符串两种形式 (Returns the text label of the button, as a std::string or C-string).
|
||||
- `StellarX::ButtonMode getButtonMode() const` – 获取按钮当前的模式(NORMAL/TOGGLE/DISABLED).
|
||||
- `StellarX::ControlShape getButtonShape() const` – 获取按钮当前形状类型.
|
||||
- `StellarX::FillMode getFillMode() const` – 获取按钮当前填充模式.
|
||||
- `StellarX::FillStyle getFillIma() const` – 获取按钮当前填充图案样式.
|
||||
- `IMAGE* getFillImaImage() const` – 如果按钮使用了图像填充,获取当前填充所用的 IMAGE 对象指针.
|
||||
- `COLORREF getButtonBorder() const` – 获取按钮边框颜色.
|
||||
- `COLORREF getButtonTextColor() const` – 获取按钮文字颜色 (Returns the text color used for the button’s label). *(说明:文字颜色存储在 `ControlText` 的 color 字段中,此方法便于直接获取)*(Note: The text color is actually stored in the `ControlText` struct as part of textStyle; this getter provides convenient access to it.)*.
|
||||
- `StellarX::ControlText getButtonTextStyle() const` – 获取按钮的文字样式结构副本。包含字体、字号、颜色等信息 (Returns a copy of the ControlText struct representing the button’s current text style, including font face, size, color, etc.).
|
||||
- **Tooltip 提示功能方法** (Button 提示工具条 API):
|
||||
- `void enableTooltip(bool on)` – 启用或禁用鼠标悬停提示功能。设为 true 则当鼠标悬停在按钮上时显示提示文本 (Enable or disable a tooltip that appears when the mouse hovers over the button). 关闭提示时会立即隐藏当前提示 (Disabling tooltips will hide any currently visible tooltip immediately).
|
||||
- `void setTooltipDelay(int ms)` – 设置提示出现的延迟时间(毫秒)。例如 1000 表示鼠标悬停1秒后显示提示 (Sets the delay in milliseconds before the tooltip is shown on hover. e.g., 1000 means the tooltip appears after 1 second of hovering).
|
||||
- `void setTooltipFollowCursor(bool on)` – 设置提示框是否跟随鼠标移动。如果为 true,则提示将出现在鼠标附近位置,并随鼠标移动更新 (Determines if the tooltip should follow the cursor. If true, the tooltip will appear near the cursor and move along with it).
|
||||
- `void setTooltipOffset(int dx, int dy)` – 设置提示框相对于鼠标位置的偏移。可调整提示框出现的位置,例如 (12, 18) 表示在鼠标坐标基础上右移12,下移18 像素 (Sets an offset for the tooltip’s position relative to the cursor. For example, (12, 18) will position the tooltip 12px to the right and 18px below the cursor).
|
||||
- `void setTooltipStyle(COLORREF textColor, COLORREF backgroundColor, bool transparent)` – 设置提示框文本颜色、背景颜色及是否背景透明。若 transparent 为 true,则提示背景不绘制矩形底色 (Configures the tooltip’s text color, background color, and transparency. If `transparent` is true, the tooltip has no opaque background, allowing underlying graphics to show through behind the text).
|
||||
- `void setTooltipText(const std::string& text)` – 设置按钮在 NORMAL 模式下的提示文本。当按钮未切换或不在TOGGLE模式时,将显示此提示内容 (Sets the tooltip text for the button (used in NORMAL mode or when the button is not toggling between two states)). 调用该函数会将 tipTextClick 设置为给定内容,并标记用户自定义标志以避免覆盖 (This updates the internal `tipTextClick` and flags that a custom tooltip is set by the user).
|
||||
- `void setTooltipTextsForToggle(const std::string& onText, const std::string& offText)` – 设置按钮在 TOGGLE 模式下不同状态的提示文本。第一个参数用于按钮选中(Pressed)时的提示,第二个用于未选中(Released)时的提示 (Defines two tooltip strings for a toggle-mode button: one when the button is toggled on (pressed) and one when toggled off).
|
||||
|
||||
**成员变量** *(Button的大部分成员为私有 private)*:
|
||||
|
||||
- `std::string text` – 按钮当前显示的文本 (The text label displayed on the button).
|
||||
- `bool click` – 按钮按下状态标志。true 表示按钮当前呈现为按下(TOGGLE模式下为选中),false 表示未按下。(Indicates if the button is in a pressed state. True when the button is currently pressed (or toggled on), false when not pressed.)
|
||||
- `bool hover` – 按钮悬停状态标志。true 表示鼠标当前在按钮区域内 (Indicates if the mouse cursor is currently hovering over the button).
|
||||
- `std::string cutText` – 裁剪后的文本。如果按钮文本过长需要裁剪显示,则存储裁剪结果 (A possibly truncated version of the text used for rendering if the full text does not fit in the button).
|
||||
- `bool needCutText` – 标志是否需要裁剪文本。当文本长度超出按钮宽度时设为 true (Flag indicating if text needs to be truncated to fit the button width).
|
||||
- `bool isUseCutText` – 标志当前是否使用裁剪后的文本显示。为 true 则表示 draw 时使用 `cutText` 而非完整 text (Indicates whether the button is currently using the truncated `cutText` for display instead of the full `text`).
|
||||
- `int padX, padY` – 文本绘制的内边距 (padding)。padX 是左右最小内边距像素,padY 是上下内边距 (Minimum horizontal (padX) and vertical (padY) padding in pixels around the button’s text). 默认 padX=6, padY=4.
|
||||
- **颜色设置 (Color settings)**:
|
||||
- `COLORREF buttonTrueColor` – 按钮被点击(选中)时的填充背景颜色 (Background color when the button is in pressed/true state).
|
||||
- `COLORREF buttonFalseColor` – 按钮未被点击时的填充背景颜色 (Background color when the button is in unpressed/false state).
|
||||
- `COLORREF buttonHoverColor` – 鼠标悬停在按钮上时的背景颜色 (Background color when the mouse is hovering over the button).
|
||||
- `COLORREF buttonBorderColor` – 按钮边框颜色,默认黑色 (The color of the button’s border; default is black).
|
||||
- `StellarX::ButtonMode mode` – 当前按钮模式(NORMAL/TOGGLE/DISABLED).
|
||||
- `StellarX::ControlShape shape` – 当前按钮形状(矩形、圆角矩形、圆形或椭圆等).
|
||||
- `StellarX::FillMode buttonFillMode` – 按钮填充模式(纯色、图案等),默认 Solid 纯色填充.
|
||||
- `StellarX::FillStyle buttonFillIma` – 按钮填充图案样式,默认 BDiagonal(右斜线网格),当 FillMode=Hatched 时使用.
|
||||
- `IMAGE* buttonFileIMAGE` – 填充按钮背景的图像指针(如使用自定义图片填充),默认为 nullptr.
|
||||
- **回调函数**:
|
||||
- `std::function<void()> onClickCallback` – 按钮点击回调函数指针 (Function to call on button click in normal mode).
|
||||
- `std::function<void()> onToggleOnCallback` – 按钮 TOGGLE 模式下切换为选中状态时的回调 (Function to call when a toggle button is toggled on).
|
||||
- `std::function<void()> onToggleOffCallback` – 按钮 TOGGLE 模式下切换为未选中状态时的回调 (Function to call when a toggle button is toggled off).
|
||||
- `StellarX::ControlText oldStyle` – 按钮文本原样式的备份 (Backup of the button’s text style before certain changes). 一些操作如禁用按钮时可能暂时修改文本样式(如加删除线),oldStyle 保存原始样式以便恢复 (For example, when disabling the button, the text might be styled with a strikethrough; `oldStyle` stores the original style so it can be restored when re-enabled).
|
||||
- `int oldtext_width, oldtext_height` – 记录上一次绘制时文本的宽度和高度 (Stores the width and height of the text from the last draw, used to detect if recalculation or re-cutting is needed).
|
||||
- `int text_width, text_height` – 当前文本的像素宽度和高度 (The measured pixel width and height of the current text string, used for centering and for truncation logic).
|
||||
- **Tooltip 提示相关**:
|
||||
- `bool tipEnabled` – 是否启用了鼠标悬停提示 (Whether the tooltip feature is enabled for this button).
|
||||
- `bool tipVisible` – 当前提示是否正显示 (Whether the tooltip is currently visible on screen).
|
||||
- `bool tipFollowCursor` – 提示框是否跟随鼠标移动 (Whether the tooltip should move with the cursor).
|
||||
- `bool tipUserOverride` – 用户是否自定义了提示文本 (Flag indicating if the user has overridden the tooltip text via setTooltipText; if false, default texts might be used for toggle states).
|
||||
- `int tipDelayMs` – 提示显示延迟毫秒数,默认1000ms (Delay in milliseconds before tooltip appears; default is 1000 ms).
|
||||
- `int tipOffsetX, tipOffsetY` – 提示框相对鼠标的偏移 (Tooltip offset from the cursor in X and Y).
|
||||
- `ULONGLONG tipHoverTick` – 记录鼠标开始悬停的时间戳 (Timestamp (in GetTickCount units) when the mouse started hovering over the button).
|
||||
- `int lastMouseX, lastMouseY` – 记录最近一次鼠标所在的位置,用于确定 tooltip 出现位置 (The last known mouse coordinates over the button, used for positioning the tooltip).
|
||||
- `std::string tipTextClick` – NORMAL 模式或 Toggle 未选中状态下使用的提示文本 (Tooltip text used in normal mode or when toggle button is in off state).
|
||||
- `std::string tipTextOn` – Toggle 按钮选中状态下使用的提示文本 (Tooltip text when the toggle button is in the on state).
|
||||
- `std::string tipTextOff` – Toggle 按钮未选中状态下使用的提示文本 (Tooltip text when the toggle button is in the off state).
|
||||
- `Label tipLabel` – 用于显示 tooltip 的 Label 控件对象。内部直接复用一个 Label 来呈现提示文本。tooltip 逻辑通过操作 tipLabel 的显示和内容实现 (A Label object used internally to render the tooltip text. The button’s tooltip functionality is implemented by configuring and showing this label near the cursor when needed).
|
||||
|
||||
**依赖**:Button 依赖 **Label** 控件来显示其 Tooltip 提示 (The Button class internally uses a **Label** control to display tooltips). 它还使用框架的 **ControlShape**、**FillMode**、**FillStyle** 等枚举定义不同的外观选项 (It uses framework enums like ControlShape, FillMode, FillStyle, etc., for its appearance settings). Button 是常用控件,通常作为对话框按钮或触发某动作的 UI 元素使用 (Button is a fundamental interactive control, commonly used in dialogs or as a trigger for actions in the UI).
|
||||
|
||||
### Label(标签控件)
|
||||
|
||||
**类名**:`Label`
|
||||
**继承**:继承自 Control (`class Label : public Control`)
|
||||
|
||||
**简要说明**:静态文本标签控件,用于显示只读文本内容。Label 不处理用户输入,主要作用是呈现文本,可支持背景透明。(*A static text label control for displaying read-only text. The Label does not handle user input and is mainly for presenting text, with support for transparent background.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Label()` – 默认构造函数,创建一个空文本的标签,使用默认字体颜色黑色、背景白色,默认大小适配文本 (Default constructor that creates a label with default text “标签” (Chinese for “Label”), black text color, white background. The size will be determined based on text content once set).
|
||||
- `Label(int x, int y, std::string text = "标签", COLORREF textColor = BLACK, COLORREF bkColor = RGB(255,255,255))` – 重载构造函数,在指定位置创建带初始文本的标签,可指定文字颜色和背景色。背景默认白色,text默认“标签” (Overloaded constructor to create a label at given position with initial text and optional text color and background color. The default text is “标签” (label), default text color black, default background white).
|
||||
- `void draw() override` – 绘制标签内容。实现为:如果 `textBkDisap` 为 false,则先绘制背景矩形(填充 `textBkColor`),然后设置文字颜色和字体,将 `text` 绘制在控件位置。如果 `textBkDisap` 为 true,则不绘制背景使其透明叠加 (Renders the label. If `textBkDisap` (background disappear flag) is false, it fills a rectangle with `textBkColor` as background; then draws the `text` at the label’s position using the current font and text color. If `textBkDisap` is true, no background rectangle is drawn, allowing whatever is behind the label to show through, achieving a transparent background effect). Label 根据其文本和样式自动适应大小 (The label’s drawn size adapts to the text content and style).
|
||||
- `void hide()` – 将标签隐藏。实现上相当于 `setIsVisible(false)`,并(可能)清除或不再绘制标签内容 (Hides the label, equivalent to calling setIsVisible(false) so it will no longer be drawn. This is a convenience method to quickly make the label invisible).
|
||||
- `void setTextdisap(bool transparent)` – 设置标签背景是否透明。传入 true 则开启背景透明模式(不绘制背景颜色),false 则有背景色填充 (Enables or disables transparent background for the label. True means the label will not draw any background (transparent), false means it will fill a background with its background color).
|
||||
- `void setTextBkColor(COLORREF color)` – 设置标签背景颜色。仅当背景不透明时有效,改变 Label 绘制时填充的背景矩形颜色 (Sets the background color of the label. Has effect only if the label is not set to transparent; changes the color used to fill behind the text).
|
||||
- `void setText(std::string newText)` – 设置标签显示的文本内容。更新文本后会自动调整控件大小以适应新文本长度,并将控件标记为需要重绘 (Changes the text displayed by the label. After setting, the label may resize itself to fit the new text (depending on implementation) and will be marked dirty for redraw).
|
||||
|
||||
**事件处理**:Label 重写了 `handleEvent` 但不做任何处理,总是返回 false。这意味着标签不拦截或消费任何事件,事件会传递给底层控件 (The Label overrides `handleEvent` to do nothing and always return false, meaning it does not consume any events and they will pass through it).
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- `std::string text` – 标签显示的文本内容 (The text string displayed by the label).
|
||||
- `COLORREF textBkColor` – 文本背景色 (Background color behind the text). 默认情况下在构造时设为白色或指定颜色 (Set in constructor, default white unless specified).
|
||||
- `bool textBkDisap` – 文本背景是否透明的标志。true 表示背景透明(不绘制背景色),false 表示绘制不透明背景 (Flag indicating if the label’s background is transparent. True means do not draw the background (transparent), false means fill background with `textBkColor`). 默认 false (Default is false, meaning background is drawn).
|
||||
- `StellarX::ControlText textStyle` – 标签文本的样式 (字体、字号、颜色等)。默认使用黑色字体、默认大小 (Defaults to a standard font (e.g., 12pt “微软雅黑”) and black color, can be modified to change font style or color). 开发者可以直接修改该结构体的字段(如 textStyle.color 等)然后调用 `draw()` 刷新,以改变标签文字外观 (Developers can modify this struct’s fields (e.g., textStyle.color for text color) and then redraw to change the label’s text appearance).
|
||||
|
||||
**依赖**:Label 主要依赖 **ControlText** 结构来存储字体和颜色信息,使用 Windows GDI(通过 EasyX)绘制文本。它无子控件且不处理事件,常作为静态显示用途 (The Label uses **ControlText** for font info and EasyX (GDI) to draw text. It has no children and performs no event logic, typically used for static display).
|
||||
|
||||
### TextBox(文本框控件)
|
||||
|
||||
**类名**:`TextBox`
|
||||
**继承**:继承自 Control (`class TextBox : public Control`)
|
||||
|
||||
**简要说明**:文本输入框控件,支持用户输入和只读显示两种模式,并提供可选的密码模式。内部集成 EasyX 的输入框功能来实现用户输入。(*A text box control that supports both user input mode and read-only display mode, as well as an optional password mode. It internally leverages EasyX’s input box capabilities for text input.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `TextBox(int x, int y, int width, int height, std::string text = "", StellarX::TextBoxmode mode = INPUT_MODE, StellarX::ControlShape shape = RECTANGLE)` – 构造函数,在指定位置创建文本框,初始化显示文本、模式和形状。默认模式为可输入,默认形状为有边框矩形 (Constructs a TextBox at the given position and size, with an initial text (which defaults to empty), a mode (defaults to input mode), and shape (defaults to a bordered rectangle)).
|
||||
- `void draw() override` – 绘制文本框外观。根据当前形状绘制文本框的边框和背景,然后绘制文本内容。若模式为密码模式,则绘制时会隐藏实际文字(例如用星号替代)(Renders the text box. It draws the rectangle (or chosen shape) for the text box border and background, then draws the text. If the mode is password, the actual characters are hidden (likely rendered as asterisks or bullets)).
|
||||
- `bool handleEvent(const ExMessage& msg) override` – 处理文本框的鼠标和键盘事件。当检测到鼠标点击文本框时,若模式为可输入,则调用 EasyX 提供的 `InputBox` 弹出文本输入对话框获取用户输入。获取输入后更新内部文本并标记重绘 (Handles events for the text box. If a mouse click is detected within the text box and the mode is INPUT_MODE, it uses EasyX’s InputBox (a system modal input dialog) to get user input. After the user enters text and closes the InputBox, the TextBox updates its internal text with the new value and marks itself dirty for redraw). 在 READONLY_MODE 下,点击不会触发输入框 (In READONLY_MODE, clicking does nothing).
|
||||
- `void setMode(StellarX::TextBoxmode mode)` – 设置文本框的工作模式(输入或只读或密码)。更改模式会影响交互行为:只读模式下禁止输入,密码模式下输入的文字以特殊符号显示 (Sets the TextBox’s mode. Changing the mode alters its behavior: in READONLY_MODE, user input is disabled; in PASSWORD_MODE, the text is masked when displayed).
|
||||
- `void setMaxCharLen(size_t len)` – 设置文本框允许输入的最大字符长度。限制用户通过 InputBox 输入的字符数量 (Sets the maximum number of characters that can be input in the text box. This limits the length of text accepted by the InputBox dialog).
|
||||
- `void setTextBoxshape(StellarX::ControlShape shape)` – 设置文本框的形状类型。可选矩形或圆角矩形等,但一般文本框使用矩形外观 (Sets the shape of the text box (rectangle, rounded rectangle, etc.). Typically text boxes use a rectangular shape).
|
||||
- `void setTextBoxBorder(COLORREF color)` – 设置文本框边框颜色。改变文本框四周边框的绘制颜色 (Changes the border color of the text box’s outline).
|
||||
- `void setTextBoxBk(COLORREF color)` – 设置文本框背景填充颜色。 (Sets the background fill color of the text box).
|
||||
- `void setText(std::string text)` – 设置文本框显示的文本内容。如果在 INPUT_MODE 下,可以程序matically预填内容;在 READONLY_MODE 下用于显示只读文本 (Sets the text content of the text box. In input mode, can be used to pre-fill text; in read-only mode, use it to display static text). 设置后标记控件需要重绘 (After setting, the control is marked dirty for redraw).
|
||||
- `std::string getText() const` – 获取文本框当前的文本内容。如果处于密码模式,返回的仍是实际文本而非掩码字符 (Returns the current text content of the text box. In password mode, this returns the actual stored text, not the masked display).
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- `std::string text` – 文本框当前包含的文本内容 (The text currently stored/displayed in the text box).
|
||||
- `StellarX::TextBoxmode mode` – 文本框当前模式(INPUT_MODE 可输入、READONLY_MODE 只读、PASSWORD_MODE 密码).
|
||||
- `StellarX::ControlShape shape` – 文本框外观形状(矩形、圆角矩形等).
|
||||
- `bool click` – 文本框点击状态标志。用于指示当前控件是否处于选中/激活(点击后正在输入)的状态。例如,click 为 true 时可能表示输入框正在获取输入 (A flag possibly indicating if the textbox is “active” or clicked. True might mean the text box was clicked and is awaiting input, though the exact usage depends on implementation details).
|
||||
- `size_t maxCharLen` – 文本框允许输入的最大字符数,默认10。超过此长度的输入会被截断 (Maximum number of characters allowed in the text box. Defaults to 10. Input beyond this length will be truncated or disallowed).
|
||||
- `COLORREF textBoxBkClor` – 文本框背景颜色,默认白色 (Background color of the text box, default is white).
|
||||
- `COLORREF textBoxBorderClor` – 文本框边框颜色,默认黑色 (Border color of the text box, default is black).
|
||||
- `StellarX::ControlText textStyle` – 文本框文本样式。决定文本绘制的字体、颜色等 (The font and text appearance settings for the text content of the text box). 可以调整其中字体大小以改变文本框中文字的显示大小 (Modifying this (e.g., font height) will change how the text appears inside the box).
|
||||
|
||||
**依赖**:TextBox 依赖 **CoreTypes** 中的 **TextBoxmode** 枚举来区分模式,还使用 EasyX 的 `InputBox` 函数进行实际文本输入对话框(在 Windows 环境下弹出模态输入窗口)。在图形上,它类似 **Button** 使用 **ControlShape** 控制边框形状。TextBox 提供了简单的文本输入能力,对于复杂文本编辑需要另行扩展 (Internally, the TextBox calls EasyX’s InputBox to get user input in a modal dialog, which is a limitation to Windows platform. Graphically, it uses ControlShape for its outline similar to Button. It is intended for basic text input; more complex text editing would require additional functionality beyond this control).
|
||||
|
||||
### Table(表格控件)
|
||||
|
||||
**类名**:`Table`
|
||||
**继承**:继承自 Control (`class Table : public Control`)
|
||||
|
||||
**简要说明**:高级表格控件,用于显示二维表格数据,支持分页显示和大量数据高效渲染。Table 提供表头、数据行分页、翻页按钮等完整功能,适合用于数据报告、记录浏览等场景。(*An advanced table/grid control for displaying tabular data. It supports pagination and efficient rendering of large data sets. The Table provides features such as headers, paginated data rows, navigation buttons for page flips, etc., making it suitable for reports, record browsers, and similar use cases.*)
|
||||
|
||||
**主要特性**: 自动分页计算、每页行数可配置、自适应列宽行高、翻页导航按钮、背景缓存优化绘制性能等。(*Key features include automatic pagination and page index calculation, configurable rows per page, auto-calculated column widths and row heights, navigation buttons for paging, and background buffering to optimize rendering performance.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Table(int x, int y)` – 构造函数,在指定位置创建一个空的表格控件。默认表格初始宽高由内容决定(通常在设置数据后计算)。默认每页显示行数为 5。创建后需调用 `setHeaders` 和 `setData` 来填充表头和数据 (Constructs a Table at the given position (top-left). The initial size may be determined after data is provided. By default, it shows 5 rows per page. After construction, one should call `setHeaders` and `setData` to populate the table).
|
||||
- `~Table()` – 析构函数,清理表格资源 (Destructor to clean up any resources. It will delete any dynamically allocated components, like navigation buttons or labels created internally).
|
||||
- `void draw() override` – 绘制表格当前页的内容。绘制流程包括表头、数据行以及页脚(页码和翻页按钮)。Table 内部通过辅助的私有 `drawHeader()`, `drawTable()`, `drawPageNum()`, `drawButton()` 方法分别绘制不同部分。(Draws the table for the current page. The drawing routine includes rendering the header row, the data rows for the current page, and the footer (page number display and navigation buttons). Internally it likely uses helper functions like `drawHeader()`, `drawTable()` (for data cells), `drawPageNum()`, and `drawButton()` for different sections.) Table 会根据内容自动计算列宽和行高,并支持隔行变色、高亮当前行等(如果实现了的话)(The Table calculates column widths and row heights based on content, and may support features like alternating row colors or highlighting if implemented).
|
||||
- `bool handleEvent(const ExMessage& msg) override` – 处理表格的事件。包括翻页按钮的点击事件,可能还有对行的点击选择等 (Handles events for the table, such as detecting clicks on the "Previous" or "Next" page buttons, and potentially row click events for selection if such feature exists). 当点击翻页按钮时,会更新 `currentPage` 并触发重绘显示新页数据 (On clicking navigation buttons, it updates `currentPage` and triggers a redraw to display the new page of data).
|
||||
- 设置数据与外观的方法 (Data and appearance setters):
|
||||
- `void setHeaders(std::initializer_list<std::string> headers)` – 设置表格表头列名。传入一个字符串列表,每个元素作为一列的标题。调用后会自动计算列宽,并标记需要重绘表头 (Sets the table’s header labels. The initializer_list of strings provides a title for each column. This triggers a recalculation of column widths and marks the table for redraw).
|
||||
- `void setData(std::vector<std::string> data)` – 设置表格数据。**注意**: 这里参数类型可能是错误,应为 `std::vector<std::vector<std::string>>` 或初始化列表(见下)(Note: The signature in code appears to be `setData(std::vector<std::string>)` which is likely a typo; actual implementation probably expects a 2D structure. Use the initializer_list overload for clarity).
|
||||
- `void setData(std::initializer_list<std::vector<std::string>> data)` – 设置表格数据。传入一个列表,每个元素是代表一行的字符串向量。Table 将保存数据并自动分页计算 `totalPages` 和 `currentPage` 等 (Sets the table data by providing an initializer_list of rows, where each row is a vector of strings for the columns. The table stores this data and computes `totalPages` based on rowsPerPage, resetting currentPage to 1).
|
||||
- `void setRowsPerPage(int rows)` – 设置每页显示的行数。改变此值会重新计算总页数并调整当前显示 (Sets how many rows are displayed per page. Changing this will recalculate `totalPages` and adjust the current page if needed).
|
||||
- `void showPageButton(bool show)` – 设置是否显示翻页按钮。如果数据量小仅一页,开发者可选择隐藏翻页控制 (Determines whether the page navigation buttons (prev/next) are visible. If the data fits on one page, one might hide the navigation controls).
|
||||
- `void setTableBorder(COLORREF color)` – 设置表格边框颜色(单元格网格线颜色)。改变表格绘制时单元格边框和外框的颜色 (Sets the color used for the table grid lines and border).
|
||||
- `void setTableBk(COLORREF color)` – 设置表格背景颜色。作为单元格背景的底色 (Sets the background color used for the table’s cells).
|
||||
- `void setTableFillMode(StellarX::FillMode mode)` – 设置表格单元格背景填充模式。可选择纯色或图案填充 (Sets the fill mode for the table cells background, e.g., solid fill or hatched pattern).
|
||||
- `void setTableLineStyle(StellarX::LineStyle style)` – 设置表格线型样式。用于单元格边框线,可选实线、虚线等 (Sets the line style for the table grid lines (cells borders), e.g., solid, dashed).
|
||||
- `void setTableBorderWidth(int width)` – 设置表格网格线和外边框的宽度(像素)(Sets the width (thickness) of the table’s grid lines and border in pixels).
|
||||
- `void clearHeaders()` – 清空表头。将 headers 列表置空,并标记需要重绘 (Clears all header labels. After calling, the table will have no columns defined until new headers are set).
|
||||
- `void clearData()` – 清空表格数据。移除所有数据行,重置当前页等 (Clears all table data rows and resets pagination state).
|
||||
- `void resetTable()` – 清空表头和数据。相当于依次调用 clearHeaders() 和 clearData(), 将表格恢复初始空状态 (Clears both headers and data, resetting the table to an initial empty state).
|
||||
- `void onWindowResize() override` – 当容器窗口大小变化时调用。实现为丢弃背景快照并标记表格为脏,需要在新尺寸下重绘 (Called when the window is resized. The Table’s implementation likely discards any saved background (if using caching) and marks itself dirty to redraw according to the new size).
|
||||
- 查询方法 (Getters):
|
||||
- `int getCurrentPage() const` – 获取当前页码(从1开始计数).
|
||||
- `int getTotalPages() const` – 获取总页数.
|
||||
- `int getRowsPerPage() const` – 获取每页显示的行数设置.
|
||||
- `bool getShowPageButton() const` – 获取当前是否设置为显示翻页按钮.
|
||||
- `COLORREF getTableBorder() const` – 获取表格边框(网格线)颜色.
|
||||
- `COLORREF getTableBk() const` – 获取表格背景颜色.
|
||||
- `StellarX::FillMode getTableFillMode() const` – 获取表格当前填充模式.
|
||||
- `StellarX::LineStyle getTableLineStyle() const` – 获取表格当前线型样式.
|
||||
- `std::vector<std::string> getHeaders() const` – 获取当前表头列表的副本.
|
||||
- `std::vector<std::vector<std::string>> getData() const` – 获取当前表格数据的副本.
|
||||
- `int getTableBorderWidth() const` – 获取表格边框/网格线宽度.
|
||||
- `int getTableWidth() const, int getTableHeight() const` – 获取表格当前总宽度和总高度。这通常对应绘制时计算出的整个表格占用尺寸,包括表头和页脚 (Returns the overall width and height of the table as currently rendered, including header and footer areas. These are typically calculated during the last draw).
|
||||
|
||||
**成员变量** *(主要为私有属性)*:
|
||||
|
||||
- `std::vector<std::vector<std::string>> data` – 表格数据存储,按行列组织的字符串二维数组。每个内部 `std::vector<std::string>` 代表一行的数据,所有行长度应与 headers 列数匹配 (Stores the table’s data in a 2D vector of strings (rows × columns). Each inner vector represents one row. The number of elements in each row should match the number of header columns).
|
||||
- `std::vector<std::string> headers` – 表格列标题列表。长度即列数 (List of column headers. The size of this vector defines the number of columns in the table).
|
||||
- `std::string pageNumtext` – 页码标签文本模版。默认值 "页码标签",可能用于显示当前页/总页的信息 (A template or base text for the page number label, default "页码标签". This might be combined with current page info to display pagination status like “第 X 页/共 Y 页”).
|
||||
- `int tableBorderWidth` – 表格边框和网格线宽度,默认值来自 `TABLE_DEFAULT_BORDER_WIDTH` 宏,通常为1 (Thickness of table grid lines and border. Default comes from TABLE_DEFAULT_BORDER_WIDTH, typically 1 pixel).
|
||||
- `std::vector<int> colWidths` – 每列宽度像素值的数组。绘制时每列的起始位置和单元格矩形基于此计算 (Array of pixel widths for each column. These are calculated from header/text lengths and used to layout the table cells).
|
||||
- `std::vector<int> lineHeights` – 每行高度像素值的数组。通常各行高度相同,由字体高度和 padding 决定;也可能表头行和数据行区分 (Array of heights for each row. Often uniform for all data rows and possibly a different height for header; determined by text height and vertical padding).
|
||||
- `int rowsPerPage` – 每页显示行数,默认 5.
|
||||
- `int currentPage` – 当前页码,默认 1(第一页).
|
||||
- `int totalPages` – 总页数,默认 1。根据数据行数和 rowsPerPage 计算得到 (Total number of pages, computed based on number of data rows and rowsPerPage).
|
||||
- **特性开关**:
|
||||
- `bool isShowPageButton` – 是否显示翻页按钮,默认 true.
|
||||
- `bool isNeedDrawHeaders` – 是否需要绘制表头标志,暂未使用(代码注释为“暂时废弃”).
|
||||
- `bool isNeedCellSize` – 是否需要计算单元格尺寸标志。可能用于延迟计算优化 (Flag indicating if cell sizes need recalculation. Possibly used to optimize and avoid recalculating cell metrics on every draw).
|
||||
- `bool isNeedButtonAndPageNum` – 是否需要计算翻页按钮和页码信息标志。类似地用于控制是否更新页脚 (Flag indicating if navigation buttons and page number label need to be recalculated/positioned. Could be used to skip re-layout of footer if not needed).
|
||||
- **导航控件**:
|
||||
- `Button* prevButton` – “上一页”按钮指针。指向 Table 内部创建的 Button 对象,用于翻页到前一页。nullptr 表示未创建或隐藏 (Pointer to the "Previous Page" button control. Created internally by the Table for pagination. If nullptr, the button is not present or not needed).
|
||||
- `Button* nextButton` – “下一页”按钮指针。用于翻到下一页 (Pointer to the "Next Page" button).
|
||||
- `Label* pageNum` – 页码显示的标签指针。用于显示当前页/总页信息 (Pointer to a Label that displays the page number text, e.g., "第 X 页/共 Y 页").
|
||||
- **内部坐标缓存**(用于绘制过程的临时值):
|
||||
- `int dX, dY` – 当前单元格绘制的起始坐标 (likely "draw X/Y": the starting x,y for drawing cells). 初始化为表格区域左上角 (Initialized to x,y of the table). 绘制过程中更新以逐行逐列推进 (These are updated as the table draws each cell to track the current drawing position).
|
||||
- `int uX, uY` – 当前单元格绘制的结束坐标 (likely "end X/Y": maybe unused or similar to dX,dY as drawing coordinates).
|
||||
- `int pX, pY` – 页码标签 Label 的左上角坐标 (Coordinates for where the page number label is placed).
|
||||
- **颜色和样式**:
|
||||
- `StellarX::FillMode tableFillMode` – 表格单元格填充模式, 默认 Solid。
|
||||
- `StellarX::LineStyle tableLineStyle` – 表格网格线线型, 默认 Solid 实线。
|
||||
- `COLORREF tableBorderClor` – 表格边框和网格线颜色, 默认黑色 (RGB(0,0,0))。
|
||||
- `COLORREF tableBkClor` – 表格背景底色, 默认白色 (RGB(255,255,255))。
|
||||
- `StellarX::ControlText textStyle` – 表格内容文本样式。用于设置表格单元格中文字的字体和颜色,默认继承自 ControlText 默认值 (Determines font and color for text drawn in the table’s cells). 可以修改例如字体大小以调整表格内容字号 (Can be adjusted to change text size of table content).
|
||||
|
||||
**依赖**:Table 控件内部组合使用 **Button**(翻页按钮)和 **Label**(页码显示)控件来实现完整功能,因此它依赖这些子控件的接口来处理事件和绘制文字。Table 作为容器包含这些控件并在翻页时对它们进行布局和更新 (The Table internally composes **Button** controls for navigation and a **Label** for page number, thus it relies on their functionality for event handling and text rendering. The Table acts as a container for these controls, positioning and updating them as pages change). Table 还会使用 GDI 绘制单元格边框和背景,对性能要求高时利用了背景缓存等优化 (The Table uses GDI (EasyX) to draw cell grids and background, and likely employs background buffering optimizations to handle large data efficiently).
|
||||
|
||||
## 复合控件(Composite Controls)
|
||||
|
||||
复合控件是指包含其他控件作为子元素,实现更复杂界面功能的控件。例如 TabControl 包含多个页面 Canvas 和对应的按钮,Dialog 包含文本、按钮等控件。下面是这些复合控件的接口说明: *(Composite controls contain other controls as child elements to provide more complex UI functionality. For example, TabControl contains multiple Canvas pages and their respective tab buttons; Dialog contains text and button controls. Below are the interface details of these composite controls:)*
|
||||
|
||||
### TabControl(选项卡控件)
|
||||
|
||||
**类名**:`TabControl`
|
||||
**继承**:继承自 Canvas (`class TabControl : public Canvas`)
|
||||
|
||||
**简要说明**:选项卡容器控件,可在单一界面区域内承载多个子页面,通过页签(标签按钮)进行切换。TabControl 提供类似选项卡对话框的界面,每个选项卡有一个标题按钮和对应的内容区域。(*A tabbed container control that can hold multiple child “pages” in the same area and switch between them using tab header buttons. It provides a tabbed dialog-like interface where each tab has a header button and an associated content area.*)
|
||||
|
||||
**功能特点**:TabControl 支持将页签栏放置在容器的不同位置(上、下、左、右)。每个选项卡由一个按钮(作为页签)和一个 Canvas 容器(作为页面内容)组成。一次仅显示一个选项卡的内容,其余页面隐藏。TabControl 自动管理页签按钮的布局和当前激活页内容的显示切换。(*The TabControl allows the tab bar to be placed at the top, bottom, left, or right of the control. Each tab consists of a Button (tab header) and a Canvas (page content). Only one page is visible at a time, with others hidden. The TabControl automatically handles laying out the tab header buttons and toggling the visibility of the page content for the active tab.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `TabControl()` – 默认构造函数,创建一个默认大小的选项卡控件。内部调用 Canvas 基类构造将位置设为 (0,0), 宽高默认100×100,并设置控件ID为 "TabControl" (Calls the Canvas constructor to initialize a TabControl at (0,0) of default size, and sets its id to "TabControl").
|
||||
- `TabControl(int x, int y, int width, int height)` – 构造函数,在指定位置和尺寸创建一个选项卡控件。初始化后无选项卡,需要通过 `add` 方法添加页面 (Creates a TabControl at specified position with given width and height. Initially it contains no tabs; use `add()` to add tab pages).
|
||||
- `void add(std::pair<std::unique_ptr<Button>, std::unique_ptr<Canvas>>&& control)` – **添加选项卡页面**,将一个按钮-页面对添加为新的选项卡。`pair.first` 是页签按钮,`pair.second` 是对应内容 Canvas。调用该方法后,TabControl 会负责管理该按钮和页面的布局与显示 (Adds a new tab to the TabControl given a pair of a Button (tab header) and a Canvas (tab page content). After adding, the TabControl takes ownership and will manage the layout and display of the tab’s button and page). 调用后自动调整所有页签按钮大小并初始化新页面坐标,将新选项卡默认设置为隐藏内容。(The method will recalc the size of all tab buttons, position the new page, and by default hide the new page’s content so that it’s not shown until activated.)
|
||||
- `void add(std::string tabText, std::unique_ptr<Control> control)` – **向已有选项卡添加子控件**。此重载用于将一个新的控件添加到已有的某个选项卡页面内。`tabText` 指定目标选项卡的标题文本,`control` 是要添加的控件指针。调用时会在匹配标题的选项卡页面 Canvas 内添加该控件,并保持其相对坐标 (Adds a control to one of the existing tab pages. The `tabText` identifies which tab’s page to add to (by matching the tab’s title text), and `control` is the new child control to add. The method sets the new control’s parent to the target page’s Canvas and adjusts its coordinates to be relative to that page). 如果 `tabText` 没找到对应页签,则不执行操作 (If no tab with the given title is found, the call does nothing).
|
||||
- `void setTabPlacement(StellarX::TabPlacement placement)` – 设置选项卡页签栏的位置。可以在 TabControl 的顶部、底部、左侧或右侧显示页签。调用后立即重新布局页签和页面区域 (Sets the placement of the tabs (Top, Bottom, Left, or Right). Recomputes the layout of tab header buttons and page content areas accordingly).
|
||||
- `void setTabBarHeight(int height)` – 设置页签栏的高度(或宽度,如果在左/右侧)。调整这个值可以改变页签按钮的大小。默认高度有最小值限制 (Sets the height of the tab bar (if tabs are top/bottom) or width (if tabs are left/right)). This effectively changes the size of each tab button on that dimension. There is an internal minimum enforced for tab button size to ensure usability (e.g., `BUTMINHEIGHT`, `BUTMINWIDTH`).
|
||||
- `void setActiveIndex(int index)` – 显式设置当前激活的选项卡索引。索引从0开始。若指定索引有效且不等于当前激活,则将对应页签按钮设为点击状态,切换显示该页内容。如果在首次绘制前调用,则会将此索引存为默认激活页 (Sets the active tab by index (0-based). If called after the control is shown and the index is valid (and different from current), it programmatically “clicks” that tab’s button to activate the page. If called before the first draw (initialization phase), the index is stored as the default to activate on first render rather than switching immediately).
|
||||
- `int getActiveIndex() const` – 获取当前激活的选项卡索引。如果没有页签被选中则可能返回 -1 (Returns the index of the currently active tab. If no tab is active, it returns -1).
|
||||
- `int count() const` – 获取当前选项卡总数量.
|
||||
- `int indexOf(const std::string& tabText) const` – 根据页签标题文本查找对应的索引。如果存在多个同名页签,返回第一个匹配的索引;如未找到则返回 -1 (Returns the index of the tab with the given title text. If multiple tabs have the same title, returns the first match. Returns -1 if not found).
|
||||
- `void setIsVisible(bool visible) override` – 重载自 Canvas:设置整个 TabControl(以及其中所有页签按钮和页面)的可见性。如果设置为可见,则只显示当前激活的页面,但**所有**页签按钮都会显示;如果设置为不可见,则页签和页面全部隐藏。此外,该实现会确保隐藏状态下子页面不会遗留背景快照 (Overrides Canvas::setIsVisible to show/hide the TabControl along with all its tabs and pages. When made visible, all tab header buttons are shown and only the currently active page’s Canvas is shown (others remain hidden); when invisible, all tabs and pages are hidden. It also handles clearing out saved snapshots for hidden pages to prevent stale visuals).
|
||||
- `void onWindowResize() override` – 当父窗口尺寸改变时调用。实现为:调用 Control 基类的 onWindowResize() 丢弃自身背景,然后重新计算页签栏和页面区域布局。之后对每个页签按钮和页面调用各自 onWindowResize() 使其内容也调整 (On parent window resize, the TabControl’s override first calls Control::onWindowResize() to discard its background and mark dirty. It then recalculates the tab bar and page layout (size and position) for the new control size. Finally it forwards the onWindowResize call to each tab’s Button and Canvas so they can adjust their internals if needed).
|
||||
- `void setDirty(bool dirty) override` – 重载自 Control:将 TabControl 及其所有子页签按钮和页面的脏标记设为给定值。通常在需要整组重绘时调用 (Overrides Control::setDirty to set the dirty flag for the TabControl itself and all its child tab buttons and page Canvases to the given value (true/false). This is useful to invalidate or validate the entire tab set at once).
|
||||
- `void requestRepaint(Control* parent) override` – 重载自 Control:处理 TabControl 自身或子控件请求重绘的逻辑。如果 `parent` 参数就是当前 TabControl 本身,则表示一次针对整个选项卡控件的重绘请求;实现中会检查每个子控件(按钮和页面)的 dirty 状态,将需要重绘的子控件各自绘制一遍。否则(parent 不是本控件),调用基类 Canvas 的 onRequestRepaintAsRoot() 让更高层容器处理。(Overrides Control::requestRepaint. If the `parent` passed in is this TabControl itself (meaning a repaint of the whole tab control is requested), the implementation iterates through all tab pairs and if a tab’s Button or Canvas is dirty and visible, it calls their draw() to repaint them. If `parent` is not this (meaning the request is bubbled further up), it defers to the base behavior by calling onRequestRepaintAsRoot().) 这一特殊实现确保当 TabControl 本身重绘时,其子页面内容也会刷新 (This ensures that when the TabControl is repainted, all visible child content is also redrawn).
|
||||
|
||||
**事件处理**:TabControl 实现自己的 `handleEvent` 逻辑,将事件分发给当前页的子控件或页签按钮。具体而言,当鼠标点击一个页签按钮时,相应按钮会触发回调使该选项卡切换为激活状态;TabControl::handleEvent 会优先将事件传给所有页签按钮(通常是排列在最上层)检查是否有按钮点击。如果没有页签按钮消费事件,则再把事件传递给当前激活的页面 Canvas 里的子控件。这样实现当用户点击不同区域时由不同元素响应 (The TabControl’s event handling sends incoming messages first to the tab header buttons (which are typically drawn above the page content) to see if any button consumes the event (e.g., a click on a tab). If none of the buttons handle the event, it then forwards the event to the currently visible page’s Canvas (which in turn dispatches to its child controls). This ensures the correct element responds depending on where the user clicked).
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- `std::vector< std::pair< std::unique_ptr<Button>, std::unique_ptr<Canvas> > > controls` – 存储选项卡的容器,包含多个 (按钮, 页面Canvas) 对。每个 pair 的 first 是页签按钮,second 是对应内容页面 (Vector holding the tab definitions: each element is a pair where first is the tab header Button and second is the page Canvas for that tab). 这个容器是 TabControl 最重要的结构,用于迭代布局和事件处理 (This is central to TabControl’s operation for iterating through tabs for layout, drawing, and event dispatch).
|
||||
- `int tabBarHeight` – 页签栏高度(或宽度),用于决定页签按钮尺寸。默认值可能为某个常量,例如30像素 (Height of the tab bar. Determines the size of tab header buttons in the minor axis. Default might be around 30px, ensuring a minimum usable size). 可以通过 `setTabBarHeight` 修改。
|
||||
- `StellarX::TabPlacement tabPlacement` – 当前页签栏位置(Top/Bottom/Left/Right)。默认应该为 Top (Default placement likely Top). 改变该值会在下一次布局时把页签移动到相应边 (Changing this will re-position the tabs on the specified side on next layout recalculation).
|
||||
- `bool IsFirstDraw` – 标记是否尚未绘制过(首次绘制标志)。初始为 true,第一次调用 draw() 后置 false (A flag indicating whether the TabControl has been drawn for the first time or not. Initialized to true, set to false after the first draw). 用于处理 `defaultActivation` 逻辑,在首次绘制时激活预设的选项卡.
|
||||
- `int defaultActivation` – 默认激活选项卡索引。初始可能为 -1,表示未指定。如果在控件显示前通过 `setActiveIndex` 调用设置了一个索引,则该值保存那个索引,在首次绘制时相应页签会被激活。(Stores an index of a tab to activate on first draw. Default -1 meaning none specified. If `setActiveIndex` is called before the control is drawn, this captures the desired active tab, and during the first `draw()` call the TabControl will activate that tab).
|
||||
- **常量**:内部定义的最小按钮宽高常量,如 `BUTMINWIDTH`, `BUTMINHEIGHT`,用于确保无论 TabControl 尺寸多小,每个页签按钮都有合理可点击大小。这些常量可能定义为例如 50 像素宽、20 像素高 (There are internal constants for minimum tab button dimensions (e.g., `BUTMINWIDTH`, `BUTMINHEIGHT`) to guarantee each tab remains a clickable size even if the control is very small).
|
||||
- *(其余布局相关变量和 Canvas 基类的成员,如 x, y, width, height, 以及 Canvas 提供的 children 列表,都通过继承获得)*(Other layout and inherited members: since TabControl extends Canvas, it inherits all Canvas members like x, y, width, height, and the vector of child controls from Canvas. However, in TabControl, instead of using the inherited `controls` vector from Canvas, it manages its own vector of pair for tabs. The Canvas’s own child list might remain empty or unused in this context.)*
|
||||
|
||||
**继承和依赖**:TabControl 直接继承自 **Canvas**(即它本身就是一个可包含控件的画布),这意味着 TabControl 拥有 Canvas 的所有能力(背景绘制、子控件容器等),并进一步组合了多个 Button 和 Canvas 子控件来形成选项卡结构。**Button** 用于页签,**Canvas** 用于页内容,因此 TabControl 强依赖 Button 和 Canvas 的接口 (TabControl inherits from **Canvas**, giving it container capabilities. It composes **Button** controls as tab headers and **Canvas** controls as pages. It heavily relies on the Button interface (for toggling and event callbacks) and Canvas for holding page content). TabControl 本身不依赖外部系统资源,除了通过父 Window 获取尺寸变化事件。作为复杂控件,TabControl 提供了一个在桌面 GUI 中组织多页面内容的便捷组件 (As a composite control, TabControl provides an easy way to organize multi-page content in a desktop GUI, without relying on OS-level tabs).
|
||||
|
||||
### Dialog(对话框控件)
|
||||
|
||||
**类名**:`Dialog`
|
||||
**继承**:继承自 Canvas (`class Dialog : public Canvas`)
|
||||
|
||||
**简要说明**:模态/非模态对话框控件,提供标准消息框的界面和功能。Dialog 可以独立弹出,包含标题、消息文本和一组按钮(如确定、取消等),并支持阻塞主窗口(模态)或非阻塞回调两种模式。(*A dialog box control supporting both modal and modeless operation, providing a standard message box UI with a title, message text, and a set of buttons (e.g., OK, Cancel). The Dialog can be shown modally (blocking the main window) or non-modally with a callback for results.*)
|
||||
|
||||
**主要特性**: 支持多个预定义类型(MessageBoxType 枚举的六种组合按钮),可以根据需要显示相应按钮组合;支持自动根据消息文本长度换行及调整对话框尺寸;在模态模式下弹出会阻塞调用线程直到对话框关闭,在非模态模式下则通过回调通知结果;对话框绘制时会保存背景并在关闭时恢复,以实现半透明效果或防止闪烁。(*Key features include support for several predefined configurations of buttons (according to the MessageBoxType enum), automatic text wrapping and dialog resizing based on content, modal display (blocking until closed) vs. modeless with callbacks, and background saving/restoring to prevent flicker or allow transparency effects.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Dialog(Window& hWnd, std::string text, std::string message = "对话框", StellarX::MessageBoxType type = OK, bool modal = true)` – 构造函数,创建一个对话框实例。参数:`hWnd` 父窗口引用,用于在该窗口中央显示对话框;`text` 对话框显示的消息内容;`message` 对话框标题文本(默认为“对话框”);`type` 对话框类型(决定按钮组合,默认为 OK 单按钮);`modal` 指定是否模态 (true=模态)。构造函数内会根据类型创建对应的按钮集合、关闭按钮等,并计算对话框初始尺寸 (The constructor sets up the dialog: it stores a reference to the parent Window, saves the provided message text and title, creates the appropriate buttons according to the specified type, adds a close (“X”) button, and computes an initial size based on text length and number of buttons. If `modal` is true, the Dialog is configured to block input to the parent window when shown).
|
||||
- `~Dialog()` – 析构函数,负责销毁对话框内创建的控件(按钮、标签等)并释放背景缓存等资源。若对话框在非模态显示且尚未关闭,析构时应通知父窗口清理引用 (Destroys all child controls created inside the dialog (buttons, labels) and releases any saved background images. If the dialog was modeless and still open, the destructor ensures any references in the parent are cleared).
|
||||
- `void draw() override` – 绘制对话框。Dialog 继承自 Canvas,draw() 实现包含:绘制对话框背景矩形(使用背景颜色 backgroundColor 和边框颜色 borderColor,通常为一个带边框的圆角矩形或矩形);绘制标题栏(包括标题文本Label和关闭按钮);绘制消息文本内容(自动换行后的多行);绘制底部功能按钮区域(按照 type 创建的确定/取消等按钮)。绘制过程中处理背景快照以在出现对话框时保存被遮挡的内容 (The Dialog’s draw method draws the dialog’s background and border (often a rounded rectangle with borderColor), draws the title bar (title text label and close button at the top), renders the message text (splitting it into lines to fit width), and draws the bottom area with the action buttons as specified by the dialog type. It uses background snapshot routines to save what's behind the dialog when it appears and restore upon closing to prevent artifacts).
|
||||
- `bool handleEvent(const ExMessage& msg) override` – 处理对话框的事件。包括:点击关闭按钮时将关闭对话框;点击功能按钮(如确定、取消等)时,将根据按钮设定设置结果枚举,并关闭对话框(模态则结束阻塞返回结果,非模态则通过回调); 以及拖动窗口(如果实现了窗口拖动)(Handles events such as clicks on the close button (triggers Close()), clicks on any of the action buttons (sets the result accordingly and closes the dialog), and possibly window dragging if the title bar is draggable). 在模态情况下,handleEvent 内部可能会自己运行消息循环直到对话框关闭 (In modal mode, handleEvent might not be used in the typical way since control is in a separate loop; but for modeless, it ensures events are passed to child controls).
|
||||
- **设置和获取**:
|
||||
- `void SetTitle(const std::string& title)` – 设置对话框标题文本。更新内部 `titleText` 并刷新标题 Label (Changes the dialog’s title. Updates the internal `titleText` and the title Label control accordingly).
|
||||
- `void SetMessage(const std::string& message)` – 设置对话框主消息文本。更新内部 `message` 并重新拆分行、调整对话框大小 (Sets the main message text of the dialog. Updates the internal `message` string, re-splits it into lines, and recalculates dialog size as needed to accommodate the new text).
|
||||
- `void SetType(StellarX::MessageBoxType type)` – 设置对话框类型。更改需要显示的按钮组合,例如从 OK 切换为 YesNo 等。调用将移除原有按钮并根据新类型创建新按钮,重新布局底部区域 (Changes which buttons are displayed by altering the MessageBoxType. This will remove any existing action buttons and create new ones for the specified type, then reposition them in the footer).
|
||||
- `void SetModal(bool modal)` – 设置对话框的模态属性。true 表示在 Show() 时以模态方式运行(阻塞),false 表示以非模态方式运行 (Configures whether the dialog is modal or not. True means it will run modally (blocking the caller until closed), false means it will be modeless).
|
||||
- `void SetResult(StellarX::MessageBoxResult result)` – 人为设置对话框结果。这通常在对话框逻辑内部使用,例如用户点击按钮后调用,以记录选择的结果 (Manually sets the dialog’s result. Typically used internally when a button is clicked to store the user’s choice prior to closing the dialog).
|
||||
- `StellarX::MessageBoxResult GetResult() const` – 获取对话框结果。仅在对话框关闭后有意义:模态对话框可以通过此函数获取用户选择的结果枚举值 (Returns the dialog’s result (which button was pressed). This is useful after a modal dialog closes to know what the user selected).
|
||||
- `bool model() const override` – 返回对话框是否为模态。Dialog 实现此函数,用于区分模态对话框(返回 true)和非模态(返回 false)。父窗口在处理窗口事件时会据此判断是否需要暂停交互 (Indicates if the dialog is modal. The Dialog overrides `model()` to return the value of its modal flag. This can be used by the parent Window to determine whether user interaction with other controls should be blocked).
|
||||
- `void Show()` – 显示对话框。对于模态对话框,该函数会使对话框在屏幕中央出现并阻塞,直到对话框关闭。对于非模态,则在屏幕中央显示并立即返回 (Displays the dialog. If modal, this will position the dialog (typically centered on parent window) and enter a local event loop, blocking further execution until the dialog is closed by the user. If modeless, it simply makes the dialog visible (likely centered) and returns immediately). Show() 方法内部会将对话框加入父窗口的对话框列表 `Window::dialogs` 并标记窗口存在对话框 (Internally, Show() likely adds this dialog to the parent Window’s `dialogs` vector (for tracking open dialogs) and sets flags like `dialogClose = false` in the window).
|
||||
- `void Close()` – 关闭对话框。将对话框隐藏并从父窗口管理列表中移除,销毁内部控件。模态情况下Close会结束内部阻塞循环,恢复主窗口事件处理;非模态情况下Close则调用已注册的 resultCallback (Closes the dialog. It hides/removes the dialog from view, removes it from the parent window’s tracking list, and triggers cleanup of its child controls. In modal mode, Close breaks out of the modal loop allowing execution to continue in the caller; in modeless mode, Close will invoke the `resultCallback` (if set) to inform of the result asynchronously).
|
||||
- `void setInitialization(bool init)` – 设置是否需要初始化标志。这个内部标志 `needsInitialization` 控制对话框仅在首次 Show 时创建按钮等 (Sets the internal `needsInitialization` flag. If true, indicates that the dialog hasn’t yet fully initialized its UI (buttons/labels) and should do so on next show. Once initialized, this can be set false to avoid reinitializing).
|
||||
- **结果回调**:
|
||||
- `std::function<void(StellarX::MessageBoxResult)> resultCallback` – 非模态对话框结果回调函数。在 Dialog 显示为非模态时可以设置此回调,当用户点击某个按钮关闭对话框后将异步调用该函数并传入选择结果 (Callback function that will be called with the dialog’s result when a modeless dialog is closed. This allows handling the user’s choice without blocking).
|
||||
- `void SetResultCallback(std::function<void(StellarX::MessageBoxResult)> cb)` – 设置结果回调函数。用于非模态对话框,传入一个函数,当对话框关闭时框架会调用它并将 MessageBoxResult 结果传递进去 (Assigns the callback to call when the dialog is closed in modeless mode, receiving the MessageBoxResult).
|
||||
- **其他方法**:
|
||||
- `void performDelayedCleanup()` – 执行延迟清理。当对话框以非模态显示并关闭时,由 MessageBox 工厂调用,用于实际删除对话框对象 (Performs a delayed cleanup of the dialog. This is used by the MessageBox factory to delete the dialog object some time after closing if it was modeless, ensuring the callback is called before destruction).
|
||||
- `std::string GetCaption() const` – 获取对话框标题文本,用于去重检测。MessageBox 工厂在创建非模态对话框时可调用此函数检查是否已有相同标题和消息的对话框未关闭,从而避免重复弹出 (Returns the dialog’s title text (caption). The MessageBox factory uses this to check if a dialog with the same caption/text is already open, to prevent duplicates).
|
||||
- `std::string GetText() const` – 获取对话框消息文本,用于去重检测。
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- `Window& hWnd` – 对话框所属的父窗口引用。Dialog 会在该窗口的客户区显示,并对其事件进行拦截(模态时阻止 hWnd 处理事件)。通过引用可以在需要时调用父窗口的方法,例如 addDialog/removeDialog (Reference to the parent Window on which this dialog is displayed. The dialog is drawn within the parent window’s context. In modal mode, it uses this reference to block input to the window. The reference is also used to register/unregister the dialog in the window’s internal dialog list).
|
||||
- `int textWidth, textHeight` – 计算得到的对话框消息文本总尺寸(像素)。根据 `message` 内容和预设最大宽度自动换行得出 (The width and height (in pixels) of the message text area after word-wrapping. This is used to size the dialog appropriately).
|
||||
- `int buttonNum` – 底部功能按钮数量。由 MessageBoxType 决定,例如 OKCancel 类型时为2 (Number of action buttons in the dialog (excluding the close 'X' button). Determined by the MessageBoxType; e.g., OKCancel yields 2).
|
||||
- `StellarX::MessageBoxType type` – 当前对话框类型。决定对话框包含哪些功能按钮组合 (The type of the dialog, determining which action buttons are present, e.g., OK, YesNo, etc.).
|
||||
- `std::string titleText` – 对话框标题栏文本。默认 "提示" (Default is "提示", meaning "Prompt" or "Notice").
|
||||
- `std::unique_ptr<Label> title` – 标题文本的 Label 控件指针。对话框使用一个 Label 来显示标题文字,通常放置在标题栏中央 (Pointer to a Label control that displays the dialog’s title in the title bar area).
|
||||
- `std::string message` – 对话框主要消息内容文本。由构造函数传入 (The main message text of the dialog to be displayed in the body).
|
||||
- `std::vector<std::string> lines` – 分割后的消息文本行列表。根据对话框宽度将 message 拆分成若干行存储,用于在 draw 时逐行绘制 (The message text split into multiple lines to fit within the dialog’s width. This is prepared during initialization so that drawing can simply iterate over lines).
|
||||
- `bool needsInitialization` – 是否需要初始化的标志。初始为 true,表示需要调用 initButtons等初始化UI元素。在第一次 Show 时完成初始化后设为 false (Flag indicating if the dialog’s UI elements (buttons, etc.) still need to be initialized. True initially; after the first show (where `initButtons()`, etc., are called), set to false so as not to duplicate initialization).
|
||||
- `bool close` – 对话框关闭状态标志。为 true 时表示对话框应关闭,事件循环会检查此值退出 (Likely used to signal that the dialog should close. When set to true (e.g., after a button click), the modal loop will break and the dialog will begin teardown).
|
||||
- `bool modal` – 是否模态的标志。构造时根据传入参数设置,影响 Show 和 handleEvent 行为 (Indicates if the dialog is modal. Set in constructor based on parameter, determines how Show/handleEvent operate).
|
||||
- `COLORREF backgroundColor` – 对话框背景颜色,默认 RGB(240,240,240) 浅灰.
|
||||
- `COLORREF borderColor` – 对话框边框颜色,默认 RGB(100,100,100) 深灰.
|
||||
- `COLORREF buttonTrueColor, buttonFalseColor, buttonHoverColor` – 对话框底部功能按钮的配色方案。这些颜色用于创建对话框按钮时指定其不同状态颜色:buttonTrueColor(按钮按下时颜色,默认为略深的灰粉色),buttonFalseColor(按钮正常状态颜色,默认为浅灰),buttonHoverColor(按钮悬停颜色,默认为稍亮灰) (Color scheme for the dialog’s action buttons. These are used when creating the Button controls for OK/Cancel/etc: buttonTrueColor for pressed state (default a muted red/pinkish tone, RGB(211,190,190)), buttonFalseColor for unpressed state (default light gray, RGB(215,215,215)), buttonHoverColor for hover state (default slightly brighter gray, RGB(224,224,224))).
|
||||
- `Button* closeButton` – 对话框右上角的关闭按钮(“X”)指针。点击该按钮相当于取消/关闭对话框 (Pointer to the top-right close Button (with an “X”). Clicking it will close the dialog, typically equivalent to Cancel).
|
||||
- `StellarX::MessageBoxResult result` – 对话框的结果枚举值。初始默认为 Cancel(假定取消),当用户点击某个功能按钮时被设为对应的结果 (Stores the outcome of the dialog (which button was pressed). Initialized to Cancel by default, and set to the corresponding value when a button is clicked).
|
||||
- `bool shouldClose` – 标志对话框是否即将关闭。可能与 close 类似,但用于区分真正销毁时机 (Flag indicating the dialog should be closed. This might be used to initiate the shutdown sequence slightly before actual removal).
|
||||
- `bool isCleaning` – 标志对话框是否正在清理过程中。防止重复清理 (Flag indicating the dialog is currently in the cleanup process, to avoid re-entrance).
|
||||
- `bool pendingCleanup` – 标志是否需要延迟清理(如等待回调完成)。非模态对话框关闭时可能先不立即销毁对象而设置此标志,稍后由 performDelayedCleanup 真正删除 (Flag indicating that cleanup (object deletion) is pending. For modeless dialogs, after close, the object might not be destroyed immediately to allow the result callback to execute; instead pendingCleanup is set and actual deletion is done via performDelayedCleanup when safe).
|
||||
- `StellarX::ControlText textStyle` – 对话框文本样式。用于对话框消息文本的字体和颜色 (Font and style for the dialog’s message text). Dialog 通常使用系统默认字体、黑色文本 (Likely default to a standard font and black color).
|
||||
- **内部方法** *(private, for initialization and layout)*:
|
||||
- `void initButtons()` – 根据当前 `type` 创建底部功能按钮(如确定、取消等)并布局它们。同时计算 buttonNum 等 (Creates the action buttons (OK, Cancel, etc.) based on the dialog’s type and positions them appropriately at the bottom. Updates `buttonNum` and likely sizes).
|
||||
- `void initCloseButton()` – 创建并设置关闭按钮 (Creates the close “X” button and positions it at the top-right of the dialog).
|
||||
- `void initTitle()` – 创建并初始化标题 Label 控件 (Initializes the title Label with the current titleText and positions it in the title bar).
|
||||
- `void splitMessageLines()` – 将 `message` 按一定宽度拆分成多行填充到 `lines` 向量中 (Performs word wrapping: splits the message string into multiple lines that fit within the dialog’s width and stores them in `lines`).
|
||||
- `void getTextSize()` – 计算消息文本内容在当前字体下需要的宽高 (Calculates the pixel width and height required for the message text given the current font and line breaks).
|
||||
- `void initDialogSize()` – 根据内容(文本尺寸和按钮区域)计算对话框的总尺寸并调整自身宽高 (Sets the overall dialog width and height based on the text dimensions and space needed for buttons and title, including margins).
|
||||
- `void addControl(std::unique_ptr<Control> control)` – 将给定控件加入对话框的子控件列表 (Adds a new child control (Button/Label) to the Dialog’s Canvas children list and position relative to dialog).
|
||||
- `void clearControls()` – 清除并删除对话框内的所有子控件 (Removes all child controls from the dialog, deleting the buttons and labels. Used when resetting or destroying).
|
||||
- `std::unique_ptr<Button> createDialogButton(int x, int y, const std::string& text)` – 工具函数,创建一个在对话框底部指定位置的标准按钮。用于 OK/Cancel 等按钮的批量创建 (Utility to create a standard-sized dialog action button at given coordinates with given label text. Used by initButtons to create each required button).
|
||||
- `void requestRepaint(Control* parent) override` – 重载自 Control:Dialog 特殊实现覆盖 Canvas 默认行为。如果 parent == this,则仅执行 Canvas::requestRepaint 逻辑;否则调用父类 onRequestRepaintAsRoot() (The Dialog’s override for requestRepaint likely ensures that if a repaint is requested, it properly handles redrawing of itself and perhaps background. It might also intercept calls to avoid propagating beyond the dialog if not needed. The snippet suggests it overrides but possibly just uses default Canvas behavior except in special cases).
|
||||
|
||||
**依赖**:Dialog 依赖 **Window** 类来实现模态效果:模态对话框弹出时,会通过 Window 拦截消息循环或标记 `dialogClose` 等使主窗口等待。Dialog 内部组合了 **Label**(标题和消息文本)和 **Button**(操作按钮和关闭按钮)等多个控件,因此其正确运行依赖这些子控件的行为。Dialog 还使用 **MessageBoxType**/**MessageBoxResult** 枚举定义按钮方案和结果值。作为 Canvas 子类,Dialog 继承了绘制和背景处理机制,并在此基础上扩展 (The Dialog works closely with the **Window** class to implement modality: when shown modally, it likely uses Window’s event loop control (like Window::runEventLoop or flags) to block input to other controls. It composes multiple **Label** and **Button** controls and therefore relies on them for display and click handling. It uses **MessageBoxType** to decide what Buttons to create and **MessageBoxResult** to report outcomes. Being a subclass of Canvas, it benefits from Canvas's drawing logic and snapshot management to handle covering the underlying window content smoothly).
|
||||
|
||||
### MessageBox(消息框工厂类)
|
||||
|
||||
**类名**:`StellarX::MessageBox`
|
||||
**继承**:无,所有成员为静态方法 (This is a static utility class within namespace StellarX; it is not a Control and cannot be instantiated).
|
||||
|
||||
**简要说明**:消息框对话框的工厂类,提供简化的静态方法来创建和显示 **Dialog** 对象。开发者无需直接操作 Dialog 类,通过 MessageBox 提供的接口即可快捷地显示模态或非模态对话框。(*A factory class for message boxes that provides convenient static methods to create and display **Dialog** instances. It spares developers from dealing with the Dialog class directly by offering easy functions to show modal or modeless dialogs.*)
|
||||
|
||||
**公共静态方法**:
|
||||
|
||||
- `static MessageBoxResult showModal(Window& wnd, const std::string& text, const std::string& caption = "提示", MessageBoxType type = MessageBoxType::OK)` – 显示一个模态消息框。在窗口 `wnd` 中央弹出一个对话框,显示内容 `text` 和标题 `caption`(默认“提示”),按钮组合由 `type` 指定(默认单个 OK)。该调用会阻塞当前线程,直到用户点击任意按钮关闭对话框。返回值为用户选择的结果(MessageBoxResult 枚举,例如 MessageBoxResult::OK 或 MessageBoxResult::Cancel 等) (Displays a modal message box on the given window `wnd`. It creates a Dialog with the provided message text and caption (default "提示"), with buttons as specified by `type` (default OK only). This call blocks execution until the user closes the dialog by clicking a button. It returns the result as a MessageBoxResult value corresponding to which button was pressed). 典型用法如:`MessageBox::showModal(mainWindow, "操作完成", "通知", MessageBoxType::OKCancel)` 阻塞等待用户点“确定”或“取消” (Example: calling showModal to present an "Operation completed" message with OK and Cancel buttons, and wait for the user to choose).
|
||||
|
||||
- `static void showAsync(Window& wnd, const std::string& text, const std::string& caption = "提示", MessageBoxType type = MessageBoxType::OK, std::function<void(MessageBoxResult)> onResult = nullptr)` – 显示一个非模态(异步)消息框。参数同上,但该函数**不会阻塞**。它立即返回,消息框以非模态方式显示在窗口上,用户可以继续与主窗口交互。当用户点击按钮关闭消息框时,如果提供了 `onResult` 回调函数,则异步调用之并传入结果枚举值 (Displays a modeless (non-blocking) message box. Parameters are similar to showModal, but this function returns immediately, allowing the main window to continue running. The message box dialog is shown and will close when the user clicks a button, at which point if an `onResult` callback is provided, it will be invoked with the MessageBoxResult of the user’s choice). 这种用法适合不想打断用户操作的提示,例如:
|
||||
|
||||
```
|
||||
MessageBox::showAsync(mainWindow, "下载已在后台进行", "信息", MessageBoxType::OK,
|
||||
[](MessageBoxResult res){ /* 回调处理 */ });
|
||||
```
|
||||
|
||||
(This is useful for notifications that shouldn’t halt the program flow. For example, showing a "Download started in background" info box with just an OK button and using the callback to perform any follow-up if needed).
|
||||
|
||||
**实现说明**: MessageBox 的实现会根据提供的参数创建一个 **Dialog** 对象并显示。对于 showModal,它创建 Dialog(模态=true)然后调用 Dialog::Show(),等待获取结果后返回 (In implementation, showModal likely constructs a Dialog with modal=true, then calls its Show() method, and finally returns the Dialog’s result). 对于 showAsync,它创建 Dialog(模态=false),设置 Dialog::resultCallback 为传入的 onResult,然后调用 Dialog::Show() 后直接返回 (For showAsync, it constructs a Dialog with modal=false, sets its resultCallback to the provided function (if any), calls Show(), and returns immediately without waiting). MessageBox 工厂可能维护一个记录以避免同时弹出两个内容相同的非模态对话框(如通过 Dialog::GetCaption()/GetText() 检查去重) (The MessageBox might also ensure no duplicate dialogs are opened for the same text/caption pair, possibly by checking existing open dialogs in Window’s list using Dialog::GetCaption()/GetText()).
|
||||
|
||||
**依赖**:MessageBox 工厂严重依赖 **Dialog** 类实现实际对话框,以及 **Window** 提供的容器支持。它只是封装了 Dialog 的构造和显示逻辑 (The MessageBox relies on the **Dialog** class to do the actual work of showing a message box, and on **Window** for placement. It is essentially a thin wrapper that simplifies using Dialog).
|
||||
|
||||
## 顶层容器(Top-Level Containers)
|
||||
|
||||
顶层容器类在框架中充当应用程序窗口或主要界面容器,能够容纳其他控件。这里包括 Window 和 Canvas 两个类:Window 代表应用主窗口,负责和操作系统交互;Canvas 则是一个通用的控件容器,可以放置在窗口内或其他容器内用于分组子控件。 *(The top-level container classes serve as the application window or primary interface containers that hold other controls. This includes the Window class (representing the main application window, handling OS-level interactions) and the Canvas class (a general-purpose container control that can be placed in windows or other containers to group child controls).)*
|
||||
|
||||
### Window(窗口容器)
|
||||
|
||||
**类名**:`Window`
|
||||
**继承**:无直接继承自 Control,但 Window 包含并管理 Control 子控件的列表 (Window is not a Control itself, but it aggregates controls. It does not inherit from Control, it's an independent class that manages a collection of Control objects).
|
||||
|
||||
**简要说明**:应用程序主窗口类,封装 Win32 窗口并提供容器功能,能够添加控件并处理窗口事件循环。Window 结合 EasyX 图形库,实现一个可调整大小、不闪烁的窗口,支持锚定布局和双缓冲绘图,以容纳 GUI 控件。(*The main application window class. It wraps a Win32 window (via EasyX) and provides a container for controls. The Window class is designed to be resizable and minimize flicker, supporting anchored layouts and double-buffered drawing, and serves as the root container for GUI controls.*)
|
||||
|
||||
**关键实现**: Window 通过子类化窗口过程(WndProcThunk)拦截窗口消息,如大小调整(WM_SIZING/WM_SIZE)、最小尺寸约束等。它将窗口客户区大小变化解耦为 pending 尺寸记录和统一重绘信号,从而在拖动调整窗口大小时避免频繁重绘抖动。(*Key points: The Window subclasses the window procedure (using a thunk) to intercept important messages like WM_SIZING/WM_SIZE. It clamps minimum client size, defers resize handling by recording pending width/height and uses a flag (needResizeDirty) to trigger a one-time redraw at the end of a resize, preventing flicker during continuous resizing.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Window(int width, int height, int mode)` – 构造函数,创建指定客户区宽高的窗口。`mode` 为 EasyX 初始化模式,如 EX_SHOWCONSOLE(显示控制台)或 EX_TOPMOST(置顶)等。构造函数仅初始化成员,实际创建窗口和子类化窗口过程在 draw() 中完成 (Initializes a Window with given client area width and height, and an EasyX mode flag. It does not immediately open the OS window; it just sets up internal state. Actual window creation and subclassing of WndProc happen in draw()).
|
||||
- `Window(int width, int height, int mode, COLORREF bkColor)` – 重载构造,额外指定背景颜色。
|
||||
- `Window(int width, int height, int mode, COLORREF bkColor, std::string headline)` – 重载构造,额外指定窗口标题文本。
|
||||
- `~Window()` – 析构函数,关闭窗口并清理 (Closes the window (likely via EasyX closegraph or similar) and destroys child controls).
|
||||
- **绘制与事件循环**:
|
||||
- `void draw()` – 绘制窗口界面(无参数版本)。执行 EasyX 初始化(initgraph)创建窗口,设置必要的窗口扩展样式 WS_EX_COMPOSITED(useComposited 控制)减少闪烁。然后填充背景纯色(wBkcolor)或背景图(如果设置了 background image),并绘制所有已添加的控件 (This sets up the actual Win32 window if not done, possibly by calling EasyX’s initgraph using stored `width`, `height` and `windowMode`. It then draws the background: if a background image is loaded (background != nullptr), it draws that, otherwise fills a solid color (wBkcolor). After that, it iterates through the `controls` vector to draw each child control. It also likely draws any non-modal dialogs that are open (from `dialogs` vector) on top).
|
||||
- `void draw(std::string pImgFile)` – 绘制窗口界面(带背景图)。该重载加载指定路径的图像作为窗口背景(赋值给 background 指针),然后调用 draw() 主函数 (This variant sets the background image by loading from the provided file path (stores it in `background` image pointer and records `bkImageFile` path), then likely calls the regular draw() routine to render with this image).
|
||||
- `int runEventLoop()` – 运行窗口的主事件循环。实现为循环调用 EasyX 的 PeekMessage 获取消息,然后对所有控件调用其 handleEvent() 进行分发,并在必要时调用 draw 进行重绘 (Runs the main GUI loop. Likely uses a loop around `PeekMessage()` (non-blocking message fetch) to continuously handle events. For each message, it passes it to each control’s handleEvent (in reverse order perhaps for proper z-order), tracks if any control became dirty (needResizeDirty usage), and if so, triggers a redraw of all controls at the end of the loop iteration). 特殊处理 WM_SIZING 等消息:当用户拖动调整窗口大小时,临时冻结重绘(isSizing=true),只在拖动结束 WM_EXITSIZEMOVE 时统一更新 (It has logic to handle WM_SIZING by not immediately redrawing (set isSizing true), and only upon WM_SIZE at end (or WM_EXITSIZEMOVE) does it schedule one combined redraw using `needResizeDirty`). runEventLoop 返回值可能是窗口关闭时的退出代码 (The function returns an exit code when the window is closed, possibly 0).
|
||||
- **背景与标题设置**:
|
||||
- `void setBkImage(std::string pImgFile)` – 更换窗口背景图像。加载指定文件为背景 (Loads the specified image file and sets it as the window’s background. After calling, it triggers a redraw of the window to display the new background).
|
||||
- `void setBkcolor(COLORREF c)` – 设置窗口背景纯色。将背景色改为 c,并立即触发一次重绘 (Sets the window background color to `c` and immediately triggers a full redraw of the window).
|
||||
- `void setHeadline(std::string headline)` – 设置窗口标题文本。更新内部 `headline` 字符串,并调用 Win32 API 更新窗口标题栏显示 (Changes the window’s title text. Updates the internal `headline` and likely calls SetWindowText on the underlying HWND to reflect the new title).
|
||||
- **控件和对话框管理**:
|
||||
- `void addControl(std::unique_ptr<Control> control)` – 将一个新的控件添加到窗口。此控件将被纳入 Window 的 `controls` 列表,在下次 draw 时绘制,并在事件循环中接收事件 (Adds a Control to the window’s control list. The Window takes ownership via the unique_ptr. The new control’s coordinates are typically relative to the window’s client area. It will be drawn on next repaint and will participate in event handling). 对于某些控件,Window 在添加时可能根据当前窗口大小调用其 onWindowResize 以初始化布局 (Window might call the new control’s onWindowResize upon adding to adjust layout if anchors are used).
|
||||
- `void addDialog(std::unique_ptr<Control> dialog)` – 将一个非模态对话框控件添加到窗口。Window 将其存入 `dialogs` 列表,该列表专门用于对话框( Adds a non-modal dialog (which is a Control) to the window. It is stored in a separate `dialogs` vector. The window will draw these on top of other controls and give them priority in event handling). 这通常由 MessageBox::showAsync 内部调用,当创建 Dialog 后将其托管给 Window (This is typically called internally by MessageBox::showAsync after creating a Dialog, to ensure the window knows about the open dialog).
|
||||
- `bool hasNonModalDialogWithCaption(const std::string& caption, const std::string& message) const` – 检查是否存在某个标题和消息匹配的非模态对话框正在窗口中显示。用于避免重复弹出内容相同的对话框 (Checks the `dialogs` list to see if a dialog with the given caption and message text is currently open. This is used to prevent opening duplicate dialogs with identical content).
|
||||
- **状态访问器**:
|
||||
- `HWND getHwnd() const` – 获取窗口的 Windows 窗口句柄。这允许调用底层 Win32 API,如需要 (Returns the Win32 window handle (HWND) of the EasyX-created window, in case direct Win32 calls are needed).
|
||||
- `int getWidth() const` / `int getHeight() const` – 获取窗口当前客户区宽度和高度。注意 Window 自身维护的 width/height 表示当前**有效**客户区尺寸,可能在交互拉伸过程中暂时保持旧值直到松开鼠标统一更新 (Returns the current effective client area width and height of the window. Note that the Window maintains `width`/`height` as the last fully applied size; during interactive resizing, it uses pendingW/H to store the changing values).
|
||||
- `std::string getHeadline() const` – 获取窗口标题文本.
|
||||
- `COLORREF getBkcolor() const` – 获取窗口背景色.
|
||||
- `IMAGE* getBkImage() const` – 获取窗口背景 IMAGE 对象指针(如果有). 如果未设置背景图则返回 nullptr (Returns the pointer to the background image if one is set, otherwise nullptr).
|
||||
- `std::string getBkImageFile() const` – 获取当前背景图片文件路径(如果有).
|
||||
- `std::vector<std::unique_ptr<Control>>& getControls()` – 获取对窗口普通控件列表的非 const 引用。允许遍历或操作已添加的控件 (Provides a reference to the vector of controls (not including dialogs), allowing iteration or manipulation of child controls if needed).
|
||||
- **尺寸调整**:
|
||||
- `void pumpResizeIfNeeded()` – 检查并执行一次延迟的重绘以响应窗口尺寸变化。Window 内部在事件循环每次迭代结尾调用此函数:如果 `needResizeDirty` 标志为 true,则调用一次 draw() 完成所有控件的调整绘制,然后将 `needResizeDirty` 复位 (Executes a deferred full redraw if a resize event has occurred. Inside the event loop, after processing all messages, Window calls this: if `needResizeDirty` is true (meaning a resize has happened and controls might need repositioning), it calls draw() to redraw everything and resets `needResizeDirty`). 这样可以把连续的 WM_SIZE 处理压缩为单次绘制 (This condenses potentially many WM_SIZE events into a single redraw, improving efficiency and reducing flicker).
|
||||
- `void scheduleResizeFromModal(int w, int h)` – 当模态对话框关闭时调用,将 pendingW/H 更新为给定值并标记 `needResizeDirty`。这用于在模态对话框可能改变父窗口大小(比如隐藏滚动条之类)后,通知窗口稍后调整布局 (Schedules a resize handling after a modal dialog closes and potentially affected the window size or layout. It sets the pendingW, pendingH (maybe to w,h) and marks needResizeDirty so that pumpResizeIfNeeded will redraw with updated layout).
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- **尺寸状态**:
|
||||
- `int width, height` – 当前有效客户区宽度和高度。这是应用到控件布局的实际尺寸 (The current effective width and height of the client area, which have been applied to control layout).
|
||||
- `int localwidth, localheight` – 窗口创建时的初始基准宽度和高度。作为锚定布局计算参考 (The baseline width/height at window creation, used as reference for anchor layout scaling calculations).
|
||||
- `int pendingW, pendingH` – 待应用的新宽高。在窗口被拉伸 (WM_SIZING) 过程中,Window 会记录不断变化的尺寸到 pendingW/H,但暂不应用到控件;等到用户释放鼠标(最终 WM_SIZE)时,再将 pendingW/H 赋给 width/height 并触发统一重绘。(The width and height that are pending application. During interactive resizing, as WM_SIZING events provide new sizes, the Window stores them in pendingW/H without immediately adjusting controls. Only when resizing is done (WM_SIZE final) do these get applied to actual width/height with one unified redraw).
|
||||
- `int minClientW, minClientH` – 业务设定的最小客户区宽高。Window 初始化时可指定一个最小大小,用于在 WM_GETMINMAXINFO 消息处理中限制窗口不能缩得太小 (Minimum client area width and height set for the window (if any). The Window uses these to enforce a minimum window size by handling WM_GETMINMAXINFO or clamping WM_SIZING).
|
||||
- `int windowMode` – EasyX 窗口初始化模式标志。例如 EX_SHOWCONSOLE, EX_TOPMOST 等,通过 EasyX initgraph 用 (The EasyX window mode flags used on creation, such as whether to show a console or make the window topmost, etc.).
|
||||
- `bool needResizeDirty` – 统一收口重绘标志。为 true 表示窗口尺寸变动引起的重绘尚未处理,需要在事件循环空闲时统一执行 (Flag indicating that a resize occurred and a full redraw is needed. When true, the event loop will call draw once and then clear this flag. It's set during resizing events to avoid multiple intermediate draws).
|
||||
- `bool isSizing` – 是否处于拖拽调整大小的状态。当收到 WM_ENTERSIZEMOVE 消息(用户开始拖拽窗口边框)时设 true,在 WM_EXITSIZEMOVE(拖拽结束)时设 false。(Flag indicating if the user is currently resizing the window (dragging the window border). Set to true on WM_ENTERSIZEMOVE, false on WM_EXITSIZEMOVE. When true, Window may suppress immediate redraws to avoid jitter).
|
||||
- **原生窗口和子类化**:
|
||||
- `HWND hWnd` – EasyX 创建的窗口句柄。Window 类在 draw() 中通过 EasyX 初始化拿到窗口句柄,并安装自定义窗口过程 (The Win32 window handle obtained after EasyX initialization. The Window uses it to subclass the window procedure).
|
||||
- `WNDPROC oldWndProc` – 保存的旧窗口过程指针。子类化时,用于在 Window 过程内调用原窗口过程处理未拦截的消息 (The original window procedure pointer saved when subclassing. The custom WndProcThunk will call this (via CallWindowProc) for messages it doesn’t handle).
|
||||
- `bool procHooked` – 标志窗口过程是否已子类化,避免重复钩挂.
|
||||
- `static LRESULT CALLBACK WndProcThunk(HWND h, UINT m, WPARAM w, LPARAM l)` – **静态窗口过程**,将 Win32 消息分发到特定 Window 实例的成员函数 (A static window procedure that acts as a trampoline to the Window instance’s message handler. It likely retrieves the Window* from a static map or from `GetWindowLongPtr(h,GWLP_USERDATA)` and calls an instance method). Window 在初始化时把该 Thunk 安装到 hWnd (During Window initialization, this function is set as the new window procedure for hWnd).
|
||||
- **绘制相关**:
|
||||
- `bool useComposited` – 是否使用组合窗口扩展风格(WS_EX_COMPOSITED)。默认为 true。打开该选项可减少某些机器上的绘制闪烁(但可能引入一帧延迟)(Whether to use the WS_EX_COMPOSITED extended style for the window, which can reduce flicker by double buffering the entire window. Default true, though on some systems this might introduce a slight frame delay).
|
||||
- `std::string headline` – 窗口标题文本。将在窗口标题栏显示 (The text for the window’s title bar).
|
||||
- `COLORREF wBkcolor` – 窗口背景纯色。绘制窗口时作为填充底色 (The solid background color used if no background image is set. Default BLACK (0x000000)).
|
||||
- `IMAGE* background` – 背景图像指针。如果加载了背景图,则绘制窗口时优先绘制该图像覆盖整个客户区 (Pointer to an IMAGE used as the window’s background. If not null, draw() will tile or stretch/draw this image to cover the client area).
|
||||
- `std::string bkImageFile` – 当前背景图像文件路径。记录所加载背景图的位置 (Stores the filename of the currently loaded background image, if any, mainly for reference or reloading purposes).
|
||||
- **控件/对话框容器**:
|
||||
- `std::vector<std::unique_ptr<Control>> controls` – 存放窗口上的普通控件列表。Window 的主要子控件容器。加入此列表的控件会在 draw() 时绘制、在事件循环中接收事件 (Holds all non-dialog child controls added to the window. These are drawn in the window’s draw() and have their events processed in the main loop).
|
||||
- `std::vector<std::unique_ptr<Control>> dialogs` – 存放窗口上当前打开的非模态对话框控件列表。这些对话框(Dialog 类实例)在 Window::draw() 中应绘制在普通控件之上,在事件处理时应优先处理 (Holds any modeless dialog controls currently open on this window. In draw(), these are drawn on top of regular controls, and in event handling, they get first chance to consume input, effectively overlaying modal-like behavior for their portion of the window).
|
||||
- `bool dialogClose` – 项目内使用的标志,指示对话框关闭状态。当窗口存在模态对话框时,该标志或许用于中断主事件循环 (A flag used to indicate a dialog has closed; possibly used internally to break out of a modal loop or signal something related to dialogs. It’s usage is not fully clear but likely interacts with the modal logic).
|
||||
|
||||
**依赖**:Window 直接使用 Win32 API(通过 EasyX)来创建窗口和处理消息。因此,它需要 Windows 平台支持。Window 包含框架内所有控件,是 GUI 的根容器:它依赖 **Control** 及其子类(Button 等)的存在,以将它们加入显示列表并调用其绘制和事件处理。Window 也依赖 **Dialog** 用于处理模态对话框逻辑、依赖 **MessageBoxType/Result** 枚举来处理最小化尺寸、结果返回等 (The Window class wraps the OS window and heavily interacts with the Win32 API via EasyX. It serves as the integration point where Control objects meet OS events. It depends on all control classes for populating its interface, and on **Dialog** for handling modal scenarios. It uses enumerated types from CoreTypes (LayoutMode, Anchor) for resizing logic as well). Window 与操作系统的交互如消息循环、最小化最大化等,均在其内部实现,对于开发者而言主要使用其 addControl、draw、runEventLoop 等接口 (All OS-level interactions (minimize, close, etc.) are handled internally by Window’s subclassed WndProc. For the developer, the main usage is adding controls, calling draw to initialize, and runEventLoop to start the GUI loop).
|
||||
|
||||
### Canvas(画布容器)
|
||||
|
||||
**类名**:`Canvas`
|
||||
**继承**:继承自 Control (`class Canvas : public Control`)。Canvas 是 Control 的一个具体实现,主要用于作为容器承载其他控件。
|
||||
|
||||
**简要说明**:通用画布控件,可充当容器容纳子控件,并支持绘制背景形状和处理子控件布局。Canvas 通常用作复合控件的基础(如 Dialog 和 TabControl 都继承自 Canvas),也可独立用于在窗口中分组一组控件。(*A general-purpose canvas control that can contain child controls and draw a background shape. Canvas often serves as a base for composite controls (e.g., Dialog and TabControl inherit Canvas), and can also be used on its own to group a set of controls in a window.*)
|
||||
|
||||
**功能**: Canvas 继承自 Control,提供除基本属性外的重要扩展:维护一个子控件列表(controls),并在绘制时能够绘制自身背景(可设置形状、填充模式、颜色等)然后递归绘制其包含的子控件。它也重载了部分 Control 方法以在自身移动或可见性变化时调整子控件。例如,当 Canvas 移动时,会相应偏移所有子控件的位置;当 Canvas 被隐藏时,自动隐藏子控件。(*Canvas extends Control by maintaining a list of child controls and by drawing a background (with configurable shape, fill mode, colors) before drawing its children. It overrides certain Control methods to handle child elements: for instance, moving a Canvas shifts all its children’s positions accordingly; hiding a Canvas also hides its children.*)
|
||||
|
||||
**公共方法**:
|
||||
|
||||
- `Canvas()` – 默认构造函数,将 Canvas 初始放置在 (0,0) 且尺寸为 100×100。调用 Control 基类构造,并设置 id 为 "Canvas" (Initializes a Canvas at origin with a default size of 100 by 100. Sets the control’s id to "Canvas").
|
||||
- `Canvas(int x, int y, int width, int height)` – 构造函数,在指定坐标创建给定尺寸的 Canvas。设置 id 为 "Canvas"。初始时背景形状默认矩形,填充模式、颜色等使用默认值 (Creates a Canvas at (x,y) with specified width and height. Id set to "Canvas". By default, its shape is rectangle with default fill mode and colors).
|
||||
- `void setX(int x) override` / `void setY(int y) override` – 重载移动 Canvas 的方法。Canvas 实现除更新自身位置外,会遍历所有子控件,将每个子控件的绝对坐标随之偏移(新的 X = 子控件原 localX + Canvas 新的 x 等)并调用子控件的 `onWindowResize()` 让其自行处理 (When moving the Canvas, it not only updates its own x (or y) but also adjusts all child controls: it calls each child’s `onWindowResize()` and sets the child’s X coordinate to its stored localX plus the new Canvas X. This effectively keeps children at the same relative position inside the Canvas even as the Canvas moves. Similarly for Y. Also marks itself dirty for redraw).
|
||||
- `void setWidth(int width) override` / `void setHeight(int height) override` – 默认继承 Control 的行为,只调整自身尺寸并标记 dirty。Canvas 没有特别重载这两个,但在 Canvas 内部,调整尺寸通常伴随需要重新布局子控件,此时 Canvas 的 onWindowResize 可能会被显式调用 (Canvas uses the base implementation for setWidth/Height: update and mark dirty. However, resizing a Canvas usually would imply repositioning children if anchors are set; such logic might rely on explicit call to onWindowResize to recalculation local positions if needed).
|
||||
- `void clearAllControls()` – 清空 Canvas 容器中的所有子控件。实现为简单调用 `controls.clear()` 删除子控件智能指针列表 (Removes all child controls from the Canvas’s vector, destroying them. After calling this, the Canvas will have no child controls).
|
||||
- `void draw() override` – 绘制 Canvas 及其子控件。实现逻辑:
|
||||
1. 若 Canvas 自身不是 dirty 或处于隐藏状态(show=false),则跳过自身重绘,仅检查并绘制特殊控件子类如 Table 等需要持续绘制 (If the Canvas itself is not marked dirty or is not visible, it will skip redrawing its background. However, it still iterates children: if a child is of a special type (like Table) that manages its own content and may need continuous drawing, it calls that child’s draw anyway to update dynamic content).
|
||||
2. 如果需要重绘:先调用 `saveStyle()` 保存当前全局绘图状态。然后设置绘图颜色和样式:边框色 = `canvasBorderClor`,填充色 = `canvasBkClor`(前提 FillMode 不是 Null),填充模式 = `canvasFillMode`,线型 = `canvasLineStyle`,线宽 = `canvaslinewidth`。
|
||||
3. 绘制 Canvas 背景形状:根据 `shape` 不同,调用 EasyX 不同函数绘制矩形、圆角矩形、圆形或椭圆等。如果 shape 带 B_ 前缀表示无边框版本,则使用 solidrectangle/solidroundrect 等无边框绘制,否则用 fillrectangle/fillroundrect 绘制带边框。圆角尺寸由 rouRectangleSize 提供 (Draw the canvas background shape: depending on `shape`, it chooses the appropriate function: e.g., fillrectangle for a filled rectangle with border, solidrectangle for borderless, fillroundrect/solidroundrect for rounded corners with/without border, etc. The rouRectangle struct provides the corner ellipse size for roundrect shapes).
|
||||
4. 依次绘制所有子控件:遍历 `controls` 列表,对每个子控件设置 dirty=true(确保其自身 draw 刷新),然后调用其 `draw()`。这样保证当 Canvas 重绘时,所有子控件都重绘 (Iterates through each child control, marks it dirty (setDirty(true)), and calls its draw() to render it).
|
||||
5. 调用 `restoreStyle()` 恢复全局绘图状态,标记 Canvas 自身 dirty=false 表示绘制已完成 (Finally restores the saved drawing state and marks itself not dirty).
|
||||
- `bool handleEvent(const ExMessage& msg) override` – 处理事件,将事件分发给子控件。实现为从后向前遍历子控件列表(Z序从顶开始)调用每个子控件的 handleEvent。如有子控件消费事件则记录 firstConsumer 并设置 consumed=true。遍历完后,如果有控件消费且该事件不属于“噪音”消息(如 WM_MOUSEMOVE),则打印调试日志 (It iterates over children in reverse order (so the topmost drawn control gets event first) calling each child’s handleEvent(msg). If a child returns true (event consumed) and firstConsumer is not yet set, it stores that pointer. After checking all, if an event was consumed and is not a “noisy” event like WM_MOUSEMOVE, it logs a debug message indicating Canvas consumed the event via a child).
|
||||
然后,如果发现任意子控件 `isDirty()==true` 则设 anyDirty=true。若 anyDirty 且消息非噪音,则打印日志并调用 `requestRepaint(parent)` 通知父容器需要重绘 (It also checks if any child became dirty during event handling; if yes, for non-mouse-move events it logs and calls `requestRepaint(parent)` to ask the parent to repaint this Canvas). 最后返回 consumed (Finally returns whether any child consumed the event).
|
||||
- 管理子控件:
|
||||
- `void addControl(std::unique_ptr<Control> control)` – 将一个子控件添加到 Canvas。实现:把 control 的 local 坐标 (getLocalX/Y) 转换为全局坐标,即加上 Canvas 自身的 x,y;将 control.parent 设为 this;记录日志说明添加 (Logs the addition with both local and computed global coords)。然后将 control 转移到 Canvas.controls 列表末尾,并将 Canvas 标记 dirty=true (Then moves the control into the Canvas’s controls list and marks the Canvas dirty). 这样下次 Canvas 重绘时会绘制该子控件 (The new control will be rendered on the next draw call of the Canvas).
|
||||
- `void setShape(StellarX::ControlShape shape)` – 设置 Canvas 背景形状。允许在矩形、圆角矩形、圆形、椭圆几种外观之间切换。只接受枚举定义的四边形/圆形形状 (Sets the shape used to draw the Canvas background (rectangle, round-rectangle, circle, ellipse with or without border). Only the shapes defined in ControlShape are accepted). 实现中,对传入 shape 进行 switch,但实际上任何受支持值都会执行 (The implementation likely just switches to the provided shape if valid and sets dirty true).
|
||||
- `void setCanvasfillMode(StellarX::FillMode mode)` – 设置 Canvas 背景填充模式(注意代码拼写大小写,此应为 setCanvasFillMode)。(Sets the fill mode for the Canvas background). 例如可将 Canvas 背景设为图案填充等。实现:赋值 canvasFillMode = mode 并标记 dirty (It assigns the new fill mode and marks the Canvas dirty).
|
||||
- `void setBorderColor(COLORREF color)` – 设置 Canvas 边框颜色。实现:canvasBorderClor = color,dirty=true.
|
||||
- `void setCanvasBkColor(COLORREF color)` – 设置 Canvas 背景填充颜色。实现:canvasBkClor = color,dirty=true.
|
||||
- `void setCanvasLineStyle(StellarX::LineStyle style)` – 设置 Canvas 边框线型样式。实现:canvasLineStyle = style,dirty=true.
|
||||
- `void setLinewidth(int width)` – 设置 Canvas 边框线宽。实现:canvaslinewidth = width,dirty=true.
|
||||
- `void setIsVisible(bool visible) override` – 重载 Control::setIsVisible。Canvas 将自身 show 标志设为 visible 并置 dirty=true。与 Control 默认实现相比没有额外逻辑 (Canvas does not add extra logic here beyond base: it sets its own `show` to the given value and marks itself dirty. It does not explicitly hide children here – however, when Canvas’s draw runs and show=false, children won’t be drawn and events won’t be passed if IsVisible returns false). 注:TabControl 等子类会进一步重载实现子控件可见性同步 (Note: As seen, TabControl overrides setIsVisible to handle children, but base Canvas doesn’t).
|
||||
- `void setDirty(bool dirty) override` – 重载 Control::setDirty。实现:设置自身 dirty 标志,并对所有子控件也递归设置 dirty= true。这确保当 Canvas 需要重绘时,其包含的子控件也会重绘 (Marks the canvas and all its children as dirty when dirty=true is set. This ensures a full redraw of all content. If dirty=false, it similarly clears the dirty flag on children).
|
||||
|
||||
**成员变量**:
|
||||
|
||||
- `std::vector< std::unique_ptr<Control> > controls` – Canvas 的子控件列表 (The container of child controls within this Canvas). 这些控件的坐标是**全局**坐标(已经加上 Canvas.x,y),Canvas 同时可能存储子控件的局部坐标用于布局 (Children are stored with their absolute positions already offset by Canvas’s position. The Canvas itself may not separately store local coords for them, as each Control already knows its local coordinates relative to parent from when it was added).
|
||||
- `StellarX::ControlShape shape` – Canvas 背景形状类型 (The shape used for this Canvas’s background. Default likely RECTANGLE).
|
||||
- `StellarX::FillMode canvasFillMode` – Canvas 背景填充模式 (Fill mode for the background; default Solid).
|
||||
- `StellarX::LineStyle canvasLineStyle` – Canvas 边框线型 (Border line style; default Solid).
|
||||
- `int canvaslinewidth` – Canvas 边框线宽度(像素)(Border line width; default maybe 1).
|
||||
- `COLORREF canvasBorderClor` – Canvas 边框颜色 (Border color; default black RGB(0,0,0)).
|
||||
- `COLORREF canvasBkClor` – Canvas 背景填充颜色 (Background fill color; default white RGB(255,255,255)).
|
||||
|
||||
*(默认值参考 TABLE_DEFAULT_BG_COLOR/DEFAULT_BORDER_COLOR 等相似定义推测)*
|
||||
|
||||
**依赖**:Canvas 作为 Control 子类,不直接依赖 OS 资源,但它依赖 **ControlShape**、**FillMode**、**LineStyle** 等 CoreTypes 定义来渲染外观。Canvas 常被其他控件继承或组合使用,例如 **TabControl** 和 **Dialog** 就利用 Canvas 来实现多控件布局和背景绘制功能 (Canvas relies on the core enums for shapes and styles. It is often used as a base or a component in composite controls: e.g., **TabControl** inherits Canvas to manage pages, **Dialog** inherits Canvas to manage dialog content. Thus, Canvas forms a foundational block for any container-like control in the framework). 开发者可直接使用 Canvas 来划分界面区域或自定义绘制形状和放置子控件 (A developer might use a Canvas directly in a Window to group controls or draw a colored panel background). Canvas 无窗口句柄,不处理独立消息循环,其事件处理和重绘完全依赖父 Window 传递 (Canvas doesn’t have its own window handle; it relies on the parent Window to dispatch events and refresh calls to it, just like any other Control).
|
||||
|
||||
## 工具类(Utility Classes)
|
||||
|
||||
工具类提供辅助功能,非 GUI 控件但为框架的开发和调试提供支持。例如日志记录类 SxLog 用于输出调试信息。下面对框架的日志系统做简要说明: *(Utility classes offer supporting functionality outside of the UI controls, such as logging or debug output. For instance, the SxLog logging system is used for debug and information logging. Below is an overview of the framework’s logging utility:)*
|
||||
|
||||
### 日志系统 SxLog(Logging Utility)
|
||||
|
||||
**类名**:`StellarX::SxLog` *(实际上由多个类和宏组成,包括 SxLogger, FileSink, SxLogLine, SxLogScope 等;对外主要以宏接口使用)* (Implemented by several classes like SxLogger, FileSink, SxLogLine, SxLogScope, but primarily exposed via macros).
|
||||
|
||||
**简要说明**:StellarX 框架的日志记录工具,支持中英双语日志输出、日志分级过滤、文件输出及滚动等功能。通过一组宏(如 `SX_LOGD`, `SX_LOGI`, `SX_LOGW`, `SX_LOGE` 分别用于调试、信息、警告、错误级别)和辅助宏 `SX_T`(将中英文字符串选择输出)实现简洁的日志记录接口。(*The logging system for the StellarX framework, providing bilingual log output, log level filtering, and file output with rotation. It is accessed via a set of macros (e.g., `SX_LOGD`, `SX_LOGI`, `SX_LOGW`, `SX_LOGE` for debug, info, warning, error levels respectively) and a helper macro `SX_T` (for bilingual text selection) to offer a simple logging interface.*)
|
||||
|
||||
**使用方法**:
|
||||
在代码中,可通过例如:
|
||||
|
||||
```
|
||||
SX_LOGD("Event") << SX_T("Canvas 消耗消息: ","Canvas consumed: msg=") << msg.message;
|
||||
```
|
||||
|
||||
将会打印一条调试日志。在日志输出中,`"Event"` 为日志标签,SX_T 宏包含了中文和英文两段字符串,日志系统会根据当前语言设置选取相应语言输出。以上示例最终可能输出:“Canvas 消耗消息: msg=0x0201 子控件 id=Button1”(当语言设为中文)或 “Canvas consumed: msg=0x0201 by child id=Button1”(设为英文)(In practice, using the macros as shown will produce log lines with a tag and bilingual text. The system chooses Chinese or English text in SX_T based on the current language setting. For example, the above might log “Canvas 消耗消息: msg=...” in Chinese mode, or “Canvas consumed: msg=...” in English mode).
|
||||
|
||||
**日志级别**: SxLog 定义了日志级别枚举 SxLogLevel(例如 Debug, Info, Warn, Error 等)。通过全局日志器 SxLogger,可以设置最低输出级别。当使用 `SX_LOGx` 宏记录时,低于当前最低级别的日志不会输出 (The SxLog system has log levels (likely Debug=0, Info=1, etc.). The global logger SxLogger has a `setMinLevel(SxLogLevel level)` function to set the minimum level of messages to actually output. Logging calls via `SX_LOGx` macros with a level below this threshold are no-ops).
|
||||
|
||||
**语言控制**: 默认情况下日志语言为中文(ZhCN)。可以通过 `SxLogger::setLanguage(SxLogLanguage lang)` 切换语言,例如设为 EnUS 输出英文日志 (By default, the log language is Chinese (ZhCN). The language can be changed by calling `SxLogger::setLanguage(SxLogLanguage)` to switch to English (EnUS) or other supported languages. Only the text provided via SX_T macro is affected by this setting).
|
||||
|
||||
**输出方式**: 日志既可以输出到调试控制台,也可以输出到文件。通过 `SxLogger::enableFile(const std::string& path, bool append, size_t rotateBytes)` 可以启用日志文件输出。参数 path 为文件路径,append 指定是否追加模式写入,rotateBytes 则如果>0表示启用文件滚动,当文件达到指定大小字节时自动改名备份并开启新文件 (The log can be configured to write to a file by calling `SxLogger::enableFile(path, append, rotateBytes)`. If `rotateBytes` is set (non-zero), the logger will automatically rotate (rename and start a new log file) when the current file exceeds that size).
|
||||
|
||||
**实现细节**:
|
||||
|
||||
- 日志系统由以下组件构成:
|
||||
- **FileSink**:负责文件输出的类,封装文件打开、写入、关闭及文件滚动逻辑。
|
||||
- **SxLogger**:日志核心单例类(Get() 获取实例),管理日志级别、语言和输出目的地。SxLogger 提供 `shouldLog(level)` 判断是否应输出某级别日志,`logLine(level, tag, message)` 统一将一行日志送往所有目的(控制台、文件)。
|
||||
- **SxLogLine**:使用 RAII 的技巧实现流式日志,将 `SX_LOGx` 宏展开后生成的对象在析构时自动调用 SxLogger 提交日志。这保证了一条日志完整输出在一行结束。
|
||||
- **SxLogScope**:用于计算一段作用域执行时间的辅助类。在构造时记录时间戳,析构时计算耗时并输出日志,可用于性能分析。
|
||||
- **日志宏**:
|
||||
- `SX_LOGD(tag)`, `SX_LOGI(tag)`, `SX_LOGW(tag)`, `SX_LOGE(tag)` 分别创建一个 SxLogLine 对象用于调试(D)、信息(I)、警告(W)、错误(E)级别日志。参数 `tag` 是短字符串标签,用于标识日志分类。后续可以用流插入操作符 `<<` 将消息内容流入日志对象。每条日志宏调用最终在一行输出,并以换行结束 (These macros create an SxLogLine internally for the specified level with the given tag, then the code uses `<<` to append message parts. When the statement ends, the SxLogLine’s destructor is invoked, which sends the accumulated text to SxLogger to output with a newline).
|
||||
- `SX_T(chinese, english)` 宏用于处理内嵌在日志中的中英文双语字符串。运行时根据当前语言,只选择其中一个串输出。例如 `SX_T("失败","Failure")` 若语言为中文则产出 "失败",英文则产出 "Failure" (The SX_T macro is a translation helper: it takes a Chinese string and an English string, and at runtime includes only the one matching the current language setting in the log. It allows log messages to be bilingual without duplicating code).
|
||||
|
||||
**使用示例**:
|
||||
|
||||
```
|
||||
SX_LOGI("Init") << SX_T("窗口创建成功,大小=","Window created, size=")
|
||||
<< wnd.getWidth() << "x" << wnd.getHeight();
|
||||
```
|
||||
|
||||
如果当前日志级别 <= Info,则将输出类似:“窗口创建成功,大小=800x600” 或 “Window created, size=800x600”。否则不会输出任何信息 (If the current log level is Info or lower, this will output the message in the appropriate language. If the level is higher (e.g., Warning), nothing is output).
|
||||
|
||||
**依赖**:日志系统与 GUI 框架其他部分松耦合。它使用 C++11 线程安全特性(如 `std::call_once` 设置控制台 CodePage, `std::mutex` 来序列化日志输出)。日志宏在 GUI 控件代码中被调用以记录调试信息,但它本身不依赖 GUI 类。**EasyX** 控制台输出在 Windows 默认是 GBK,所以 SxLogger 在初始化时尝试设置控制台 CodePage 为 936 (GBK) 以正确显示中文日志(The logging system is mostly self-contained, using standard C++ for file and console operations. In the context of GUI, it’s used by controls for debug output but does not interact with GUI components. Notably, it sets the Windows console code page to 936 (GBK) once to ensure Chinese characters are properly displayed on the console, as noted in the comments).
|
||||
|
||||
通过 SxLog 工具类,开发者可以方便地输出框架内部运行状况信息,这对调试 GUI 行为、事件处理流程等非常有帮助。(*The SxLog utility enables developers to conveniently output internal state and flow information from the framework, which is invaluable for debugging GUI behavior and event handling.*)
|
||||
Reference in New Issue
Block a user