Files
crown/Update/UpdateWindow.cpp

857 lines
31 KiB
C++

#define NOMINMAX
#include "UpdateWindow.h"
#include "Config.h"
#include "Utils.h"
#include <windows.h>
#include <windowsx.h>
#include <objbase.h>
#include <objidl.h>
#include <shlwapi.h>
#include <shobjidl.h>
#include <algorithm>
#include <string>
// GDI+ 头文件依赖未限定的 min/max
using std::min;
using std::max;
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "ole32.lib")
namespace updater {
namespace {
const UINT kWmState = WM_APP + 1;
const UINT kTimerClose = 1;
const int kWidth = UPDATER_WINDOW_WIDTH;
const int kHeight = UPDATER_WINDOW_HEIGHT;
// VS 2019 是直角窗口,窗口和控件都不做圆角
const int kTitleH = 32; // 标题栏高度
const int kCloseSize = 32; // 关闭按钮是标题栏右侧的正方形
const int kCloseMarginX = 0;
const int kCloseMarginY = 0;
const int kMarginX = 24;
// 标题区
const int kHeadY = 46;
const int kHeadH = 26;
const int kSubY = 74;
const int kSubH = 20;
// 更新日志卡片
const int kLogX = kMarginX;
const int kLogY = 100;
const int kLogW = kWidth - kMarginX * 2;
const int kLogH = 180;
const int kLogPadX = 16;
const int kLogTitleY = kLogY + 12;
const int kLogTitleH = 22;
const int kLogTextY = kLogTitleY + kLogTitleH + 4;
const int kLogTextH = kLogY + kLogH - 12 - kLogTextY;
const int kLogTextW = kLogW - kLogPadX * 2;
// 状态行与进度条
const int kStatusY = kLogY + kLogH + 12;
const int kStatusH = 22;
const int kBarX = kMarginX;
const int kBarY = kStatusY + kStatusH + 10;
const int kBarW = kWidth - kMarginX * 2;
const int kBarH = 10;
// 安装目录选择面板
const int kPickPanelX = kMarginX;
const int kPickPanelW = kWidth - kMarginX * 2;
const int kPickTextX = kPickPanelX;
const int kPickTitleY = 46;
const int kPickHintY = 78;
const int kPathX = kPickPanelX;
const int kPathY = 126;
const int kPathW = kPickPanelW - 12 - 104;
const int kPathH = 34;
const int kBrowseX = kPathX + kPathW + 12;
const int kBrowseW = 104;
const int kSpaceY = 176;
const int kButtonY = 298;
const int kButtonH = 38;
const int kInstallW = 140;
const int kInstallX = kWidth - kMarginX - kInstallW;
const int kCancelW = 104;
const int kCancelX = kInstallX - 12 - kCancelW;
// 更新日志一屏滚动的步长
const int kScrollStep = 24;
const wchar_t* const kFontName = L"Segoe UI";
// Visual Studio 2019 暗色主题取色
const Gdiplus::ARGB kArgbWindow = 0xFF1E1E1E; // 窗口背景
const Gdiplus::ARGB kArgbTitleBar = 0xFF2D2D30; // 标题栏
const Gdiplus::ARGB kArgbSurface = 0xFF252526; // 卡片/面板
const Gdiplus::ARGB kArgbControl = 0xFF333337; // 输入框/按钮/进度条轨道
const Gdiplus::ARGB kArgbBorder = 0xFF3F3F46; // 分隔线/边框
const Gdiplus::ARGB kArgbHover = 0xFF3E3E42; // 控件悬停
const Gdiplus::ARGB kArgbAccent = 0xFF007ACC; // 强调蓝
const Gdiplus::ARGB kArgbAccentHover = 0xFF1B8AD6;
const Gdiplus::ARGB kArgbAccentPress = 0xFF005C9E;
const Gdiplus::ARGB kArgbText = 0xFFFFFFFF;
const Gdiplus::ARGB kArgbTextDim = 0xFFCCCCCC;
const Gdiplus::ARGB kArgbTextWeak = 0xFF999999;
const Gdiplus::ARGB kArgbCloseHover = 0xFFE81123; // 关闭按钮悬停红
const Gdiplus::ARGB kArgbClosePress = 0xFFB01018;
const Gdiplus::ARGB kArgbError = 0xFFE81123;
// 1 像素描边:GDI+ 默认会把整数坐标的边框画成两像素灰边,内缩半像素才是清晰的一条线
void DrawHairline(Gdiplus::Graphics& graphics, const Gdiplus::Rect& rect, Gdiplus::ARGB color) {
Gdiplus::Pen pen(color, 1.0f);
graphics.DrawRectangle(&pen,
Gdiplus::RectF(static_cast<float>(rect.X) + 0.5f,
static_cast<float>(rect.Y) + 0.5f,
static_cast<float>(rect.Width) - 1.0f,
static_cast<float>(rect.Height) - 1.0f));
}
// VS 2019 的按钮是直角矩形:主按钮强调蓝实底,次按钮深灰底 + 灰描边
void DrawButton(Gdiplus::Graphics& graphics, int x, int y, int w, int h, const wchar_t* text,
bool primary, int state) {
Gdiplus::Rect rect(x, y, w, h);
Gdiplus::Color textColor;
if (primary) {
Gdiplus::ARGB fill = state == 2 ? kArgbAccentPress : state == 1 ? kArgbAccentHover : kArgbAccent;
Gdiplus::SolidBrush brush(fill);
graphics.FillRectangle(&brush, rect);
textColor = Gdiplus::Color(kArgbText);
} else {
Gdiplus::ARGB fill = state == 2 ? kArgbSurface : state == 1 ? kArgbHover : kArgbControl;
Gdiplus::SolidBrush brush(fill);
graphics.FillRectangle(&brush, rect);
DrawHairline(graphics, rect, kArgbBorder);
textColor = Gdiplus::Color(state == 0 ? kArgbTextDim : kArgbText);
}
Gdiplus::StringFormat format;
format.SetAlignment(Gdiplus::StringAlignmentCenter);
format.SetLineAlignment(Gdiplus::StringAlignmentCenter);
Gdiplus::Font font(kFontName, 13.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::SolidBrush textBrush(textColor);
Gdiplus::RectF textRect(static_cast<float>(x), static_cast<float>(y), static_cast<float>(w),
static_cast<float>(h));
graphics.DrawString(text, -1, &font, textRect, &format, &textBrush);
}
std::wstring PercentText(int percent) {
return std::to_wstring(percent) + L"%";
}
// 完整包安装时的默认目录:更新器由主程序从自身目录启动,默认就装到主程序所在目录
std::wstring DefaultInstallDir() {
std::wstring custom = UPDATER_DEFAULT_INSTALL_DIR;
if (!custom.empty()) return custom;
return Utils::GetModuleDir();
}
// 目录可能还不存在,向上回溯到存在的祖先再取可用空间
bool QueryFreeSpace(const std::wstring& path, unsigned long long& freeBytes) {
std::wstring probe = path;
while (!probe.empty() && !Utils::DirExists(probe)) {
std::wstring parent = Utils::GetParentDir(probe);
if (parent.empty() || parent == probe) break;
probe = parent;
}
if (probe.empty()) return false;
ULARGE_INTEGER available;
if (!GetDiskFreeSpaceExW(probe.c_str(), &available, nullptr, nullptr)) return false;
freeBytes = available.QuadPart;
return true;
}
}
struct UpdateWindow::RenderContext {
ULONG_PTR token = 0;
};
UpdateWindow::UpdateWindow() : render_(new RenderContext()) {
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
Gdiplus::GdiplusStartupInput input;
Gdiplus::GdiplusStartup(&render_->token, &input, nullptr);
}
UpdateWindow::~UpdateWindow() {
if (render_) {
if (render_->token) Gdiplus::GdiplusShutdown(render_->token);
delete render_;
render_ = nullptr;
}
CoUninitialize();
}
bool UpdateWindow::Create(HINSTANCE instance, const UpdateOptions& options) {
instance_ = instance;
options_ = options;
WNDCLASSW wc;
ZeroMemory(&wc, sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = &UpdateWindow::WndProc;
wc.hInstance = instance;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = nullptr;
wc.lpszClassName = L"VerifyUpdaterWindowClass";
RegisterClassW(&wc);
int screenX = GetSystemMetrics(SM_CXSCREEN);
int screenY = GetSystemMetrics(SM_CYSCREEN);
int left = (screenX - kWidth) / 2;
int top = (screenY - kHeight) / 2;
// 分层窗口:整体画在 32 位位图上再提交,圆角由 GDI+ 抗锯齿,不会有锯齿边
hwnd_ = CreateWindowExW(WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW, wc.lpszClassName,
UPDATER_TITLE, WS_POPUP, left, top, kWidth, kHeight, nullptr, nullptr,
instance, this);
if (!hwnd_) return false;
// 完整包安装且没有指定目录时,先让用户选安装目录
// 必须在首次显示之前定好阶段,否则首帧会画成更新进度面板
bool pickDir = options.fullMode && options.targetDir.empty();
if (pickDir) {
phase_ = Phase::PickDir;
installDir_ = DefaultInstallDir();
status_ = L"请选择安装目录";
} else {
phase_ = Phase::Updating;
status_ = options.fullMode ? L"正在准备完整包更新..." : L"正在检查版本更新...";
}
Render();
ShowWindow(hwnd_, SW_SHOW);
Render();
if (!pickDir) StartWorker(options);
return true;
}
void UpdateWindow::StartWorker(const UpdateOptions& options) {
HWND hwnd = hwnd_;
worker_.Start(options,
[this, hwnd](int percent, const std::wstring& text) {
UiState* state = new UiState();
state->percent = percent;
state->status = text;
PostMessageW(hwnd, kWmState, 0, reinterpret_cast<LPARAM>(state));
},
[this, hwnd](bool ok, const std::wstring& text) {
UiState* state = new UiState();
state->percent = ok ? 100 : percent_;
state->status = text;
state->finished = true;
state->success = ok;
PostMessageW(hwnd, kWmState, 0, reinterpret_cast<LPARAM>(state));
},
[this, hwnd](const UpdateInfo& info) {
UiState* state = new UiState();
state->hasInfo = true;
state->info = info;
PostMessageW(hwnd, kWmState, 0, reinterpret_cast<LPARAM>(state));
});
}
bool UpdateWindow::BrowseFolder() {
IFileDialog* dialog = nullptr;
HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dialog));
if (FAILED(hr)) return false;
DWORD options = 0;
if (SUCCEEDED(dialog->GetOptions(&options))) {
dialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
}
dialog->SetTitle(L"选择安装目录");
if (!installDir_.empty() && Utils::DirExists(installDir_)) {
IShellItem* folder = nullptr;
if (SUCCEEDED(SHCreateItemFromParsingName(installDir_.c_str(), nullptr,
IID_PPV_ARGS(&folder)))) {
dialog->SetFolder(folder);
folder->Release();
}
}
bool changed = false;
if (SUCCEEDED(dialog->Show(hwnd_))) {
IShellItem* item = nullptr;
if (SUCCEEDED(dialog->GetResult(&item))) {
wchar_t* path = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &path)) && path) {
installDir_ = path;
changed = true;
CoTaskMemFree(path);
}
item->Release();
}
}
dialog->Release();
return changed;
}
void UpdateWindow::StartUpdate() {
if (started_ || installDir_.empty()) return;
started_ = true;
phase_ = Phase::Updating;
closeState_ = browseState_ = installState_ = cancelState_ = 0;
pressed_ = 0;
UpdateOptions options = options_;
options.targetDir = installDir_;
status_ = L"正在准备安装...";
Invalidate();
StartWorker(options);
}
int UpdateWindow::MessageLoop() {
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return static_cast<int>(msg.wParam);
}
void UpdateWindow::Invalidate() {
if (hwnd_) InvalidateRect(hwnd_, nullptr, FALSE);
}
bool UpdateWindow::HitCloseButton(int x, int y) const {
int left = kWidth - kCloseMarginX - kCloseSize;
return x >= left && x <= left + kCloseSize && y >= kCloseMarginY &&
y <= kCloseMarginY + kCloseSize;
}
bool UpdateWindow::HitBrowseButton(int x, int y) const {
return phase_ == Phase::PickDir && x >= kBrowseX && x <= kBrowseX + kBrowseW && y >= kPathY &&
y <= kPathY + kPathH;
}
bool UpdateWindow::HitInstallButton(int x, int y) const {
return phase_ == Phase::PickDir && x >= kInstallX && x <= kInstallX + kInstallW &&
y >= kButtonY && y <= kButtonY + kButtonH;
}
bool UpdateWindow::HitCancelButton(int x, int y) const {
return phase_ == Phase::PickDir && x >= kCancelX && x <= kCancelX + kCancelW &&
y >= kButtonY && y <= kButtonY + kButtonH;
}
bool UpdateWindow::HitAnyButton(int x, int y) const {
return HitCloseButton(x, y) || HitBrowseButton(x, y) || HitInstallButton(x, y) ||
HitCancelButton(x, y);
}
void UpdateWindow::UpdateHover(int x, int y) {
int close = HitCloseButton(x, y) ? (pressed_ == 1 ? 2 : 1) : 0;
int browse = HitBrowseButton(x, y) ? (pressed_ == 2 ? 2 : 1) : 0;
int install = HitInstallButton(x, y) ? (pressed_ == 3 ? 2 : 1) : 0;
int cancel = HitCancelButton(x, y) ? (pressed_ == 4 ? 2 : 1) : 0;
if (close != closeState_ || browse != browseState_ || install != installState_ ||
cancel != cancelState_) {
closeState_ = close;
browseState_ = browse;
installState_ = install;
cancelState_ = cancel;
Invalidate();
}
}
void UpdateWindow::RequestClose() {
if (closing_) return;
closing_ = true;
if (phase_ == Phase::Updating && !finished_) {
status_ = L"正在取消更新...";
Invalidate();
}
worker_.Cancel();
DestroyWindow(hwnd_);
}
void UpdateWindow::ApplyInfo(const UpdateInfo& info) {
info_ = info;
// 后台可能只填了其中一个,两个都没有时给句占位说明
std::wstring text = info.changelog;
if (text.empty()) text = info.updateNotes;
if (text.empty()) text = L"本次更新包含功能优化与稳定性改进。";
changelogText_ = text;
if (info.currentVersion.empty() && !options_.clientVersion.empty()) {
info_.currentVersion = options_.clientVersion;
}
changelogScroll_ = 0;
Invalidate();
}
void UpdateWindow::ScrollChangelog(int delta) {
int maxScroll = (std::max)(0, changelogContentH_ - kLogTextH);
int next = changelogScroll_ + delta;
next = (std::max)(0, (std::min)(maxScroll, next));
if (next != changelogScroll_) {
changelogScroll_ = next;
Invalidate();
}
}
void UpdateWindow::OnState(const UiState& state) {
if (closing_) return;
if (state.hasInfo) {
ApplyInfo(state.info);
return;
}
percent_ = std::max(0, std::min(100, state.percent));
status_ = state.status;
if (state.finished) {
finished_ = true;
success_ = state.success;
if (success_) SetTimer(hwnd_, kTimerClose, 1500, nullptr);
}
Invalidate();
}
void UpdateWindow::DrawPickPanel(Gdiplus::Graphics& graphics) {
Gdiplus::StringFormat nearFormat;
nearFormat.SetAlignment(Gdiplus::StringAlignmentNear);
nearFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
nearFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisWord);
Gdiplus::SolidBrush textBrush(kArgbText);
Gdiplus::SolidBrush dimBrush(kArgbTextDim);
Gdiplus::Font titleFont(kFontName, 16.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF titleRect(static_cast<float>(kPickTextX), static_cast<float>(kPickTitleY),
static_cast<float>(kPickPanelW), 26.0f);
std::wstring appName = UPDATER_APP_NAME;
std::wstring titleText =
appName.empty() ? L"选择安装目录" : (L"选择 " + appName + L" 的安装目录");
graphics.DrawString(titleText.c_str(), -1, &titleFont, titleRect, &nearFormat, &textBrush);
Gdiplus::Font hintFont(kFontName, 13.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF hintRect(static_cast<float>(kPickTextX), static_cast<float>(kPickHintY),
static_cast<float>(kPickPanelW), 22.0f);
graphics.DrawString(L"请选择程序的安装位置,目录下的同名文件会被覆盖", -1, &hintFont, hintRect,
&nearFormat, &dimBrush);
// 路径输入框:控件底色 + 灰描边,直角
Gdiplus::Rect boxRect(kPathX, kPathY, kPathW, kPathH);
Gdiplus::SolidBrush boxBrush(kArgbControl);
graphics.FillRectangle(&boxBrush, boxRect);
DrawHairline(graphics, boxRect, kArgbBorder);
Gdiplus::StringFormat pathFormat;
pathFormat.SetAlignment(Gdiplus::StringAlignmentNear);
pathFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
pathFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisPath);
Gdiplus::Font pathFont(kFontName, 14.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF pathRect(static_cast<float>(kPathX + 12), static_cast<float>(kPathY),
static_cast<float>(kPathW - 24), static_cast<float>(kPathH));
graphics.DrawString(installDir_.c_str(), -1, &pathFont, pathRect, &pathFormat, &textBrush);
DrawButton(graphics, kBrowseX, kPathY, kBrowseW, kPathH, L"浏览...", false, browseState_);
// 可用空间与目录状态
std::wstring spaceText;
unsigned long long freeBytes = 0;
if (QueryFreeSpace(installDir_, freeBytes)) {
spaceText = L"可用空间 " + Utils::FormatSize(freeBytes);
}
if (Utils::DirExists(installDir_)) {
if (!spaceText.empty()) spaceText += L" ";
spaceText += L"目录已存在,将覆盖其中的同名文件";
}
if (!spaceText.empty()) {
Gdiplus::RectF spaceRect(static_cast<float>(kPickTextX), static_cast<float>(kSpaceY),
static_cast<float>(kPickPanelW), 22.0f);
graphics.DrawString(spaceText.c_str(), -1, &hintFont, spaceRect, &nearFormat, &dimBrush);
}
DrawButton(graphics, kCancelX, kButtonY, kCancelW, kButtonH, L"取消", false, cancelState_);
DrawButton(graphics, kInstallX, kButtonY, kInstallW, kButtonH, L"开始安装", true,
installState_);
}
// VS 2019 暗色主题:纯色窗口背景 + 一条标题栏,不做渐变和装饰
void UpdateWindow::DrawBackground(Gdiplus::Graphics& graphics) {
Gdiplus::SolidBrush windowBrush(kArgbWindow);
graphics.FillRectangle(&windowBrush, 0, 0, kWidth, kHeight);
Gdiplus::SolidBrush titleBrush(kArgbTitleBar);
graphics.FillRectangle(&titleBrush, 0, 0, kWidth, kTitleH);
// 标题栏与内容区之间的分隔线,取整像素位置避免被抗锯齿糊掉
Gdiplus::Pen line(kArgbBorder, 1.0f);
graphics.DrawLine(&line, Gdiplus::PointF(0.0f, static_cast<float>(kTitleH) - 0.5f),
Gdiplus::PointF(static_cast<float>(kWidth), static_cast<float>(kTitleH) - 0.5f));
Gdiplus::Font font(kFontName, 12.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::StringFormat format;
format.SetAlignment(Gdiplus::StringAlignmentNear);
format.SetLineAlignment(Gdiplus::StringAlignmentCenter);
format.SetTrimming(Gdiplus::StringTrimmingEllipsisWord);
Gdiplus::SolidBrush textBrush(kArgbTextDim);
Gdiplus::RectF rect(10.0f, 0.0f, static_cast<float>(kWidth - kCloseSize - 16),
static_cast<float>(kTitleH));
graphics.DrawString(UPDATER_TITLE, -1, &font, rect, &format, &textBrush);
}
// 更新日志:先量出文本总高度,再按滚动偏移裁剪绘制
void UpdateWindow::DrawChangelog(Gdiplus::Graphics& graphics) {
Gdiplus::Rect card(kLogX, kLogY, kLogW, kLogH);
Gdiplus::SolidBrush cardBrush(kArgbSurface);
graphics.FillRectangle(&cardBrush, card);
DrawHairline(graphics, card, kArgbBorder);
Gdiplus::SolidBrush titleBrush(kArgbText);
Gdiplus::Font titleFont(kFontName, 13.0f, Gdiplus::FontStyleBold, Gdiplus::UnitPixel);
Gdiplus::RectF titleRect(static_cast<float>(kLogX + kLogPadX), static_cast<float>(kLogTitleY),
static_cast<float>(kLogTextW), static_cast<float>(kLogTitleH));
graphics.DrawString(L"更新内容", -1, &titleFont, titleRect, nullptr, &titleBrush);
std::wstring text = changelogText_.empty() ? L"正在获取更新说明..." : changelogText_;
Gdiplus::Font textFont(kFontName, 12.5f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::StringFormat format;
format.SetAlignment(Gdiplus::StringAlignmentNear);
format.SetLineAlignment(Gdiplus::StringAlignmentNear);
format.SetTrimming(Gdiplus::StringTrimmingNone);
Gdiplus::RectF measureRect(0.0f, 0.0f, static_cast<float>(kLogTextW), 10000.0f);
Gdiplus::RectF needed;
graphics.MeasureString(text.c_str(), -1, &textFont, measureRect, &format, &needed);
changelogContentH_ = static_cast<int>(needed.Height + 0.999f);
int maxScroll = (std::max)(0, changelogContentH_ - kLogTextH);
if (changelogScroll_ > maxScroll) changelogScroll_ = maxScroll;
if (changelogScroll_ < 0) changelogScroll_ = 0;
graphics.SetClip(Gdiplus::Rect(kLogX + kLogPadX, kLogTextY, kLogTextW, kLogTextH));
Gdiplus::SolidBrush textBrush(kArgbTextDim);
Gdiplus::RectF drawRect(static_cast<float>(kLogX + kLogPadX),
static_cast<float>(kLogTextY - changelogScroll_),
static_cast<float>(kLogTextW), static_cast<float>(needed.Height));
graphics.DrawString(text.c_str(), -1, &textFont, drawRect, &format, &textBrush);
graphics.ResetClip();
// 内容超出时给个滚动提示
if (maxScroll > 0) {
Gdiplus::SolidBrush hintBrush(kArgbTextWeak);
Gdiplus::Font hintFont(kFontName, 11.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::StringFormat farFormat;
farFormat.SetAlignment(Gdiplus::StringAlignmentFar);
farFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
Gdiplus::RectF hintRect(static_cast<float>(kLogTextW - 150),
static_cast<float>(kLogTitleY), 150.0f,
static_cast<float>(kLogTitleH));
graphics.DrawString(L"滚轮可滚动", -1, &hintFont, hintRect, &farFormat, &hintBrush);
}
}
void UpdateWindow::DrawProgressPanel(Gdiplus::Graphics& graphics) {
Gdiplus::SolidBrush textBrush(kArgbText);
Gdiplus::SolidBrush dimBrush(kArgbTextDim);
Gdiplus::StringFormat nearFormat;
nearFormat.SetAlignment(Gdiplus::StringAlignmentNear);
nearFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
nearFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisWord);
std::wstring headText = L"正在检查更新";
std::wstring subText = UPDATER_APP_NAME;
if (info_.hasUpdate) {
if (!info_.latestVersion.empty()) headText = L"发现新版本 " + info_.latestVersion;
if (!info_.currentVersion.empty() && !info_.latestVersion.empty()) {
subText = L"当前 " + info_.currentVersion + L" → 最新 " + info_.latestVersion;
}
}
Gdiplus::Font headFont(kFontName, 17.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF headRect(static_cast<float>(kMarginX), static_cast<float>(kHeadY),
static_cast<float>(kWidth - kMarginX * 2 - kCloseSize),
static_cast<float>(kHeadH));
graphics.DrawString(headText.c_str(), -1, &headFont, headRect, &nearFormat, &textBrush);
Gdiplus::Font subFont(kFontName, 12.5f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF subRect(static_cast<float>(kMarginX), static_cast<float>(kSubY),
static_cast<float>(kWidth - kMarginX * 2), static_cast<float>(kSubH));
graphics.DrawString(subText.c_str(), -1, &subFont, subRect, &nearFormat, &dimBrush);
DrawChangelog(graphics);
Gdiplus::Font statusFont(kFontName, 13.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF statusRect(static_cast<float>(kBarX), static_cast<float>(kStatusY),
static_cast<float>(kBarW - 90), static_cast<float>(kStatusH));
graphics.DrawString(status_.c_str(), -1, &statusFont, statusRect, &nearFormat, &dimBrush);
Gdiplus::StringFormat farFormat;
farFormat.SetAlignment(Gdiplus::StringAlignmentFar);
farFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
Gdiplus::Font percentFont(kFontName, 13.0f, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::RectF percentRect(static_cast<float>(kBarX + kBarW - 80),
static_cast<float>(kStatusY), 80.0f, static_cast<float>(kStatusH));
graphics.DrawString(PercentText(percent_).c_str(), -1, &percentFont, percentRect, &farFormat,
&textBrush);
Gdiplus::SolidBrush trackBrush(kArgbControl);
graphics.FillRectangle(&trackBrush, kBarX, kBarY, kBarW, kBarH);
int fillW = static_cast<int>(static_cast<double>(kBarW) * percent_ / 100.0);
if (fillW > 0) {
// 失败时转 VS 的错误红,正常时是主题蓝
bool failed = finished_ && !success_;
Gdiplus::SolidBrush fillBrush(failed ? kArgbError : kArgbAccent);
graphics.FillRectangle(&fillBrush, kBarX, kBarY, fillW, kBarH);
}
}
// 标题栏右侧的关闭按钮:悬停/按下时整块变红,和 VS 2019 一致
void UpdateWindow::DrawCloseButton(Gdiplus::Graphics& graphics) {
int left = kWidth - kCloseSize;
if (closeState_ != 0) {
Gdiplus::SolidBrush bg(closeState_ == 2 ? kArgbClosePress : kArgbCloseHover);
graphics.FillRectangle(&bg, left, 0, kCloseSize, kTitleH);
}
float cx = static_cast<float>(left + kCloseSize / 2);
float cy = static_cast<float>(kTitleH / 2);
float a = 5.0f;
Gdiplus::Pen pen(kArgbText, 1.4f);
pen.SetStartCap(Gdiplus::LineCapRound);
pen.SetEndCap(Gdiplus::LineCapRound);
pen.SetLineJoin(Gdiplus::LineJoinRound);
graphics.DrawLine(&pen, cx - a, cy - a, cx + a, cy + a);
graphics.DrawLine(&pen, cx + a, cy - a, cx - a, cy + a);
}
// 分层窗口:整窗画到 32 位 DIB 上再一次性提交。
// 圆角、斜切色块、进度条全部走 GDI+ 抗锯齿,边缘不会出现锯齿
void UpdateWindow::Render() {
if (!hwnd_) return;
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = kWidth;
bi.bmiHeader.biHeight = -kHeight; // 负值 = 自上而下,省一次翻转
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
HDC screenDc = GetDC(nullptr);
HBITMAP dib = CreateDIBSection(screenDc, &bi, DIB_RGB_COLORS, &bits, nullptr, 0);
ReleaseDC(nullptr, screenDc);
if (!dib || !bits) {
if (dib) DeleteObject(dib);
return;
}
HDC memDc = CreateCompatibleDC(nullptr);
HGDIOBJ oldBmp = SelectObject(memDc, dib);
{
Gdiplus::Bitmap bitmap(kWidth, kHeight, kWidth * 4, PixelFormat32bppARGB,
static_cast<BYTE*>(bits));
Gdiplus::Graphics graphics(&bitmap);
graphics.SetTextRenderingHint(Gdiplus::TextRenderingHintAntiAliasGridFit);
graphics.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
graphics.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHalf);
DrawBackground(graphics);
if (phase_ == Phase::PickDir) {
DrawPickPanel(graphics);
} else {
DrawProgressPanel(graphics);
}
DrawCloseButton(graphics);
DrawHairline(graphics, Gdiplus::Rect(0, 0, kWidth, kHeight), kArgbBorder);
}
POINT ptSrc = {0, 0};
RECT wr;
GetWindowRect(hwnd_, &wr);
POINT ptDst = {wr.left, wr.top};
SIZE size = {kWidth, kHeight};
BLENDFUNCTION blend;
blend.BlendOp = AC_SRC_OVER;
blend.BlendFlags = 0;
blend.SourceConstantAlpha = 255;
blend.AlphaFormat = AC_SRC_ALPHA;
UpdateLayeredWindow(hwnd_, nullptr, &ptDst, &size, memDc, &ptSrc, 0, &blend, ULW_ALPHA);
SelectObject(memDc, oldBmp);
DeleteDC(memDc);
DeleteObject(dib);
}
void UpdateWindow::OnPaint() {
PAINTSTRUCT ps;
BeginPaint(hwnd_, &ps);
EndPaint(hwnd_, &ps);
Render();
}
LRESULT UpdateWindow::HandleMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_PAINT:
OnPaint();
return 0;
case WM_ERASEBKGND:
return 1;
case kWmState: {
UiState* state = reinterpret_cast<UiState*>(lParam);
if (state) {
OnState(*state);
delete state;
}
return 0;
}
case WM_NCHITTEST: {
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
ScreenToClient(hwnd_, &pt);
// 按钮区域交给客户区消息处理,其余部分允许拖动窗口
if (HitAnyButton(pt.x, pt.y)) return HTCLIENT;
return HTCAPTION;
}
case WM_MOUSEMOVE: {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
UpdateHover(x, y);
if (!tracking_) {
TRACKMOUSEEVENT tme;
ZeroMemory(&tme, sizeof(tme));
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hwnd_;
TrackMouseEvent(&tme);
tracking_ = true;
}
return 0;
}
case WM_MOUSEWHEEL: {
if (phase_ != Phase::PickDir) {
int delta = GET_WHEEL_DELTA_WPARAM(wParam);
ScrollChangelog(-delta / WHEEL_DELTA * kScrollStep);
}
return 0;
}
case WM_MOUSELEAVE:
tracking_ = false;
pressed_ = 0;
if (closeState_ != 0 || browseState_ != 0 || installState_ != 0 || cancelState_ != 0) {
closeState_ = browseState_ = installState_ = cancelState_ = 0;
Invalidate();
}
return 0;
case WM_LBUTTONDOWN: {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
if (HitCloseButton(x, y)) pressed_ = 1;
else if (HitBrowseButton(x, y)) pressed_ = 2;
else if (HitInstallButton(x, y)) pressed_ = 3;
else if (HitCancelButton(x, y)) pressed_ = 4;
else pressed_ = 0;
UpdateHover(x, y);
return 0;
}
case WM_LBUTTONUP: {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
int hit = pressed_;
pressed_ = 0;
UpdateHover(x, y);
if (hit == 1 && HitCloseButton(x, y)) {
RequestClose();
} else if (hit == 2 && HitBrowseButton(x, y)) {
if (BrowseFolder()) Invalidate();
} else if (hit == 3 && HitInstallButton(x, y)) {
StartUpdate();
} else if (hit == 4 && HitCancelButton(x, y)) {
RequestClose();
}
return 0;
}
case WM_TIMER:
if (wParam == kTimerClose) {
KillTimer(hwnd_, kTimerClose);
closing_ = true;
DestroyWindow(hwnd_);
}
return 0;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE) RequestClose();
if (phase_ == Phase::PickDir && wParam == VK_RETURN) StartUpdate();
return 0;
case WM_CLOSE:
RequestClose();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
break;
}
return DefWindowProcW(hwnd_, msg, wParam, lParam);
}
LRESULT CALLBACK UpdateWindow::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
UpdateWindow* self = nullptr;
if (msg == WM_NCCREATE) {
CREATESTRUCTW* cs = reinterpret_cast<CREATESTRUCTW*>(lParam);
self = static_cast<UpdateWindow*>(cs->lpCreateParams);
SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(self));
if (self) self->hwnd_ = hwnd;
} else {
self = reinterpret_cast<UpdateWindow*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
}
if (self) return self->HandleMessage(msg, wParam, lParam);
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
}