替换 NIM 为独立 TTUI 引擎并完善窗口交互

移除 NIM 源码及主题依赖,加入 Win32、Direct2D、DirectWrite UI 静态库。迁移主页面、添加任务及外观设置,完善虚拟列表、统一窗口透明度和首次显示初始化。增加 Windows 7 API 回退与回归测试,在 AGENTS.md 记录后续控件体系和布局系统计划。
This commit is contained in:
tongtong committed 2026-11-16 11:52:05 +08:00
1 parent 7c0ee5d964
commit db38ec5c03
408 files changed
+1575 -55735

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
# TTUI
独立的 Windows DirectUI C++20 静态库,基于 Windows SDK 的 Win32、Direct2D、DirectWrite、WIC。无需 NIM/Duilib 或其他第三方 UI 框架。
## 构建与集成
- Visual Studio 2022 / MSVC v143 / 最低目标 Windows 7 SP1 x64,兼容 Windows 10、11。
- 根目录 `TTUI.sln` 仅构建引擎;`TTDownloader.sln` 构建下载器和引擎。
- `build.cmd Debug` / `build.cmd Release` 构建客户端。
- 静态库输出 `ui/ttui/lib/x64/<Configuration>/ttui.lib`。
- 宿主导入 `ttui.props` 并添加 `ttui.vcxproj` 的 ProjectReference;Windows SDK 链接依赖由库的编译单元声明。
- 客户端不再加载旧主题 XML,没有皮肤资源复制步骤;当前页面布局在业务 C++ 代码中定义。
## 接口与线程
- `application.h`:UI 线程上初始化 OLE、每屏 DPI,运行 Win32 消息循环。创建回调返回 false 时退出;主窗口销毁后结束循环。
- `window.h`:宿主持有窗口对象,TTUI 管理 HWND、DPI、Direct2D 渲染目标及设备丢失后的重建。窗口默认固定大小,只有 Create 的 resizable 参数显式为 true 时才允许用户缩放。业务类在析构函数中先销毁 HWND,再销毁回调访问的成员。
- `Canvas`:矩形、文字、进度和裁剪;按钮由 TTUI 自绘,支持命中检测、按下/移出取消、Tab 和键盘激活。
- `CreateEdit`:系统 EDIT 输入框,支持中文输入法、复制粘贴;编辑通知不会自动提交,Enter 单独提交。外观设置的滑块使用系统 trackbar。
- `virtual_list.h`:仅维护数量、选择和视口;绘制只遍历可见行,不创建永久行控件。
- UI 刷新合并到约 30Hz;下载器批量处理引擎事件。任务数据和 SQLite 仍由下载工作线程处理。
- 控件不绘制独立底色:自绘按钮绘制透明背景的边框、居中文字及焦点/悬停/按下反馈,焦点通过边框体现,系统编辑框和滑块沿用窗口背景(包括背景图片)。背景图片使用 WIC 在工作线程解码,在 UI 线程上传纹理。缓存像素用于重建渲染目标;限制解码尺寸避免超大图片占用失控。无效图片回退到纯色背景。
## 回归验证
运行仓库根目录 `test.cmd Debug` / `test.cmd Release`。独立测试项目为 `ui/ttui/tests/smoke.vcxproj`,也可选择 x64 手动构建并运行对应目录的 `smoke.exe`。
覆盖十万行视口边界、中文/emoji 编码及非法输入、工作线程上临时 SQLite 文件的任务恢复、系统输入框通知、Direct2D/DirectWrite 实际绘制、按钮按下/取消、键盘焦点、窗口调整及消息循环退出。测试不访问用户的 tasks.db。
## 当前范围
已迁移下载主窗口及外观设置,保留任务增删、暂停恢复、托盘、菜单、文件打开和拖出。保留 Windows 标准标题栏及 DPI 缩放行为,窗口默认固定大小。
这是一套服务于下载器的轻量引擎,尚无 XML 解析器、通用样式系统、动画时间轴或完整 UI Automation 提供程序。下一步可以在现有窗口/绘制/视口接口上扩展,不再需要兼容旧框架。
## Windows 7 与窗口重建
最低系统目标为 Windows 7 SP1 x64。编译定义 `_WIN32_WINNT=0x0601`,可执行文件子系统版本为 6.01,使用 MSVC v143 静态运行库。DPI 新 API 通过 GetProcAddress 可选解析;Windows 7 回退到 SetProcessDPIAware、GetDeviceCaps 和 AdjustWindowRectEx。参考 [Microsoft DPI 模式说明](https://learn.microsoft.com/en-us/windows/win32/hidpi/setting-the-default-dpi-awareness-for-a-process)。WinHTTP 自动代理不支持时回退到 DEFAULT_PROXY,并启用 TLS 1.2;Content-Length 以文本读取并检查 64 位溢出,避免依赖较新查询标志。参考 [WinHttpOpen](https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpopen)。Windows 7 的 HTTPS 仍依赖系统 TLS、证书及系统更新。
关闭 HWND 时释放绑定该句柄的 Direct2D target 和 bitmap;复用窗口对象时重置交互状态、缓存背景画刷及布局初始化状态。重建后的布局只在子控件创建后执行。回归测试连续三次创建/关闭同一窗口对象,检查每次绘制目标均绑定当前 HWND,且按钮仍可点击。
外观设置保留背景覆盖和统一窗口透明度滑块;已删除表头、输入、列表、底部区域透明度字段及其读取,保存时清理旧注册表项。背景覆盖仍支持滑动时预览。
当前已在开发机验证编译、绘制和重开窗口;Windows 7 实机/虚拟机的完整运行验证仍需完成,不能以降低宏定义或检查导入表代替系统验收。
## 统一窗口透明度
外观设置中“窗口透明度”独立于背景覆盖,默认 100%,范围 30%–100%。使用顶层窗口的 WS_EX_LAYERED + SetLayeredWindowAttributes(LWA_ALPHA),整窗文字和子控件随窗口一起透明;拖动时同步主窗口、添加任务和设置窗口,新窗口在显示前应用当前值。WindowOpacity 注册表项保存此设置,旧配置缺失时为 100%。参考 [Microsoft SetLayeredWindowAttributes](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setlayeredwindowattributes)。测试读取三个窗口的实际 Alpha,覆盖实时同步、上下限、恢复不透明及新窗口继承。
为避免初次显示时闪过不透明窗口,业务窗口在构造/创建前读入共享透明度,CreateWindowEx 直接设置分层样式,在 WM_NCCREATE 阶段应用 Alpha;ShowWindow 前准备首帧。相同透明度不重复调用系统 API。回归覆盖连续三次重建时,在 OnCreate 之前原生 Alpha 已正确设置。
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <windows.h>
namespace ttui {
class AeroBackdrop
{
public:
AeroBackdrop() = default;
~AeroBackdrop();
AeroBackdrop(const AeroBackdrop&) = delete;
AeroBackdrop& operator=(const AeroBackdrop&) = delete;
bool Create(HWND owner);
void Sync(HWND owner);
void Refresh();
void Hide();
void Destroy();
bool IsValid() const { return hwnd_ != nullptr; }
private:
static LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void ApplyGlass(int width, int height);
HWND hwnd_ = nullptr;
int blur_width_ = 0;
int blur_height_ = 0;
bool blur_enabled_ = false;
bool visible_ = false;
};
} // namespace ttui
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <functional>
namespace ttui {
// Initializes COM/OLE and per-monitor DPI, creates windows, then runs Win32 messages.
// Return false from create_windows on startup failure. Invoke once on the UI thread.
int RunApplication(const std::function<bool()>& create_windows);
}
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <utility>
namespace ttui {
// Data-only viewport. Rendering visits visible rows, never allocates per-row controls.
class VirtualList {
public:
void Configure(size_t count, int page) {
count_=static_cast<int>((std::min)(count, static_cast<size_t>(0x7fffffff)));
page_=(std::max)(1,page); ScrollTo(first_);
if (selected_>=count_) selected_=count_-1;
}
void ScrollTo(int row) { first_=std::clamp(row,0,(std::max)(0,count_-page_)); }
void Select(int row) { selected_=row>=0 && row<count_ ? row : -1; }
void RevealSelection() {
if (selected_<0) return;
if (selected_<first_) ScrollTo(selected_);
if (selected_>=first_+page_) ScrollTo(selected_-page_+1);
}
std::pair<int,int> Visible() const { return {first_,(std::min)(count_,first_+page_+1)}; }
int First() const { return first_; }
int Selected() const { return selected_; }
int Count() const { return count_; }
int Page() const { return page_; }
private:
int count_=0,page_=1,first_=0,selected_=-1;
};
}
+87
View File
@@ -0,0 +1,87 @@
#pragma once
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <d2d1.h>
#include <dwrite.h>
#include <wrl/client.h>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace ttui {
struct Rect {
float left=0, top=0, right=0, bottom=0;
bool Contains(float x, float y) const { return x>=left && x<right && y>=top && y<bottom; }
D2D1_RECT_F Native() const { return D2D1::RectF(left,top,right,bottom); }
};
class Canvas {
public:
Canvas(ID2D1HwndRenderTarget* target, IDWriteFactory* text) : target_(target), text_(text) {}
void Fill(Rect rect, unsigned rgb, float opacity=1);
void Text(const std::wstring& text, Rect rect, unsigned rgb=0x273449, float size=14, bool bold=false, DWRITE_TEXT_ALIGNMENT alignment=DWRITE_TEXT_ALIGNMENT_LEADING);
void Progress(Rect rect, double fraction);
void Clip(Rect rect) { target_->PushAxisAlignedClip(rect.Native(), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE); }
void Unclip() { target_->PopAxisAlignedClip(); }
ID2D1HwndRenderTarget* Target() const { return target_; }
private:
ID2D1HwndRenderTarget* target_;
IDWriteFactory* text_;
};
// Owns a native top-level window; business code owns the C++ object.
// Destroy the native window before destroying members used by virtual callbacks.
class Window {
public:
Window();
virtual ~Window();
Window(const Window&)=delete;
Window& operator=(const Window&)=delete;
bool Create(HWND owner, const wchar_t* class_name, const wchar_t* title, int width, int height, bool main_window=false, bool resizable=false);
HWND GetHWND() const { return hwnd_; }
bool IsOpen() const { return hwnd_ && IsWindow(hwnd_); }
void ShowWindow(int command=SW_SHOWNORMAL);
void CenterWindow();
void ActiveWindow();
void Close();
void Invalidate(); // coalesced to at most 30 paints per second
void Preview(); // refresh during interactive control tracking, limited to 30Hz
float Scale() const { return dpi_/96.f; }
float Width() const;
float Height() const;
void Place(HWND child, Rect rect);
HWND CreateEdit(int id, const wchar_t* cue);
static std::wstring EditText(HWND edit);
void FocusContent();
void ClearButtons();
void Button(int id, std::wstring label, Rect rect, bool primary=false);
bool SetOpacity(int percent); // Uniform window alpha, clamped to 30..100.
void SetBackgroundImage(const std::wstring& path);
bool HasBackgroundImage() const;
void SetBackgroundImageOpacity(float opacity);
void DrawBackground(Canvas& canvas, float opacity);
protected:
virtual void OnCreate() {}
virtual void OnLayout() {}
virtual void OnPaint(Canvas&) {}
virtual void OnCommand(int) {}
virtual std::optional<LRESULT> OnMessage(UINT, WPARAM, LPARAM) { return {}; }
private:
struct Impl;
std::unique_ptr<Impl> impl_;
static LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
static LRESULT CALLBACK EditProc(HWND,UINT,WPARAM,LPARAM,UINT_PTR,DWORD_PTR);
LRESULT Dispatch(UINT,WPARAM,LPARAM);
bool EnsureTarget();
void Paint();
void RefreshFont();
HBRUSH ControlBackground(HDC dc);
void DiscardControlBackground();
HWND hwnd_=nullptr;
float dpi_=96;
int opacity_percent_=100;
bool main_=false, dirty_=false, resizable_=false, initialized_=false, opacity_applied_=false;
};
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <windows.h>
#ifndef WM_DPICHANGED
#define WM_DPICHANGED 0x02E0
#endif
namespace ttui::compat {
inline UINT Dpi(HWND window=nullptr) {
HMODULE user=GetModuleHandleW(L"user32.dll");
if (window) {
using Function=UINT(WINAPI*)(HWND);
auto get=reinterpret_cast<Function>(GetProcAddress(user,"GetDpiForWindow"));
if (get) { UINT value=get(window); if (value) return value; }
}
using Function=UINT(WINAPI*)();
auto get=reinterpret_cast<Function>(GetProcAddress(user,"GetDpiForSystem"));
if (get) { UINT value=get(); if (value) return value; }
HDC dc=GetDC(nullptr); int value=dc?GetDeviceCaps(dc,LOGPIXELSX):96;
if (dc) ReleaseDC(nullptr,dc);
return value>0?static_cast<UINT>(value):96;
}
inline void EnableDpiAwareness() {
using Function=BOOL(WINAPI*)(HANDLE);
auto set=reinterpret_cast<Function>(GetProcAddress(GetModuleHandleW(L"user32.dll"),"SetProcessDpiAwarenessContext"));
if (set && (set(reinterpret_cast<HANDLE>(static_cast<INT_PTR>(-4))) || set(reinterpret_cast<HANDLE>(static_cast<INT_PTR>(-3))))) return;
SetProcessDPIAware();
}
inline void AdjustWindow(RECT& rect,DWORD style,UINT dpi) {
using Function=BOOL(WINAPI*)(LPRECT,DWORD,BOOL,DWORD,UINT);
auto adjust=reinterpret_cast<Function>(GetProcAddress(GetModuleHandleW(L"user32.dll"),"AdjustWindowRectExForDpi"));
if (adjust && adjust(&rect,style,FALSE,0,dpi)) return;
AdjustWindowRectEx(&rect,style,FALSE,0);
}
}
+167
View File
@@ -0,0 +1,167 @@
#include "ttui/aero_backdrop.h"
#include <string>
#include <dwmapi.h>
#include <cstdarg>
#include <cstdio>
#pragma comment(lib, "dwmapi.lib")
namespace ttui {
namespace
{
constexpr wchar_t kBackdropClassName[] = L"TTDownloaderAeroBackdrop";
void LogAero(const wchar_t* format, ...)
{
wchar_t temp[MAX_PATH] = {};
if (::GetTempPathW(MAX_PATH, temp) == 0)
return;
std::wstring path = std::wstring(temp) + L"TTDownloader_aero.log";
FILE* file = nullptr;
if (_wfopen_s(&file, path.c_str(), L"a") != 0 || file == nullptr)
return;
va_list args;
va_start(args, format);
vfwprintf(file, format, args);
va_end(args);
fputc(L'\n', file);
fclose(file);
}
}
AeroBackdrop::~AeroBackdrop()
{
Destroy();
}
bool AeroBackdrop::Create(HWND owner)
{
if (hwnd_ != nullptr)
return true;
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = &AeroBackdrop::WndProc;
wc.hInstance = ::GetModuleHandleW(nullptr);
wc.hCursor = ::LoadCursorW(nullptr, IDC_ARROW);
wc.lpszClassName = kBackdropClassName;
if (::RegisterClassExW(&wc) == 0 && ::GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
return false;
hwnd_ = ::CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT,
kBackdropClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, wc.hInstance, nullptr);
if (hwnd_ == nullptr)
return false;
BOOL composition = FALSE;
::DwmIsCompositionEnabled(&composition);
LogAero(L"create backdrop hwnd=%p composition=%d", hwnd_, composition);
Sync(owner);
return true;
}
void AeroBackdrop::Sync(HWND owner)
{
if (hwnd_ == nullptr || owner == nullptr)
return;
bool visible = ::IsWindowVisible(owner) != FALSE && ::IsIconic(owner) == FALSE;
if (!visible)
{
if (visible_)
{
visible_ = false;
::ShowWindow(hwnd_, SW_HIDE);
LogAero(L"sync hidden");
}
return;
}
RECT client = {};
::GetClientRect(owner, &client);
POINT origin = { client.left, client.top };
::ClientToScreen(owner, &origin);
::SetWindowPos(hwnd_, owner, origin.x, origin.y,
client.right - client.left, client.bottom - client.top, SWP_NOACTIVATE | SWP_SHOWWINDOW);
if (!visible_)
{
visible_ = true;
LogAero(L"sync visible rect=%d,%d %dx%d", origin.x, origin.y,
client.right - client.left, client.bottom - client.top);
}
ApplyGlass(client.right - client.left, client.bottom - client.top);
}
void AeroBackdrop::Refresh()
{
blur_width_ = 0;
blur_height_ = 0;
blur_enabled_ = false;
}
void AeroBackdrop::ApplyGlass(int width, int height)
{
if (blur_enabled_ && width == blur_width_ && height == blur_height_)
return;
blur_width_ = width;
blur_height_ = height;
DWM_BLURBEHIND blur = {};
blur.dwFlags = DWM_BB_ENABLE;
blur.fEnable = TRUE;
blur.hRgnBlur = nullptr;
HRESULT result = ::DwmEnableBlurBehindWindow(hwnd_, &blur);
blur_enabled_ = SUCCEEDED(result);
LogAero(L"enable blur size=%dx%d hr=0x%08X", width, height,
static_cast<unsigned int>(result));
::InvalidateRect(hwnd_, nullptr, TRUE);
}
void AeroBackdrop::Hide()
{
if (hwnd_ != nullptr && visible_)
{
visible_ = false;
::ShowWindow(hwnd_, SW_HIDE);
}
}
void AeroBackdrop::Destroy()
{
if (hwnd_ != nullptr)
{
::DestroyWindow(hwnd_);
hwnd_ = nullptr;
}
}
LRESULT CALLBACK AeroBackdrop::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_ERASEBKGND)
return 1;
if (uMsg == WM_PAINT)
{
PAINTSTRUCT ps = {};
HDC dc = ::BeginPaint(hwnd, &ps);
RECT client = {};
::GetClientRect(hwnd, &client);
::FillRect(dc, &client, static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH)));
::EndPaint(hwnd, &ps);
return 0;
}
return ::DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
} // namespace ttui
+25
View File
@@ -0,0 +1,25 @@
#include <windows.h>
#include <ole2.h>
#include "ttui/application.h"
#include "ttui/windows_compat.h"
#pragma comment(lib,"ole32.lib")
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
namespace ttui {
int RunApplication(const std::function<bool()>& create_windows) {
compat::EnableDpiAwareness();
HRESULT result=OleInitialize(nullptr);
if (FAILED(result)) return 1;
int code=1;
if (create_windows()) {
MSG message{};
BOOL status;
while ((status=GetMessageW(&message,nullptr,0,0))>0) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
code=status==-1 ? 1 : static_cast<int>(message.wParam);
}
OleUninitialize();
return code;
}
}
+390
View File
@@ -0,0 +1,390 @@
#include "ttui/window.h"
#include "ttui/windows_compat.h"
#include <windowsx.h>
#include <commctrl.h>
#include <wincodec.h>
#include <algorithm>
#include <chrono>
#include <future>
#include <limits>
#pragma comment(lib,"d2d1.lib")
#pragma comment(lib,"dwrite.lib")
#pragma comment(lib,"windowscodecs.lib")
#pragma comment(lib,"comctl32.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"gdi32.lib")
#pragma comment(lib,"msimg32.lib")
namespace ttui {
using Microsoft::WRL::ComPtr;
namespace {
constexpr UINT_PTR kPaintTimer=0x5454;
D2D1_COLOR_F Color(unsigned rgb, float opacity=1) { return D2D1::ColorF(rgb,opacity); }
struct Pixels { UINT width=0,height=0; std::vector<BYTE> bytes; };
Pixels Decode(const std::wstring& path) {
Pixels pixels;
HRESULT init=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if (FAILED(init)) return pixels;
{
ComPtr<IWICImagingFactory> factory;
ComPtr<IWICBitmapDecoder> decoder;
ComPtr<IWICBitmapFrameDecode> frame;
ComPtr<IWICFormatConverter> converter;
if (SUCCEEDED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory)))
&& SUCCEEDED(factory->CreateDecoderFromFilename(path.c_str(),nullptr,GENERIC_READ,WICDecodeMetadataCacheOnLoad,&decoder))
&& SUCCEEDED(decoder->GetFrame(0,&frame)) && SUCCEEDED(frame->GetSize(&pixels.width,&pixels.height))
&& pixels.width>0 && pixels.height>0 && pixels.width<=8192 && pixels.height<=8192
&& static_cast<size_t>(pixels.width)*pixels.height<=32*1024*1024
&& SUCCEEDED(factory->CreateFormatConverter(&converter))
&& SUCCEEDED(converter->Initialize(frame.Get(),GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom))) {
pixels.bytes.resize(static_cast<size_t>(pixels.width)*pixels.height*4);
if (FAILED(converter->CopyPixels(nullptr,pixels.width*4,static_cast<UINT>(pixels.bytes.size()),pixels.bytes.data()))) pixels={};
}
}
CoUninitialize();
return pixels;
}
}
struct Window::Impl {
struct Button { int id; std::wstring label; Rect rect; bool primary; };
std::vector<Button> buttons;
int hot=-1,pressed=-1,focus=-1;
ULONGLONG last_paint=0;
HFONT font=nullptr;
HBRUSH control_background=nullptr;
float image_opacity=1;
ComPtr<ID2D1Factory> factory;
ComPtr<IDWriteFactory> text;
ComPtr<ID2D1HwndRenderTarget> target;
ComPtr<ID2D1Bitmap> bitmap;
Pixels pixels;
std::wstring desired_path,loading_path;
std::future<Pixels> pending;
};
void Canvas::Fill(Rect rect,unsigned rgb,float opacity) {
ComPtr<ID2D1SolidColorBrush> brush;
if (SUCCEEDED(target_->CreateSolidColorBrush(Color(rgb,opacity),&brush))) target_->FillRectangle(rect.Native(),brush.Get());
}
void Canvas::Text(const std::wstring& value,Rect rect,unsigned rgb,float size,bool bold,DWRITE_TEXT_ALIGNMENT alignment) {
if (rect.right<=rect.left || rect.bottom<=rect.top) return;
ComPtr<IDWriteTextFormat> format;
ComPtr<ID2D1SolidColorBrush> brush;
if (FAILED(text_->CreateTextFormat(L"Microsoft YaHei UI",nullptr,bold?DWRITE_FONT_WEIGHT_SEMI_BOLD:DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,DWRITE_FONT_STRETCH_NORMAL,size,L"zh-CN",&format))
|| FAILED(target_->CreateSolidColorBrush(Color(rgb),&brush))) return;
format->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
format->SetTextAlignment(alignment);
format->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
DWRITE_TRIMMING trim{}; trim.granularity=DWRITE_TRIMMING_GRANULARITY_CHARACTER;
ComPtr<IDWriteInlineObject> ellipsis;
if (SUCCEEDED(text_->CreateEllipsisTrimmingSign(format.Get(),&ellipsis))) format->SetTrimming(&trim,ellipsis.Get());
target_->DrawText(value.c_str(),static_cast<UINT32>(value.size()),format.Get(),rect.Native(),brush.Get(),D2D1_DRAW_TEXT_OPTIONS_CLIP);
}
void Canvas::Progress(Rect rect,double fraction) {
rect.right=rect.left+(rect.right-rect.left)*static_cast<float>(std::clamp(fraction,0.0,1.0));
Fill(rect,0x307EF3);
}
Window::Window():impl_(std::make_unique<Impl>()) {}
Window::~Window() {
if (IsOpen()) DestroyWindow(hwnd_);
if (impl_->font) DeleteObject(impl_->font);
if (impl_->control_background) DeleteObject(impl_->control_background);
}
bool Window::Create(HWND owner,const wchar_t* cls,const wchar_t* title,int width,int height,bool main_window,bool resizable) {
if (IsOpen()) return false;
main_=main_window; resizable_=resizable; initialized_=false; opacity_applied_=false;
// A render target belongs to one HWND, including when this C++ object is reused.
impl_->bitmap.Reset(); impl_->target.Reset(); DiscardControlBackground();
impl_->buttons.clear(); impl_->hot=impl_->pressed=impl_->focus=-1;
impl_->last_paint=0; dirty_=true;
WNDCLASSEXW wc{sizeof(wc)};
wc.hInstance=GetModuleHandleW(nullptr); wc.lpfnWndProc=WndProc;
wc.lpszClassName=cls; wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);
wc.hIcon=LoadIconW(nullptr,IDI_APPLICATION); wc.style=CS_DBLCLKS;
if (!RegisterClassExW(&wc) && GetLastError()!=ERROR_CLASS_ALREADY_EXISTS) return false;
dpi_=static_cast<float>(compat::Dpi());
DWORD style=WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_CLIPCHILDREN;
if (resizable_) style|=WS_THICKFRAME|WS_MAXIMIZEBOX;
RECT bounds{0,0,static_cast<LONG>(width*Scale()),static_cast<LONG>(height*Scale())};
compat::AdjustWindow(bounds,style,static_cast<UINT>(dpi_));
HWND created=CreateWindowExW(opacity_percent_<100?WS_EX_LAYERED:0,cls,title,style,CW_USEDEFAULT,CW_USEDEFAULT,bounds.right-bounds.left,bounds.bottom-bounds.top,
owner,nullptr,wc.hInstance,this);
if (!created) return false;
if (!SetOpacity(opacity_percent_)) { DestroyWindow(created); return false; }
return true;
}
void Window::RefreshFont() {
HFONT old=impl_->font;
impl_->font=CreateFontW(-MulDiv(14,static_cast<int>(dpi_),96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Microsoft YaHei UI");
EnumChildWindows(hwnd_,[](HWND child,LPARAM font)->BOOL { SendMessageW(child,WM_SETFONT,font,TRUE); return TRUE; },reinterpret_cast<LPARAM>(impl_->font));
if (old) DeleteObject(old);
}
void Window::ShowWindow(int command) {
if (command==SW_HIDE) { ::ShowWindow(hwnd_,command); return; }
if (!IsOpen() || !SetOpacity(opacity_percent_)) return;
// Prepare the first frame while hidden; do not expose an unpainted opaque surface.
if (!IsWindowVisible(hwnd_) && initialized_) { InvalidateRect(hwnd_,nullptr,FALSE); Paint(); }
::ShowWindow(hwnd_,command);
}
void Window::CenterWindow() {
RECT window{},area{}; GetWindowRect(hwnd_,&window);
MONITORINFO info{sizeof(info)};
GetMonitorInfoW(MonitorFromWindow(GetWindow(hwnd_,GW_OWNER)?GetWindow(hwnd_,GW_OWNER):hwnd_,MONITOR_DEFAULTTONEAREST),&info); area=info.rcWork;
SetWindowPos(hwnd_,nullptr,area.left+(area.right-area.left-(window.right-window.left))/2,
area.top+(area.bottom-area.top-(window.bottom-window.top))/2,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
void Window::ActiveWindow() { ShowWindow(SW_RESTORE); SetForegroundWindow(hwnd_); }
void Window::Close() { if (IsOpen()) SendMessageW(hwnd_,WM_CLOSE,0,0); }
void Window::Invalidate() { dirty_=true; }
void Window::Preview() {
Invalidate();
if (IsOpen() && GetTickCount64()-impl_->last_paint>=33) {
dirty_=false;
InvalidateRect(hwnd_,nullptr,FALSE);
UpdateWindow(hwnd_);
}
}
float Window::Width() const { RECT r{}; GetClientRect(hwnd_,&r); return r.right/Scale(); }
float Window::Height() const { RECT r{}; GetClientRect(hwnd_,&r); return r.bottom/Scale(); }
void Window::Place(HWND child,Rect r) {
MoveWindow(child,static_cast<int>(r.left*Scale()),static_cast<int>(r.top*Scale()),
std::max(1,static_cast<int>((r.right-r.left)*Scale())),std::max(1,static_cast<int>((r.bottom-r.top)*Scale())),TRUE);
}
HWND Window::CreateEdit(int id,const wchar_t* cue) {
HWND edit=CreateWindowExW(WS_EX_CLIENTEDGE,L"EDIT",L"",WS_CHILD|WS_VISIBLE|WS_TABSTOP|ES_AUTOHSCROLL,
0,0,1,1,hwnd_,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
SendMessageW(edit,WM_SETFONT,reinterpret_cast<WPARAM>(impl_->font),TRUE);
SendMessageW(edit,EM_SETCUEBANNER,FALSE,reinterpret_cast<LPARAM>(cue));
SendMessageW(edit,EM_SETLIMITTEXT,32767,0);
SetWindowSubclass(edit,EditProc,1,reinterpret_cast<DWORD_PTR>(this));
return edit;
}
std::wstring Window::EditText(HWND edit) {
int length=GetWindowTextLengthW(edit);
std::wstring text(static_cast<size_t>(length)+1,L'\0');
int copied=GetWindowTextW(edit,text.data(),length+1); text.resize(copied); return text;
}
void Window::FocusContent() { impl_->focus=-1; SetFocus(hwnd_); Invalidate(); }
void Window::ClearButtons() { impl_->buttons.clear(); }
void Window::Button(int id,std::wstring label,Rect rect,bool primary) { impl_->buttons.push_back({id,std::move(label),rect,primary}); }
bool Window::SetOpacity(int percent) {
percent=std::clamp(percent,30,100);
if (!IsOpen()) { opacity_percent_=percent; opacity_applied_=false; return true; }
if (opacity_applied_ && opacity_percent_==percent) return true;
LONG_PTR style=GetWindowLongPtrW(hwnd_,GWL_EXSTYLE);
if (!(style&WS_EX_LAYERED)) {
if (percent==100) { opacity_percent_=percent; opacity_applied_=true; return true; }
SetLastError(ERROR_SUCCESS);
if (!SetWindowLongPtrW(hwnd_,GWL_EXSTYLE,style|WS_EX_LAYERED) && GetLastError()!=ERROR_SUCCESS) return false;
}
BYTE alpha=static_cast<BYTE>((percent*255+50)/100);
if (!SetLayeredWindowAttributes(hwnd_,0,alpha,LWA_ALPHA)) return false;
opacity_percent_=percent; opacity_applied_=true;
return true;
}
void Window::SetBackgroundImage(const std::wstring& path) {
if (impl_->desired_path==path) return;
impl_->desired_path=path; impl_->pixels={}; impl_->bitmap.Reset(); DiscardControlBackground(); Invalidate();
}
void Window::SetBackgroundImageOpacity(float opacity) {
opacity=std::clamp(opacity,0.f,1.f);
if (impl_->image_opacity==opacity) return;
impl_->image_opacity=opacity; DiscardControlBackground(); Invalidate();
if (IsOpen()) RedrawWindow(hwnd_,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
void Window::DiscardControlBackground() {
if (impl_->control_background) { DeleteObject(impl_->control_background); impl_->control_background=nullptr; }
}
HBRUSH Window::ControlBackground(HDC dc) {
if (impl_->control_background) return impl_->control_background;
RECT client{}; GetClientRect(hwnd_,&client);
int width=std::max(1L,client.right),height=std::max(1L,client.bottom);
HDC memory=CreateCompatibleDC(dc);
HBITMAP surface=CreateCompatibleBitmap(dc,width,height);
if (!memory || !surface) { if (memory) DeleteDC(memory); if (surface) DeleteObject(surface); return static_cast<HBRUSH>(GetStockObject(HOLLOW_BRUSH)); }
auto old=SelectObject(memory,surface);
SetDCBrushColor(memory,RGB(240,243,248)); FillRect(memory,&client,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
const auto& pixels=impl_->pixels;
if (!pixels.bytes.empty() && impl_->image_opacity>0) {
BITMAPINFO info{}; info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth=pixels.width; info.bmiHeader.biHeight=-static_cast<LONG>(pixels.height);
info.bmiHeader.biPlanes=1; info.bmiHeader.biBitCount=32; info.bmiHeader.biCompression=BI_RGB;
void* bits=nullptr; HBITMAP image=CreateDIBSection(dc,&info,DIB_RGB_COLORS,&bits,nullptr,0);
HDC source=CreateCompatibleDC(dc);
if (image && source && bits) {
memcpy(bits,pixels.bytes.data(),pixels.bytes.size());
auto previous=SelectObject(source,image);
BLENDFUNCTION blend{AC_SRC_OVER,0,static_cast<BYTE>(impl_->image_opacity*255),AC_SRC_ALPHA};
AlphaBlend(memory,0,0,width,height,source,0,0,pixels.width,pixels.height,blend);
SelectObject(source,previous);
}
if (source) DeleteDC(source); if (image) DeleteObject(image);
}
impl_->control_background=CreatePatternBrush(surface);
SelectObject(memory,old); DeleteObject(surface); DeleteDC(memory);
return impl_->control_background?impl_->control_background:static_cast<HBRUSH>(GetStockObject(HOLLOW_BRUSH));
}
bool Window::HasBackgroundImage() const { return !impl_->pixels.bytes.empty(); }
void Window::DrawBackground(Canvas& canvas,float opacity) {
if (impl_->pixels.bytes.empty()) return;
if (!impl_->bitmap) canvas.Target()->CreateBitmap(D2D1::SizeU(impl_->pixels.width,impl_->pixels.height),impl_->pixels.bytes.data(),
impl_->pixels.width*4,D2D1::BitmapProperties(D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,D2D1_ALPHA_MODE_PREMULTIPLIED)),&impl_->bitmap);
if (impl_->bitmap) canvas.Target()->DrawBitmap(impl_->bitmap.Get(),D2D1::RectF(0,0,Width(),Height()),opacity);
}
bool Window::EnsureTarget() {
if (!impl_->factory && FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,impl_->factory.GetAddressOf()))) return false;
if (!impl_->text && FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,__uuidof(IDWriteFactory),reinterpret_cast<IUnknown**>(impl_->text.GetAddressOf())))) return false;
if (!impl_->target) {
RECT r{}; GetClientRect(hwnd_,&r);
auto properties=D2D1::RenderTargetProperties(); properties.dpiX=dpi_; properties.dpiY=dpi_;
if (FAILED(impl_->factory->CreateHwndRenderTarget(properties,D2D1::HwndRenderTargetProperties(hwnd_,D2D1::SizeU(r.right,r.bottom)),&impl_->target))) return false;
}
return true;
}
void Window::Paint() {
impl_->last_paint=GetTickCount64();
PAINTSTRUCT ps{}; BeginPaint(hwnd_,&ps);
if (EnsureTarget()) {
impl_->target->BeginDraw(); impl_->target->Clear(Color(0xF0F3F8));
Canvas canvas(impl_->target.Get(),impl_->text.Get()); DrawBackground(canvas,impl_->image_opacity); OnPaint(canvas);
for (size_t i=0;i<impl_->buttons.size();++i) {
auto& b=impl_->buttons[i];
const bool hot=impl_->hot==static_cast<int>(i);
const bool pressed=impl_->pressed==static_cast<int>(i);
const bool focused=GetFocus()==hwnd_ && impl_->focus==static_cast<int>(i);
unsigned text_color=b.primary?0x245CB0:0x273449;
unsigned border_color=b.primary?0x307EF3:0xAAB8C8;
if (hot || focused) { text_color=0x2066D2; border_color=0x307EF3; }
if (pressed) { text_color=0x123B7A; border_color=0x123B7A; }
ComPtr<ID2D1SolidColorBrush> border;
if (SUCCEEDED(impl_->target->CreateSolidColorBrush(Color(border_color),&border))) {
auto outline=D2D1::RoundedRect(D2D1::RectF(b.rect.left+1,b.rect.top+1,b.rect.right-1,b.rect.bottom-1),3,3);
impl_->target->DrawRoundedRectangle(outline,border.Get(),focused || pressed?2.f:1.f);
}
auto text=b.rect; text.left+=6; text.right-=6;
if (pressed) { text.top+=1; text.bottom+=1; }
canvas.Text(b.label,text,text_color,14,b.primary,DWRITE_TEXT_ALIGNMENT_CENTER);
}
HRESULT result=impl_->target->EndDraw();
if (FAILED(result)) { impl_->bitmap.Reset(); impl_->target.Reset(); Invalidate(); }
} else {
FillRect(ps.hdc,&ps.rcPaint,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
const wchar_t* failure=L"无法初始化 Direct2D / DirectWrite,请检查显卡驱动。";
DrawTextW(ps.hdc,failure,-1,&ps.rcPaint,DT_LEFT|DT_WORDBREAK); Invalidate();
}
EndPaint(hwnd_,&ps);
}
LRESULT CALLBACK Window::EditProc(HWND edit,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data) {
auto* self=reinterpret_cast<Window*>(data);
if (msg==WM_KEYDOWN && wp==VK_RETURN) { self->OnCommand(GetDlgCtrlID(edit)); return 0; }
if (msg==WM_KEYDOWN && wp==VK_TAB) {
HWND next=GetNextDlgTabItem(self->hwnd_,edit,GetKeyState(VK_SHIFT)<0);
if (next && next!=edit && (GetKeyState(VK_SHIFT)<0 || GetDlgCtrlID(next)>GetDlgCtrlID(edit))) SetFocus(next);
else { SetFocus(self->hwnd_); self->impl_->focus=self->impl_->buttons.empty()?-1:0; }
self->Invalidate(); return 0;
}
if (msg==WM_NCDESTROY) RemoveWindowSubclass(edit,EditProc,1);
return DefSubclassProc(edit,msg,wp,lp);
}
LRESULT CALLBACK Window::WndProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp) {
auto* self=reinterpret_cast<Window*>(GetWindowLongPtrW(hwnd,GWLP_USERDATA));
if (msg==WM_NCCREATE) {
self=static_cast<Window*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams);
self->hwnd_=hwnd; self->dpi_=static_cast<float>(compat::Dpi(hwnd));
SetWindowLongPtrW(hwnd,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(self));
if (!self->SetOpacity(self->opacity_percent_)) return FALSE;
}
if (!self) return DefWindowProcW(hwnd,msg,wp,lp);
LRESULT result=self->Dispatch(msg,wp,lp);
if (msg==WM_NCDESTROY) {
self->initialized_=false; self->opacity_applied_=false;
self->impl_->bitmap.Reset(); self->impl_->target.Reset(); self->DiscardControlBackground();
self->impl_->hot=self->impl_->pressed=self->impl_->focus=-1;
SetWindowLongPtrW(hwnd,GWLP_USERDATA,0); self->hwnd_=nullptr;
}
return result;
}
LRESULT Window::Dispatch(UINT msg,WPARAM wp,LPARAM lp) {
if (auto result=OnMessage(msg,wp,lp)) return *result;
switch (msg) {
case WM_CREATE:
RefreshFont(); SetTimer(hwnd_,kPaintTimer,33,nullptr); OnCreate(); initialized_=true; OnLayout(); return 0;
case WM_ERASEBKGND: return 1;
case WM_PAINT: Paint(); return 0;
case WM_SIZE:
if (!initialized_) return 0;
DiscardControlBackground();
if (impl_->target) impl_->target->Resize(D2D1::SizeU(LOWORD(lp),HIWORD(lp)));
OnLayout(); Invalidate(); return 0;
case WM_DPICHANGED: {
dpi_=static_cast<float>(HIWORD(wp));
if (impl_->target) impl_->target->SetDpi(dpi_,dpi_);
RefreshFont(); auto* r=reinterpret_cast<RECT*>(lp);
SetWindowPos(hwnd_,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER|SWP_NOACTIVATE);
OnLayout(); Invalidate(); return 0;
}
case WM_TIMER:
if (wp==kPaintTimer) {
if (impl_->pending.valid() && impl_->pending.wait_for(std::chrono::seconds(0))==std::future_status::ready) {
try { auto result=impl_->pending.get(); if (impl_->loading_path==impl_->desired_path) impl_->pixels=std::move(result); }
catch (...) { impl_->pixels={}; }
DiscardControlBackground();
RedrawWindow(hwnd_,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); Invalidate();
}
if (!impl_->pending.valid() && impl_->loading_path!=impl_->desired_path) {
impl_->loading_path=impl_->desired_path;
if (!impl_->loading_path.empty()) impl_->pending=std::async(std::launch::async,Decode,impl_->loading_path);
}
if (dirty_ && GetTickCount64()-impl_->last_paint>=33) { dirty_=false; InvalidateRect(hwnd_,nullptr,FALSE); }
return 0;
} break;
case WM_MOUSEMOVE: {
float x=GET_X_LPARAM(lp)/Scale(),y=GET_Y_LPARAM(lp)/Scale(); int hot=-1;
for (size_t i=0;i<impl_->buttons.size();++i) if (impl_->buttons[i].rect.Contains(x,y)) hot=static_cast<int>(i);
if (hot!=impl_->hot) { impl_->hot=hot; Invalidate(); }
TRACKMOUSEEVENT track{sizeof(track),TME_LEAVE,hwnd_,0}; TrackMouseEvent(&track); break;
}
case WM_MOUSELEAVE: impl_->hot=-1; Invalidate(); break;
case WM_LBUTTONDOWN: {
float x=GET_X_LPARAM(lp)/Scale(),y=GET_Y_LPARAM(lp)/Scale();
for (size_t i=0;i<impl_->buttons.size();++i) if (impl_->buttons[i].rect.Contains(x,y)) {
impl_->pressed=impl_->focus=static_cast<int>(i); SetFocus(hwnd_); SetCapture(hwnd_); Invalidate(); return 0;
} break;
}
case WM_LBUTTONUP:
if (impl_->pressed>=0 && impl_->pressed<static_cast<int>(impl_->buttons.size())) {
auto button=impl_->buttons[impl_->pressed]; impl_->pressed=-1; ReleaseCapture(); Invalidate();
if (button.rect.Contains(GET_X_LPARAM(lp)/Scale(),GET_Y_LPARAM(lp)/Scale())) OnCommand(button.id);
return 0;
} break;
case WM_CAPTURECHANGED: impl_->pressed=-1; Invalidate(); break;
case WM_KEYDOWN:
if (wp==VK_TAB && !impl_->buttons.empty()) {
int next=impl_->focus+(GetKeyState(VK_SHIFT)<0?-1:1);
if (next<0 || next>=static_cast<int>(impl_->buttons.size())) {
HWND edit=GetNextDlgTabItem(hwnd_,nullptr,FALSE);
if (edit) SetFocus(edit); else next=0;
}
impl_->focus=next; Invalidate(); return 0;
}
if ((wp==VK_SPACE || wp==VK_RETURN) && impl_->focus>=0 && impl_->focus<static_cast<int>(impl_->buttons.size())) {
OnCommand(impl_->buttons[impl_->focus].id); return 0;
} break;
case WM_SETFOCUS: case WM_KILLFOCUS: Invalidate(); break;
case WM_CTLCOLOREDIT: case WM_CTLCOLORSTATIC: case WM_CTLCOLORSCROLLBAR: {
HDC dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,RGB(39,52,73)); SetBkMode(dc,TRANSPARENT);
POINT origin{}; MapWindowPoints(reinterpret_cast<HWND>(lp),hwnd_,&origin,1);
SetBrushOrgEx(dc,-origin.x,-origin.y,nullptr);
return reinterpret_cast<LRESULT>(ControlBackground(dc));
}
case WM_SYSCOMMAND:
if (!resizable_ && ((wp&0xfff0)==SC_SIZE || (wp&0xfff0)==SC_MAXIMIZE)) return 0;
break;
case WM_COMMAND: if (HIWORD(wp)==0) OnCommand(LOWORD(wp)); return 0;
case WM_CLOSE: DestroyWindow(hwnd_); return 0;
case WM_DESTROY: KillTimer(hwnd_,kPaintTimer); if (main_) PostQuitMessage(0); return 0;
}
return DefWindowProcW(hwnd_,msg,wp,lp);
}
}
+215
View File
@@ -0,0 +1,215 @@
#include "ttui/application.h"
#include "ttui/window.h"
#include "ttui/virtual_list.h"
#include "platform.h"
#include "task_store.h"
#include "settings_form.h"
#include "add_task_form.h"
#include <future>
#include <commctrl.h>
#include <iostream>
#include <stdexcept>
#include <filesystem>
#include <fstream>
#include <chrono>
static void Check(bool ok,const char* message) { if (!ok) throw std::runtime_error(message); }
static void CheckAlpha(ttui::Window& window,int percent) {
if (percent==100 && !(GetWindowLongPtrW(window.GetHWND(),GWL_EXSTYLE)&WS_EX_LAYERED)) return;
BYTE alpha=0; DWORD flags=0;
Check(GetLayeredWindowAttributes(window.GetHWND(),nullptr,&alpha,&flags)!=FALSE,"read actual window alpha");
Check((flags&LWA_ALPHA) && alpha==(percent*255+50)/100,"native window alpha matches percentage");
}
class SmokeWindow final : public ttui::Window {
public:
HWND edit=nullptr;
int commands=0,paints=0;
bool painted=false;
HWND renderer_window=nullptr;
BYTE initial_alpha=255;
bool initially_visible=false;
~SmokeWindow() override { if (IsOpen()) DestroyWindow(GetHWND()); }
private:
void OnCreate() override {
initially_visible=IsWindowVisible(GetHWND())!=FALSE;
DWORD flags=0;
if (GetWindowLongPtrW(GetHWND(),GWL_EXSTYLE)&WS_EX_LAYERED)
GetLayeredWindowAttributes(GetHWND(),nullptr,&initial_alpha,&flags);
edit=CreateEdit(100,L"输入测试");
}
void OnLayout() override { Place(edit,{10,10,300,44}); ClearButtons(); Button(200,L"按钮",{10,60,130,100}); }
void OnPaint(ttui::Canvas& c) override {
++paints; renderer_window=c.Target()->GetHwnd(); DrawBackground(c,1); c.Text(L"TTUI 中文绘制",{10,110,300,150}); c.Progress({10,160,300,166},.5); painted=true;
}
void OnCommand(int) override { ++commands; }
};
int main() {
try {
ttui::VirtualList list;
list.Configure(100000,10); list.ScrollTo(999999);
auto [first,last]=list.Visible(); Check(first==99990 && last==100000,"viewport end clamp");
list.Select(123); list.RevealSelection(); Check(list.First()==123,"selection above viewport");
list.Select(900); list.RevealSelection(); Check(list.First()==891,"selection below viewport");
list.Configure(3,10); Check(list.First()==0 && list.Selected()==2,"list shrink clamps state");
list.Configure(0,0); Check(list.Selected()==-1 && list.Visible().first==list.Visible().second,"empty viewport");
list.Configure(100000,10); Check(list.Visible().second-list.Visible().first<=11,"bounded row rendering");
const std::wstring sample=L"中文路径/任务🚀";
Check(platform::FromUtf8(platform::ToUtf8(sample))==sample,"UTF-8 roundtrip");
Check(platform::FromUtf8(std::string("\xff",1)).empty(),"invalid UTF-8 rejected");
Check(platform::ToUtf8(std::wstring(1,static_cast<wchar_t>(0xD800))).empty(),"unpaired surrogate rejected");
std::wstring embedded(L"a\0b",3); Check(platform::FromUtf8(platform::ToUtf8(embedded))==embedded,"embedded NUL conversion");
// All database access stays on a worker, using an isolated test file.
auto database_test=std::async(std::launch::async,[] {
auto folder=std::filesystem::current_path()/L"ui"/L"ttui"/L"obj";
std::filesystem::create_directories(folder);
auto path=folder/(L"test_tasks_"+std::to_wstring(GetCurrentProcessId())+L".db");
TaskStore store; Check(store.Open(path.wstring()),"open isolated SQLite store");
TaskInfo task; task.url=L"https://example.test/中文🚀.bin";
task.file_name=L"中文🚀.bin"; task.save_path=L"D:\\下载\\中文🚀.bin";
Check(store.Insert(task) && task.id>0,"insert task with Unicode");
Check(store.UpdateProgress(task.id,123,456),"persist progress");
Check(store.UpdateState(task.id,TaskState::kPaused,123,456,L"暂停测试"),"persist state");
store.Close(); Check(store.Open(path.wstring()),"reopen store");
auto restored=store.LoadTasks();
Check(restored.size()==1 && restored[0].url==task.url && restored[0].save_path==task.save_path
&& restored[0].file_name==task.file_name && restored[0].state==TaskState::kPaused
&& restored[0].downloaded_bytes==123 && restored[0].error==L"暂停测试","task recovery and UTF-8 persistence");
Check(store.DeleteTask(task.id) && store.LoadTasks().empty(),"remove isolated task");
store.Close();
std::filesystem::remove(path);
std::filesystem::remove(path.wstring()+L"-wal"); std::filesystem::remove(path.wstring()+L"-shm");
});
database_test.get();
SmokeWindow window;
int code=ttui::RunApplication([&] {
Check(window.Create(nullptr,L"TTUISmokeWindow",L"TTUI smoke",640,400,true),"create independent window");
Check((GetWindowLongPtrW(window.GetHWND(),GWL_STYLE)&(WS_THICKFRAME|WS_MAXIMIZEBOX))==0,"windows are fixed size by default");
SmokeWindow reopened;
for (int generation=0;generation<3;++generation) {
Check(reopened.Create(window.GetHWND(),L"TTUIReopenSmoke",L"Reopen smoke",640,240),"recreate the same window object");
SendMessageW(reopened.GetHWND(),WM_PAINT,0,0);
Check(reopened.paints==generation+1 && reopened.renderer_window==reopened.GetHWND(),"renderer must bind the new HWND on every reopen");
SendMessageW(reopened.GetHWND(),WM_LBUTTONDOWN,MK_LBUTTON,MAKELPARAM(static_cast<int>(30*reopened.Scale()),static_cast<int>(75*reopened.Scale())));
SendMessageW(reopened.GetHWND(),WM_LBUTTONUP,0,MAKELPARAM(static_cast<int>(30*reopened.Scale()),static_cast<int>(75*reopened.Scale())));
Check(reopened.commands==generation+1,"buttons remain interactive after reopen");
reopened.Close();
}
SkinSettings appearance;
Check(appearance.window_alpha_percent==100,"default window opacity is 100 percent");
SmokeWindow preconfigured;
preconfigured.SetOpacity(67);
for (int generation=0;generation<3;++generation) {
Check(preconfigured.Create(window.GetHWND(),L"TTUIInitialAlphaSmoke",L"Initial alpha smoke",640,240),"create preconfigured translucent window");
Check(preconfigured.initial_alpha==(67*255+50)/100 && !preconfigured.initially_visible,"native alpha must be ready before OnCreate and first show");
CheckAlpha(preconfigured,67);
preconfigured.Close();
}
SmokeWindow opacity_peer;
Check(opacity_peer.Create(window.GetHWND(),L"TTUIOpacityPeer",L"Opacity peer",640,240),"create second window for shared opacity");
int previews=0,closed=0;
SettingsForm settings(&appearance,[&] { ++previews; window.SetOpacity(appearance.window_alpha_percent); opacity_peer.SetOpacity(appearance.window_alpha_percent); window.Preview(); },[&] { ++closed; });
Check(settings.Create(window.GetHWND(),SettingsForm::kClassName.c_str(),L"Settings smoke",600,440),"create appearance settings");
HWND slider=GetDlgItem(settings.GetHWND(),100);
Check(slider!=nullptr && GetDlgItem(settings.GetHWND(),101)!=nullptr && GetDlgItem(settings.GetHWND(),102)==nullptr,"background coverage and unified window opacity sliders only");
SendMessageW(slider,TBM_SETPOS,TRUE,100);
int before=previews;
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_THUMBTRACK,37),reinterpret_cast<LPARAM>(slider));
Check(appearance.window_opacity==37 && previews==before+1,"live background preview before release");
SendMessageW(slider,TBM_SETPOS,TRUE,52);
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_LINEUP,0),reinterpret_cast<LPARAM>(slider));
Check(appearance.window_opacity==52,"keyboard background slider change");
HWND alpha_slider=GetDlgItem(settings.GetHWND(),101);
Check(SendMessageW(alpha_slider,TBM_GETRANGEMIN,0,0)==30 && SendMessageW(alpha_slider,TBM_GETRANGEMAX,0,0)==100
&& SendMessageW(alpha_slider,TBM_GETPOS,0,0)==100,"window opacity slider bounds and default");
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_THUMBTRACK,67),reinterpret_cast<LPARAM>(alpha_slider));
Check(appearance.window_alpha_percent==67 && appearance.window_opacity==52,"window transparency independent of background coverage");
CheckAlpha(window,67); CheckAlpha(opacity_peer,67); CheckAlpha(settings,67);
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_THUMBTRACK,0),reinterpret_cast<LPARAM>(alpha_slider));
Check(appearance.window_alpha_percent==30,"opacity is clamped to 30 percent minimum");
CheckAlpha(window,30); CheckAlpha(opacity_peer,30); CheckAlpha(settings,30);
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_THUMBPOSITION,1000),reinterpret_cast<LPARAM>(alpha_slider));
Check(appearance.window_alpha_percent==100,"opacity is clamped to 100 percent maximum");
CheckAlpha(window,100); CheckAlpha(opacity_peer,100); CheckAlpha(settings,100);
SendMessageW(settings.GetHWND(),WM_HSCROLL,MAKEWPARAM(TB_THUMBTRACK,67),reinterpret_cast<LPARAM>(alpha_slider));
opacity_peer.Close();
settings.Close(); Check(closed==1,"appearance close callback once");
int submissions=0;
std::wstring submitted_url,submitted_directory;
AddTaskForm add(&appearance,[&](const std::wstring& url,const std::wstring& directory) {
++submissions; submitted_url=url; submitted_directory=directory; return true;
});
Check(add.Create(window.GetHWND(),AddTaskForm::kClassName.c_str(),L"Add task smoke",640,240),"create independent add window");
CheckAlpha(add,67); // Windows created after a slider change inherit shared opacity.
HWND url_edit=GetDlgItem(add.GetHWND(),100),path_edit=GetDlgItem(add.GetHWND(),101);
Check(url_edit && path_edit,"download fields in add window");
SendMessageW(add.GetHWND(),WM_COMMAND,200,0);
Check(submissions==0 && !add.Pending() && add.IsOpen(),"blank URL must keep add window open");
SetWindowTextW(url_edit,L" https://example.test/中文.bin "); SetWindowTextW(path_edit,L"D:\\下载");
SendMessageW(url_edit,WM_KEYDOWN,VK_RETURN,0);
Check(submissions==1 && add.Pending() && add.IsOpen() && submitted_url==L"https://example.test/中文.bin"
&& submitted_directory==L"D:\\下载","submit entered URL and directory, wait for acknowledgement");
SendMessageW(add.GetHWND(),WM_COMMAND,200,0);
Check(submissions==1,"prevent duplicate submissions while pending");
add.Complete(false,L"链接已存在");
Check(add.IsOpen() && !add.Pending() && IsWindowEnabled(url_edit)
&& ttui::Window::EditText(url_edit).find(L"example.test")!=std::wstring::npos,"rejection preserves editable input");
SendMessageW(add.GetHWND(),WM_COMMAND,200,0); Check(submissions==2 && add.Pending(),"retry after rejection");
add.Close();
Check(add.Pending() && !add.IsOpen(),"closing pending window retains acknowledgement state");
Check(add.Create(window.GetHWND(),AddTaskForm::kClassName.c_str(),L"Add task smoke",640,240),"reopen pending window");
Check(!IsWindowEnabled(GetDlgItem(add.GetHWND(),100)),"reopen must not duplicate pending request");
add.Complete(true); Check(!add.IsOpen() && !add.Pending(),"acceptance closes add window");
Check(add.Create(window.GetHWND(),AddTaskForm::kClassName.c_str(),L"Add task smoke",640,240),"open next add window");
Check(ttui::Window::EditText(GetDlgItem(add.GetHWND(),100)).empty()
&& ttui::Window::EditText(GetDlgItem(add.GetHWND(),101))==L"D:\\下载","accepted URL cleared and save directory retained");
add.Close();
SetWindowTextW(window.edit,L"中文输入内容");
Check(ttui::Window::EditText(window.edit)==L"中文输入内容","native edit roundtrip");
Check(window.commands==0,"editing must not submit command");
SendMessageW(window.GetHWND(),WM_PAINT,0,0);
Check(window.painted,"Direct2D/DirectWrite paint callback");
float scale=window.Scale();
auto point=[&](int x,int y) { return MAKELPARAM(static_cast<int>(x*scale),static_cast<int>(y*scale)); };
SendMessageW(window.GetHWND(),WM_LBUTTONDOWN,MK_LBUTTON,point(30,75));
SendMessageW(window.GetHWND(),WM_LBUTTONUP,0,point(30,75));
Check(window.commands==1,"button click dispatch");
SendMessageW(window.GetHWND(),WM_LBUTTONDOWN,MK_LBUTTON,point(30,75));
SendMessageW(window.GetHWND(),WM_LBUTTONUP,0,point(350,200));
Check(window.commands==1,"release outside cancels command");
SendMessageW(window.GetHWND(),WM_KEYDOWN,VK_RETURN,0); Check(window.commands==2,"keyboard button activation");
window.FocusContent();
SendMessageW(window.GetHWND(),WM_KEYDOWN,VK_RETURN,0); Check(window.commands==2,"content focus must not activate old button");
SendMessageW(window.edit,WM_KEYDOWN,VK_RETURN,0); Check(window.commands==3,"edit Return submits once");
SetWindowPos(window.GetHWND(),nullptr,0,0,800,600,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(window.GetHWND(),WM_PAINT,0,0); Check(window.paints>=2,"resize repaint");
auto image_path=std::filesystem::current_path()/L"ui"/L"ttui"/L"obj"/(L"test_image_"+std::to_wstring(GetCurrentProcessId())+L".bmp");
const unsigned char bmp[]={
0x42,0x4d,58,0,0,0,0,0,0,0,54,0,0,0,40,0,0,0,
1,0,0,0,1,0,0,0,1,0,24,0,0,0,0,0,4,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x20,0x80,0xe0,0
};
{ std::ofstream file(image_path,std::ios::binary); file.write(reinterpret_cast<const char*>(bmp),sizeof(bmp)); }
window.SetBackgroundImage(image_path.wstring());
auto start=std::chrono::steady_clock::now();
while (!window.HasBackgroundImage() && std::chrono::steady_clock::now()-start<std::chrono::seconds(5)) {
MSG message{};
while (PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) { TranslateMessage(&message); DispatchMessageW(&message); }
Sleep(5);
}
Check(window.HasBackgroundImage(),"asynchronous WIC background decode");
SendMessageW(window.GetHWND(),WM_PAINT,0,0);
window.SetBackgroundImage(L""); Check(!window.HasBackgroundImage(),"clear background cache");
std::filesystem::remove(image_path);
window.Close(); return true;
});
Check(code==0 && !window.IsOpen(),"message loop and native window cleanup");
std::cout<<"PASS: virtual viewport, UTF conversion, isolated SQLite recovery, edit dispatch, Direct2D paint, buttons, focus, resize, WIC background, background coverage tracking, unified live window alpha, pre-show alpha initialization, repeated HWND rendering, add-window submission lifecycle, shutdown\n";
return 0;
} catch (const std::exception& error) { std::cerr<<"FAIL: "<<error.what()<<"\n"; return 1; }
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals"><ProjectGuid>{7681588A-169D-4197-A811-92CB6CF697F0}</ProjectGuid><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<Import Project="..\ttui.props" />
<PropertyGroup><OutDir>$(ProjectDir)..\lib\$(Platform)\$(Configuration)\</OutDir><IntDir>$(ProjectDir)..\obj\$(Platform)\tests\$(Configuration)\</IntDir></PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<LanguageStandard>stdcpp20</LanguageStandard><AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
<PreprocessorDefinitions>UNICODE;_UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\third_party\sqlite3;$(ProjectDir)..\..\..\client\src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
<ExceptionHandling>Sync</ExceptionHandling>
</ClCompile>
<Link><SubSystem>Console</SubSystem><AdditionalDependencies>uuid.lib;%(AdditionalDependencies)</AdditionalDependencies></Link>
</ItemDefinitionGroup>
<ItemGroup><ClCompile Include="smoke.cpp" /><ClCompile Include="..\..\..\client\src\add_task_form.cpp" /><ClCompile Include="..\..\..\client\src\settings_form.cpp" /><ClCompile Include="..\..\..\client\src\task_store.cpp" /><ClCompile Include="..\..\..\third_party\sqlite3\sqlite3.c"><WarningLevel>TurnOffAllWarnings</WarningLevel></ClCompile></ItemGroup>
<ItemGroup><ProjectReference Include="..\ttui.vcxproj"><Project>{19F8F655-C0F5-4AD9-B999-58D23F95AB43}</Project></ProjectReference></ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<TTUIRoot>$(MSBuildThisFileDirectory)</TTUIRoot>
<IncludePath>$(TTUIRoot)include;$(IncludePath)</IncludePath>
<VcpkgEnabled>false</VcpkgEnabled>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile><PreprocessorDefinitions>NOMINMAX;_WIN32_WINNT=0x0601;WINVER=0x0601;%(PreprocessorDefinitions)</PreprocessorDefinitions></ClCompile>
<Link><MinimumRequiredVersion>6.01</MinimumRequiredVersion></Link>
</ItemDefinitionGroup>
</Project>
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform></ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals"><ProjectGuid>{19F8F655-C0F5-4AD9-B999-58D23F95AB43}</ProjectGuid><RootNamespace>ttui</RootNamespace><VcpkgEnabled>false</VcpkgEnabled></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType><PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet>
<UseDebugLibraries Condition="'$(Configuration)'=='Debug'">true</UseDebugLibraries>
<UseDebugLibraries Condition="'$(Configuration)'=='Release'">false</UseDebugLibraries>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<Import Project="ttui.props" />
<PropertyGroup><OutDir>$(ProjectDir)lib\$(Platform)\$(Configuration)\</OutDir><IntDir>$(ProjectDir)obj\$(Platform)\$(Configuration)\</IntDir></PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader><WarningLevel>Level3</WarningLevel><LanguageStandard>stdcpp20</LanguageStandard><ExceptionHandling>Sync</ExceptionHandling>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
<PreprocessorDefinitions>WIN32;_WINDOWS;UNICODE;_UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary Condition="'$(Configuration)'=='Debug'">MultiThreadedDebug</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)'=='Release'">MultiThreaded</RuntimeLibrary>
<Optimization Condition="'$(Configuration)'=='Debug'">Disabled</Optimization>
<Optimization Condition="'$(Configuration)'=='Release'">MaxSpeed</Optimization>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="include\ttui\application.h" /><ClInclude Include="include\ttui\windows_compat.h" /><ClInclude Include="include\ttui\window.h" /><ClInclude Include="include\ttui\virtual_list.h" /><ClInclude Include="include\ttui\aero_backdrop.h" />
<ClCompile Include="src\application.cpp" /><ClCompile Include="src\window.cpp" /><ClCompile Include="src\aero_backdrop.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>