feat: add a new awesome feature

This commit is contained in:
2025-11-19 15:14:39 +08:00
parent 5420bfd644
commit 58d4e8ab2f
23 changed files with 3360 additions and 3971 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[中文文档](CHANGELOG.md)
## [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

View File

@@ -7,6 +7,27 @@ StellarX 项目所有显著的变化都将被记录在这个文件中。
[English document](CHANGELOG.en.md)
## [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
### ⚙️ 变更

View File

@@ -7,8 +7,8 @@
![GitHub all releases](https://img.shields.io/github/downloads/Ysm-04/StellarX/total)
[![Star GitHub Repo](https://img.shields.io/github/stars/Ysm-04/StellarX.svg?style=social&label=Star%20This%20Repo)](https://github.com/Ysm-04/StellarX)
![Version](https://img.shields.io/badge/Version-2.2.1-brightgreen.svg)
![Download](https://img.shields.io/badge/Download-2.2.1_Release-blue.svg)
![Version](https://img.shields.io/badge/Version-2.3.0-brightgreen.svg)
![Download](https://img.shields.io/badge/Download-2.3.0_Release-blue.svg)
![C++](https://img.shields.io/badge/C++-17+-00599C?logo=cplusplus&logoColor=white)
![Windows](https://img.shields.io/badge/Platform-Windows-0078D6?logo=windows)
@@ -25,12 +25,25 @@ This is a **teaching-grade and tooling-grade** framework that helps developers u
------
## 🆕 v2.2.2 — Stable Release
## 🆕 V2.3.0 - Major Update
- In the next planned update, control states will synchronize in real-time during window resizing operations.
- Modified the coordinate transfer method for Canvas containers. 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 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.
- Addressed issues related to window resizing and dialog boxes as mentioned above.
**This version represents a significant milestone, introducing a responsive layout system that transitions from static to dynamic layout management, and comprehensively resolves the previously encountered random rendering corruption issues caused by reentrant drawing operations.**
- **Optimized Window Resizing Mechanism**: Refactored `WndProcThunk`, `runEventLoop`, and `pumpResizeIfNeeded` to uniformly record size changes and perform centralized repainting at the end of the event loop, eliminating jitter and sequencing confusion caused by repeated redraws.
- **New Dialog Size Scheduling Interface**: Introduced the combination of `Window::scheduleResizeFromModal()` and `pumpResizeIfNeeded()`, enabling modal dialogs to notify the parent window of size updates even during resizing operations. Underlying controls are relayout during unified finalization while dialogs maintain their original dimensions.
- **Enhanced Adaptive Layout System**: Internally added the `adaptiveLayout()` function to recalculate control positions and sizes based on anchor points, allowing dual-anchored controls (left-right or top-bottom) to adaptively stretch with window resizing.
- **Fixed Modal Dialog Resizing Issues**: Resolved the problem where window resizing while modal dialogs were open prevented underlying controls from updating their positions and sizes according to anchor points; simultaneously eliminated ghosting artifacts caused by repeated dialog redraws.
- **Further Resolved Drawing Sequence Confusion**: Replaced `InvalidateRect` with `ValidateRect` during resizing operations, ensuring the window is marked as valid only after a single unified drawing pass, preventing system-triggered `WM_PAINT` messages from causing reentrancy.
- **Additional Fixes**: Corrected delayed background snapshot updates in tables and dialogs under certain edge cases.
![](image/1.png)
![](image/2.png)
For details, please refer to the [CHANGELOG.en](CHANGELOG.en.md).
@@ -174,6 +187,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 |

View File

@@ -12,8 +12,8 @@
![GitHub all releases](https://img.shields.io/github/downloads/Ysm-04/StellarX/total)
[![Star GitHub Repo](https://img.shields.io/github/stars/Ysm-04/StellarX.svg?style=social&label=Star%20This%20Repo)](https://github.com/Ysm-04/StellarX)
![Version](https://img.shields.io/badge/Version-2.2.1-brightgreen.svg)
![Download](https://img.shields.io/badge/Download-2.2.1_Release-blue.svg)
![Version](https://img.shields.io/badge/Version-2.3.0-brightgreen.svg)
![Download](https://img.shields.io/badge/Download-2.3.0_Release-blue.svg)
![C++](https://img.shields.io/badge/C++-17+-00599C?logo=cplusplus&logoColor=white)
![Windows](https://img.shields.io/badge/Platform-Windows-0078D6?logo=windows)
@@ -30,14 +30,27 @@
---
## 🆕v2.2.2 ——稳定版本
## 🆕V2.3.0——重要更新
- 预计下次版本更新,将同步窗口拉伸时,控件同步更新状态
**本版本是一次重大更新,增加了响应式布局系统,由静态布局转变为动态布局,并且彻底修复了之前存在的由重入重绘导致的概率出现的渲染错乱问题**
- Canvas容器坐标传递方式改变子控件坐标由原来的传递全局坐标改为传递相对坐标坐标原点为容器的左上角坐标可通过getX/Y接口获得可以设置子控件坐标为负值
- examples\register-viewer下的案例已同步修改为最新同步容器子控件为相对坐标
- 对于窗口拉伸和对话框问题进行了修复
- 详情参考[更新日志](CHANGELOG.md)
- **优化窗口尺寸调节机制**:重构 `WndProcThunk``runEventLoop``pumpResizeIfNeeded`,统一记录尺寸变化并在事件循环末尾集中重绘,避免重复重绘导致的抖动和顺序错乱。
- **新增对话框尺寸调度接口**:引入 `Window::scheduleResizeFromModal()``pumpResizeIfNeeded()` 的组合,模态对话框在拉伸期间也可通知父窗口更新尺寸。底层控件将在统一收口时重新布局,而对话框自身保持尺寸不变。
- **自适应布局改进**:内部新增 `adaptiveLayout()` 函数,按照锚点重新计算控件位置和尺寸,使双锚定(左右或上下)控件随窗口变化自适应伸缩。
- **修复模态对话框拉伸问题**:解决模态对话框打开时,窗口拉伸导致底层控件无法根据锚点更新的位置和尺寸的问题;同时避免对话框反复重绘导致的残影。
- **进一步解决绘制顺序错乱**:拉伸过程中采用 `ValidateRect` 替代 `InvalidateRect`,确保窗口仅在一次统一收口绘制后标记为有效,杜绝系统再次触发 `WM_PAINT` 造成重入。
- 其他修复:修正表格和对话框背景快照某些边界情况下的更新不及时问题。
![](image/1.png)
![](image/2.png)
详细变更请参阅[更新日志](CHANGELOG.md)
---
@@ -179,6 +192,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` |
### 结构体
| 结构体 | 描述 |

View File

@@ -90,12 +90,18 @@ int 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);
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();
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);
bitInvert->setCanvasBkColor(blackColor);
bitInvert->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
leftShift->setCanvasBkColor(blackColor);
@@ -103,6 +109,9 @@ int main()
rightShift->setCanvasBkColor(blackColor);
rightShift->setShape(StellarX::ControlShape::B_ROUND_RECTANGLE);
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);
@@ -139,7 +148,7 @@ int main()
//取反区控件
std::array<std::unique_ptr<Label>, 4> bitInvertFunctionLabel;
bitInvertFunctionLabel[0] = std::make_unique<Label>(35, 10, "低位");
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, "");
@@ -217,9 +226,6 @@ int main()
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));
//显示区控件
//数值显示
@@ -428,7 +434,7 @@ int main()
signedTogglePtr->setOnToggleOnListener([&]() {
gSigned = true;
signedTogglePtr->setButtonText("有符号");
StellarX::MessageBox::showAsync(mainWindow, "有符号模式下,\n最高位为符号位,\n其余位为数值位。", "有符号模式");
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; }();
@@ -443,6 +449,7 @@ int main()
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("切换无符号模式", "切换有符号模式");
@@ -451,7 +458,6 @@ int main()
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));

BIN
image/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
image/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

View File

@@ -18,6 +18,7 @@
#pragma once
#include "Control.h"
#include"Table.h"
class Canvas : public Control
{
@@ -39,6 +40,7 @@ public:
Canvas();
Canvas(int x, int y, int width, int height);
~Canvas() {}
//绘制容器及其子控件
void draw() override;
bool handleEvent(const ExMessage& msg) override;

View File

@@ -42,6 +42,11 @@ protected:
bool dirty = true; // 是否重绘
bool show = true; // 是否显示
/* == 布局模式 == */
StellarX::LayoutMode layoutMode = StellarX::LayoutMode::Fixed; // 布局模式
StellarX::Anchor anchor_1 = StellarX::Anchor::Top; // 锚点
StellarX::Anchor anchor_2 = StellarX::Anchor::Left; // 锚点
/* == 背景快照 == */
IMAGE* saveBkImage = nullptr;
int saveBkX = 0, saveBkY = 0; // 快照保存起始坐标
@@ -115,8 +120,8 @@ public:
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; }
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;
@@ -127,7 +132,6 @@ public:
void setParent(Control* parent) { this->parent = parent; }
//设置是否重绘
virtual void setDirty(bool dirty) { this->dirty = dirty; }
//检查控件是否可见
bool IsVisible() const { return show; };
//获取控件id
@@ -136,6 +140,12 @@ public:
bool isDirty() { return dirty; }
//用来检查对话框是否模态,其他控件不用实现
virtual bool model()const = 0;
//布局
void setLayoutMode(StellarX::LayoutMode layoutMode_);
void steAnchor(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();

View File

@@ -343,4 +343,47 @@ namespace StellarX
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
};
}

View File

@@ -1,7 +1,7 @@
/*******************************************************************************
* @文件: StellarX.h
* @摘要: 星垣(StellarX) GUI框架 - 主包含头文件
* @版本: v2.2.2
* @版本: v2.3.0
* @描述:
* 一个为Windows平台打造的轻量级、模块化C++ GUI框架。
* 基于EasyX图形库提供简洁易用的API和丰富的控件。

View File

@@ -69,6 +69,7 @@ private:
bool isShowPageButton = true; // 是否显示翻页按钮
bool isNeedDrawHeaders = true; // 是否需要绘制表头
bool isNeedCellSize = true; // 是否需要计算单元格尺寸
bool isNeedButtonAndPageNum = true; // 是否需要计算翻页按钮和页码信息
Button* prevButton = nullptr; // 上一页按钮
Button* nextButton = nullptr; // 下一页按钮
@@ -98,7 +99,8 @@ private:
bool model() const override { return false; };
public:
StellarX::ControlText textStyle; // 文本样式
void setWidth(int width) override;
void setHeight(int height) override;
public:
Table(int x, int y);
~Table();
@@ -154,6 +156,9 @@ public:
std::vector<std::vector<std::string>> getData() const;
//获取表格边框宽度
int getTableBorderWidth() const;
//获取表格尺寸
int getTableWidth() const;
int getTableHeight() const;
};

View File

@@ -26,6 +26,8 @@ class Window
// —— 尺寸状态 ——(绘制尺寸与待应用尺寸分离;收口时一次性更新)
int width; // 当前有效宽(已应用到画布/控件的客户区宽)
int height; // 当前有效高(已应用到画布/控件的客户区高)
int localwidth; // 基准宽(创建时的宽度)
int localheight; // 基准高(创建是的高度)
int pendingW; // 待应用宽WM_SIZE/拉伸中记录用)
int pendingH; // 待应用高
int minClientW; // 业务设定的最小客户区宽(用于 GETMINMAXINFO 与 SIZING 夹紧)
@@ -102,4 +104,7 @@ public:
void processWindowMessage(const ExMessage & msg); // 处理 EX_WINDOW 中的 WM_SIZE 等
void pumpResizeIfNeeded(); // 执行一次统一收口重绘
void scheduleResizeFromModal(int w, int h);
private:
void adaptiveLayout(std::unique_ptr<Control>& c,const int finalH, const int finalW);
};

View File

@@ -17,20 +17,42 @@ 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);//设置线色
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. 当坐标或尺寸变化,或缓存图像无效时,丢弃旧快照并重新抓取新的背景。
if (hasSnap)
{
// 恢复旧快照,清除上一次绘制
restBackground();
// 如果位置或尺寸变了,或没有有效缓存,则重新抓取
if (!saveBkImage || saveBkX != this->x || saveBkY != this->y || 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();
//根据画布形状绘制
switch (shape)
@@ -158,10 +180,174 @@ void Canvas::setDirty(bool 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)
{

View File

@@ -54,6 +54,27 @@ void Control::onWindowResize()
discardBackground();
setDirty(true);
}
void Control::setLayoutMode(StellarX::LayoutMode layoutMode_)
{
this->layoutMode = layoutMode_;
}
void Control::steAnchor(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()

View File

@@ -59,7 +59,7 @@ void Dialog::draw()
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()));
@@ -555,7 +555,7 @@ 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)
for (auto& text : lines)
{
int w = textwidth(LPCTSTR(text.c_str()));
int h = textheight(LPCTSTR(text.c_str()));

View File

@@ -165,10 +165,26 @@ TabControl::~TabControl()
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);
// 恢复背景(清除旧内容)
// 在绘制 TabControl 之前,先恢复并更新背景快照:
if (hasSnap)
{
// 先回贴旧快照,清除之前的绘制
restBackground();
// 如位置或尺寸变化,丢弃旧快照并重新抓取
if (!saveBkImage || saveBkX != this->x || saveBkY != this->y || 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();
// 绘制画布背景和基本形状及其子画布控件
Canvas::draw();
for (auto& c : controls)
{
@@ -176,7 +192,6 @@ void TabControl::draw()
c.first->draw();
}
for (auto& c : controls)
if(c.second->IsVisible())
{
c.second->setDirty(true);
c.second->draw();
@@ -216,6 +231,7 @@ 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].second->setIsVisible(true);
@@ -291,12 +307,19 @@ void TabControl::setIsVisible(bool 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

View File

@@ -87,11 +87,15 @@ void Table::initTextWaH()
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 +113,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()
@@ -171,6 +178,7 @@ void Table::initButton()
if (pageNum) pageNum->setDirty(true);
}
});
isNeedButtonAndPageNum = false;
}
void Table::initPageNum()
@@ -214,7 +222,7 @@ void Table::drawPageNum()
pageNumtext += "页/共";
pageNumtext += std::to_string(totalPages);
pageNumtext += "";
if (nullptr == pageNum)
if (nullptr == pageNum || isNeedButtonAndPageNum)
initPageNum();
pageNum->setText(pageNumtext);
pageNum->textStyle = this->textStyle;
@@ -226,7 +234,7 @@ void Table::drawPageNum()
void Table::drawButton()
{
if (nullptr == prevButton || nullptr == nextButton)
if ((nullptr == prevButton || nullptr == nextButton)|| isNeedButtonAndPageNum)
initButton();
this->prevButton->textStyle = this->textStyle;
@@ -242,6 +250,43 @@ void Table::drawButton()
}
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)
:Control(x, y, 0, 0)
{
@@ -317,11 +362,25 @@ 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();
// 绘制表头
@@ -365,7 +424,7 @@ 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);
isNeedCellSize = true; // 标记需要重新计算单元格尺寸
isNeedDrawHeaders = true; // 标记需要重新绘制表头
@@ -467,10 +526,13 @@ void Table::setTableBorderWidth(int width)
void Table::onWindowResize()
{
Control::onWindowResize(); // 先处理自己
if (this->prevButton && this->nextButton && this->pageNum)
{
prevButton->onWindowResize();
nextButton->onWindowResize();
pageNum->onWindowResize();
}
}
int Table::getCurrentPage() const
{
@@ -527,4 +589,17 @@ 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;
}

View File

@@ -1,7 +1,7 @@
#include "Window.h"
#include "Dialog.h"
#include <graphics.h>
#include <easyx.h>
#include <algorithm>
/**
@@ -95,23 +95,23 @@ static void ApplyMinSizeOnSizing(RECT* prc, WPARAM edge, HWND hWnd, int minClien
*/
Window::Window(int w, int h, int mode)
{
minClientW = pendingW = width = w;
minClientH = pendingH = height = h;
localwidth = minClientW = pendingW = width = w;
localheight = minClientH = pendingH = height = h;
windowMode = mode;
}
Window::Window(int w, int h, int mode, COLORREF bk)
{
minClientW = pendingW = width = w;
minClientH = pendingH = height = h;
localwidth = minClientW = pendingW = width = w;
localheight = minClientH = pendingH = height = h;
windowMode = mode;
wBkcolor = bk;
}
Window::Window(int w, int h, int mode, COLORREF bk, std::string title)
{
minClientW = pendingW = width = w;
minClientH = pendingH = height = h;
localwidth = minClientW = pendingW = width = w;
localheight = minClientH = pendingH = height = h;
windowMode = mode;
wBkcolor = bk;
headline = std::move(title);
@@ -128,7 +128,7 @@ Window::~Window()
// ---------------- 原生消息钩子----------------
/**
* WndProcThunk
* WndProcThun
* 作用:替换 EasyX 的窗口过程,接管关键消息。
* 关键处理:
* - WM_ERASEBKGND返回 1交由自绘清屏避免系统擦背景造成闪烁。
@@ -191,18 +191,10 @@ LRESULT CALLBACK Window::WndProcThunk(HWND h, UINT m, WPARAM w, LPARAM l)
self->needResizeDirty = true;
}
// 关键:立刻做统一收口,不用等下一条消息
self->pumpResizeIfNeeded();
// 不擦背景、不触发立即 WM_PAINT
// InvalidateRect(h, nullptr, TRUE);
// UpdateWindow(h);
InvalidateRect(h, nullptr, FALSE);
// 解冻 + 触发一次刷新InvalidateRect TRUE 会擦背景;如需无擦背景可传 FALSE
// 结束拉伸后不立即执行重绘,待事件循环统一收口。
// 立即解冻重绘标志,同时标记区域为有效,避免触发额外 WM_PAINT。
SendMessage(h, WM_SETREDRAW, TRUE, 0);
InvalidateRect(h, nullptr, TRUE);
UpdateWindow(h);
ValidateRect(h, nullptr);
return 0;
}
@@ -510,8 +502,8 @@ int Window::runEventLoop()
// 批量通知控件“窗口尺寸变化”,并标记重绘
for (auto& c : controls)
{
adaptiveLayout(c,finalH,finalW);
c->onWindowResize();
c->setDirty(true);
}
for (auto& d : dialogs)
{
@@ -528,9 +520,9 @@ int Window::runEventLoop()
EndBatchDraw();
// 解冻并触发一次无效化(这里 TRUE 表示会擦背景;如要避免闪白可改 FALSE
// 解冻后标记区域有效,避免系统再次触发 WM_PAINT 覆盖自绘内容。
SendMessage(hWnd, WM_SETREDRAW, TRUE, 0);
InvalidateRect(hWnd, nullptr, TRUE);
ValidateRect(hWnd, nullptr);
}
needResizeDirty = false; // 收口完成,清标志
@@ -595,10 +587,8 @@ void Window::setHeadline(std::string title)
// 设置窗口标题(仅改文本,不触发重绘)
headline = std::move(title);
if (hWnd)
{
SetWindowText(hWnd, headline.c_str());
}
}
void Window::addControl(std::unique_ptr<Control> control)
{
@@ -711,13 +701,20 @@ void Window::pumpResizeIfNeeded()
loadimage(background, bkImageFile.c_str(), rc.right - rc.left, rc.bottom - rc.top, true);
putimage(0, 0, background);
}
else { setbkcolor(wBkcolor); cleardevice(); }
else
{
setbkcolor(wBkcolor);
cleardevice();
}
width = rc.right - rc.left; height = rc.bottom - rc.top;
// 通知控件/对话框
for (auto& c : controls)
{
adaptiveLayout(c, finalH, finalW);
c->onWindowResize();
}
for (auto& d : dialogs)
if (auto* dd = dynamic_cast<Dialog*>(d.get()))
dd->setInitialization(true); // 强制对话框在新尺寸下重建布局/快照
@@ -729,9 +726,10 @@ void Window::pumpResizeIfNeeded()
EndBatchDraw();
SendMessage(hWnd, WM_SETREDRAW, TRUE, 0);
// 原来是 TRUE会擦背景再触发 WM_PAINT容易把刚画好的层“盖掉”
// InvalidateRect(hWnd, nullptr, TRUE);
InvalidateRect(hWnd, nullptr, FALSE);
// 原实现在此调用 InvalidateRect 导致系统再次发送 WM_PAINT从而重复绘制
// 这里改为 ValidateRect:直接标记区域为有效,通知系统我们已完成绘制,不必再触发 WM_PAINT。
// 这样可以避免收口阶段的绘制与系统重绘叠加造成顺序错乱。
ValidateRect(hWnd, nullptr);
needResizeDirty = false;
}
@@ -750,3 +748,72 @@ void Window::scheduleResizeFromModal(int w, int h)
}
}
void Window::adaptiveLayout(std::unique_ptr<Control>& c, const int finalH, const int finalW)
{
int origParentW = this->localwidth;
int origParentH = this->localheight;
if (c->getLayoutMode() == StellarX::LayoutMode::AnchorToEdges)
{
if ((StellarX::Anchor::Left == c->getAnchor_1() && StellarX::Anchor::Right == c->getAnchor_2())
|| (StellarX::Anchor::Right == c->getAnchor_1() && StellarX::Anchor::Left == c->getAnchor_2()))
{
int origRightDist = origParentW - (c->getLocalX() + c->getLocalWidth());
int newWidth = finalW - c->getLocalX() - origRightDist;
c->setWidth(newWidth);
// 左侧距离固定ctrl->x 保持为 localx 相对窗口左侧父容器为窗口偏移0
c->setX(c->getLocalX());
}
else if ((StellarX::Anchor::Left == c->getAnchor_1() && StellarX::Anchor::NoAnchor == c->getAnchor_2())
|| (StellarX::Anchor::NoAnchor == c->getAnchor_1() && StellarX::Anchor::Left == c->getAnchor_2())
|| (StellarX::Anchor::Left == c->getAnchor_1() && StellarX::Anchor::Left == c->getAnchor_2()))
{
// 仅左锚定:宽度固定不变
c->setX(c->getLocalX());
c->setWidth(c->getLocalWidth());
}
else if ((StellarX::Anchor::Right == c->getAnchor_1() && StellarX::Anchor::NoAnchor == c->getAnchor_2())
|| (StellarX::Anchor::NoAnchor == c->getAnchor_1() && StellarX::Anchor::Right == c->getAnchor_2())
|| (StellarX::Anchor::Right == c->getAnchor_1() && StellarX::Anchor::Right == c->getAnchor_2()))
{
int origRightDist = origParentW - (c->getLocalX() + c->getLocalWidth());
c->setWidth(c->getLocalWidth()); // 宽度不变
c->setX(finalW - origRightDist - c->getWidth());
}
else if (StellarX::Anchor::NoAnchor == c->getAnchor_1() && StellarX::Anchor::NoAnchor == c->getAnchor_2())
{
c->setX(c->getLocalX());
c->setWidth(c->getLocalWidth());
}
if ((StellarX::Anchor::Top == c->getAnchor_1() && StellarX::Anchor::Bottom == c->getAnchor_2())
|| (StellarX::Anchor::Bottom == c->getAnchor_1() && StellarX::Anchor::Top == c->getAnchor_2()))
{
// 上下锚定:高度随窗口变化
int origBottomDist = origParentH - (c->getLocalY() + c->getLocalHeight());
int newHeight = finalH - c->getLocalY() - origBottomDist;
c->setHeight(newHeight);
c->setY(c->getLocalY());
}
else if ((StellarX::Anchor::Top == c->getAnchor_1() && StellarX::Anchor::NoAnchor == c->getAnchor_2())
|| (StellarX::Anchor::NoAnchor == c->getAnchor_1() && StellarX::Anchor::Top == c->getAnchor_2())
|| (StellarX::Anchor::Top == c->getAnchor_1() && StellarX::Anchor::Top == c->getAnchor_2()))
{
c->setY(c->getLocalY());
c->setHeight(c->getLocalHeight());
}
else if ((StellarX::Anchor::Bottom == c->getAnchor_1() && StellarX::Anchor::NoAnchor == c->getAnchor_2())
|| (StellarX::Anchor::NoAnchor == c->getAnchor_1() && StellarX::Anchor::Bottom == c->getAnchor_2())
|| (StellarX::Anchor::Bottom == c->getAnchor_1() && StellarX::Anchor::Bottom == c->getAnchor_2()))
{
int origBottomDist = origParentH - (c->getLocalY() + c->getLocalHeight());
c->setHeight(c->getLocalHeight());
c->setY(finalH - origBottomDist - c->getHeight());
}
else {
// 垂直无锚点:默认为顶部定位,高度固定
c->setY(c->getLocalY());
c->setHeight(c->getLocalHeight());
}
}
}

File diff suppressed because it is too large Load Diff