替换 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

+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);
}
}