diff options
author | crupest <crupest@outlook.com> | 2019-04-10 19:42:46 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2019-04-10 19:42:46 +0800 |
commit | 7351020a582d70a1495249fba87d342c8a1fb634 (patch) | |
tree | e80f225041dc3816b3dce21c7e15aadbb211602e /src/win | |
parent | a94a806f69586e08a30fff0cdb3e52b0ce7acfa5 (diff) | |
download | cru-7351020a582d70a1495249fba87d342c8a1fb634.tar.gz cru-7351020a582d70a1495249fba87d342c8a1fb634.tar.bz2 cru-7351020a582d70a1495249fba87d342c8a1fb634.zip |
Refactor.
Diffstat (limited to 'src/win')
26 files changed, 1409 insertions, 0 deletions
diff --git a/src/win/CMakeLists.txt b/src/win/CMakeLists.txt new file mode 100644 index 00000000..1ca1f544 --- /dev/null +++ b/src/win/CMakeLists.txt @@ -0,0 +1,10 @@ +add_library(cru_win_base STATIC + debug.cpp + exception.cpp + string_util.cpp +) +target_compile_definitions(cru_win_base PUBLIC UNICODE _UNICODE) # use unicode +target_include_directories(cru_win_base PUBLIC ${PROJECT_SOURCE_DIR}/include .) + +add_subdirectory(graph) +add_subdirectory(native) diff --git a/src/win/debug.cpp b/src/win/debug.cpp new file mode 100644 index 00000000..e15b1f6c --- /dev/null +++ b/src/win/debug.cpp @@ -0,0 +1,9 @@ +#include "cru/win/win_pre_config.hpp" + +#include "cru/platform/debug.hpp" + +namespace cru::platform { +void DebugMessage(const std::wstring_view& message) { + ::OutputDebugStringW(message.data()); +} +} // namespace cru::platform diff --git a/src/win/exception.cpp b/src/win/exception.cpp new file mode 100644 index 00000000..62305329 --- /dev/null +++ b/src/win/exception.cpp @@ -0,0 +1,50 @@ +#include "cru/win/exception.hpp" + +#include "cru/common/format.hpp" + +namespace cru::win { +using util::Format; + +inline std::string HResultMakeMessage(HRESULT h_result, + const std::string_view* message) { + char buffer[10]; + sprintf_s(buffer, "%#08x", h_result); + + if (message) + return Format( + "An HResultError is thrown. HRESULT: {}.\nAdditional message: {}\n", + buffer, *message); + else + return Format("An HResultError is thrown. HRESULT: {}.\n", buffer); +} + +HResultError::HResultError(HRESULT h_result) + : PlatformException(HResultMakeMessage(h_result, nullptr)), + h_result_(h_result) {} + +HResultError::HResultError(HRESULT h_result, + const std::string_view& additional_message) + : PlatformException(HResultMakeMessage(h_result, &additional_message)), + h_result_(h_result) {} + +inline std::string Win32MakeMessage(DWORD error_code, + const std::string_view* message) { + char buffer[10]; + sprintf_s(buffer, "%#04x", error_code); + + if (message) + return Format("Last error code: {}.\nAdditional message: {}\n", buffer, + *message); + else + return Format("Last error code: {}.\n", buffer); +} + +Win32Error::Win32Error(DWORD error_code) + : PlatformException(Win32MakeMessage(error_code, nullptr)), + error_code_(error_code) {} + +Win32Error::Win32Error(DWORD error_code, + const std::string_view& additional_message) + : PlatformException(Win32MakeMessage(error_code, &additional_message)), + error_code_(error_code) {} +} // namespace cru::win diff --git a/src/win/graph/CMakeLists.txt b/src/win/graph/CMakeLists.txt new file mode 100644 index 00000000..7781e09a --- /dev/null +++ b/src/win/graph/CMakeLists.txt @@ -0,0 +1,9 @@ +add_library(cru_win_graph STATIC + graph_manager.cpp + win_brush.cpp + win_font.cpp + win_geometry.cpp + win_graph_factory.cpp + win_painter.cpp + win_text_layout.cpp) +target_link_libraries(cru_win_graph PUBLIC D3D11 D2d1 DWrite cru_win_base) diff --git a/src/win/graph/graph_manager.cpp b/src/win/graph/graph_manager.cpp new file mode 100644 index 00000000..a4306b1b --- /dev/null +++ b/src/win/graph/graph_manager.cpp @@ -0,0 +1,59 @@ +#include "cru/win/graph/graph_manager.hpp" + +#include "cru/win/exception.hpp" + +namespace cru::win::graph { +GraphManager* GraphManager::GetInstance() { + static GraphManager instance; + return &instance; +} + +GraphManager::GraphManager() { + UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; + +#ifdef CRU_DEBUG + creation_flags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + + const D3D_FEATURE_LEVEL feature_levels[] = { + D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1}; + + Microsoft::WRL::ComPtr<ID3D11DeviceContext> d3d11_device_context; + + ThrowIfFailed(D3D11CreateDevice( + nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, creation_flags, + feature_levels, ARRAYSIZE(feature_levels), D3D11_SDK_VERSION, + &d3d11_device_, nullptr, &d3d11_device_context)); + + Microsoft::WRL::ComPtr<IDXGIDevice> dxgi_device; + ThrowIfFailed(d3d11_device_->QueryInterface(dxgi_device.GetAddressOf())); + + ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, + IID_PPV_ARGS(&d2d1_factory_))); + + Microsoft::WRL::ComPtr<ID2D1Device> d2d1_device; + + ThrowIfFailed(d2d1_factory_->CreateDevice(dxgi_device.Get(), &d2d1_device)); + + ThrowIfFailed(d2d1_device->CreateDeviceContext( + D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2d1_device_context_)); + + // Identify the physical adapter (GPU or card) this device is runs on. + Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter; + ThrowIfFailed(dxgi_device->GetAdapter(&dxgi_adapter)); + + // Get the factory object that created the DXGI device. + ThrowIfFailed(dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory_))); + + ThrowIfFailed(DWriteCreateFactory( + DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), + reinterpret_cast<IUnknown**>(dwrite_factory_.GetAddressOf()))); + + ThrowIfFailed(dwrite_factory_->GetSystemFontCollection( + &dwrite_system_font_collection_)); + + graph_factory_.reset(new WinGraphFactory(this)); +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_brush.cpp b/src/win/graph/win_brush.cpp new file mode 100644 index 00000000..262c3302 --- /dev/null +++ b/src/win/graph/win_brush.cpp @@ -0,0 +1,23 @@ +#include "cru/win/graph/win_brush.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/d2d_util.hpp" +#include "cru/win/graph/graph_manager.hpp" + +#include <cassert> + +namespace cru::win::graph { +WinSolidColorBrush::WinSolidColorBrush(GraphManager* graph_manager, + const ui::Color& color) { + assert(graph_manager); + ThrowIfFailed(graph_manager->GetD2D1DeviceContext()->CreateSolidColorBrush( + util::Convert(color), &brush_)); +} + +ui::Color WinSolidColorBrush::GetColor() { + return util::Convert(brush_->GetColor()); +} +void WinSolidColorBrush::SetColor(const ui::Color& color) { + brush_->SetColor(util::Convert(color)); +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_font.cpp b/src/win/graph/win_font.cpp new file mode 100644 index 00000000..0eb5e6b2 --- /dev/null +++ b/src/win/graph/win_font.cpp @@ -0,0 +1,28 @@ +#include "cru/win/graph/win_font.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/graph_manager.hpp" + +#include <array> +#include <cassert> +#include <utility> + +namespace cru::win::graph { +WinFontDescriptor::WinFontDescriptor(GraphManager* graph_manager, + const std::wstring_view& font_family, + float font_size) { + assert(graph_manager); + std::array<wchar_t, LOCALE_NAME_MAX_LENGTH> buffer; + if (!::GetUserDefaultLocaleName(buffer.data(), buffer.size())) + throw Win32Error(::GetLastError(), "Failed to get locale."); + + ThrowIfFailed(graph_manager->GetDWriteFactory()->CreateTextFormat( + font_family.data(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, + DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, font_size, + buffer.data(), &text_format_)); + + ThrowIfFailed(text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)); + ThrowIfFailed( + text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)); +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_geometry.cpp b/src/win/graph/win_geometry.cpp new file mode 100644 index 00000000..22c4b8a7 --- /dev/null +++ b/src/win/graph/win_geometry.cpp @@ -0,0 +1,66 @@ +#include "cru/win/graph/win_geometry.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/d2d_util.hpp" +#include "cru/win/graph/graph_manager.hpp" + +#include <cassert> + +namespace cru::win::graph { +WinGeometryBuilder::WinGeometryBuilder(GraphManager* graph_manager) { + assert(graph_manager); + ThrowIfFailed( + graph_manager->GetD2D1Factory()->CreatePathGeometry(&geometry_)); + ThrowIfFailed(geometry_->Open(&geometry_sink_)); +} + +WinGeometryBuilder::~WinGeometryBuilder() { + if (geometry_sink_) { + ThrowIfFailed(geometry_sink_->Close()); + } +} + +void WinGeometryBuilder::BeginFigure(const ui::Point& point) { + assert(IsValid()); + geometry_sink_->BeginFigure(util::Convert(point), D2D1_FIGURE_BEGIN_FILLED); +} + +void WinGeometryBuilder::LineTo(const ui::Point& point) { + assert(IsValid()); + geometry_sink_->AddLine(util::Convert(point)); +} + +void WinGeometryBuilder::QuadraticBezierTo(const ui::Point& control_point, + const ui::Point& end_point) { + assert(IsValid()); + geometry_sink_->AddQuadraticBezier(D2D1::QuadraticBezierSegment( + util::Convert(control_point), util::Convert(end_point))); +} + +void WinGeometryBuilder::CloseFigure(bool close) { + assert(IsValid()); + geometry_sink_->EndFigure(close ? D2D1_FIGURE_END_CLOSED + : D2D1_FIGURE_END_OPEN); +} + +platform::graph::Geometry* WinGeometryBuilder::Build() { + assert(IsValid()); + ThrowIfFailed(geometry_sink_->Close()); + geometry_sink_ = nullptr; + const auto geometry = new WinGeometry(geometry_); + geometry_ = nullptr; + return geometry; +} + +WinGeometry::WinGeometry(Microsoft::WRL::ComPtr<ID2D1PathGeometry> geometry) { + assert(geometry); + geometry_ = std::move(geometry); +} + +bool WinGeometry::FillContains(const ui::Point& point) { + BOOL result; + ThrowIfFailed(geometry_->FillContainsPoint( + util::Convert(point), D2D1::Matrix3x2F::Identity(), &result)); + return result != 0; +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_graph_factory.cpp b/src/win/graph/win_graph_factory.cpp new file mode 100644 index 00000000..5ab905b6 --- /dev/null +++ b/src/win/graph/win_graph_factory.cpp @@ -0,0 +1,46 @@ +#include "cru/win/graph/win_graph_factory.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/d2d_util.hpp" +#include "cru/win/graph/graph_manager.hpp" +#include "cru/win/graph/win_brush.hpp" +#include "cru/win/graph/win_font.hpp" +#include "cru/win/graph/win_geometry.hpp" +#include "cru/win/graph/win_text_layout.hpp" + +#include <cassert> +#include <utility> + +namespace cru::platform::graph { +GraphFactory* GraphFactory::GetInstance() { + return win::graph::GraphManager::GetInstance()->GetGraphFactory(); +} +} + +namespace cru::win::graph { +WinGraphFactory::WinGraphFactory(GraphManager* graph_manager) { + assert(graph_manager); + graph_manager_ = graph_manager; +} + +platform::graph::SolidColorBrush* WinGraphFactory::CreateSolidColorBrush( + const ui::Color& color) { + return new WinSolidColorBrush(graph_manager_, color); +} + +platform::graph::GeometryBuilder* WinGraphFactory::CreateGeometryBuilder() { + return new WinGeometryBuilder(graph_manager_); +} + +platform::graph::FontDescriptor* WinGraphFactory::CreateFontDescriptor( + const std::wstring_view& font_family, float font_size) { + return new WinFontDescriptor(graph_manager_, font_family, font_size); +} + +platform::graph::TextLayout* WinGraphFactory::CreateTextLayout( + std::shared_ptr<platform::graph::FontDescriptor> font, std::wstring text) { + const auto f = std::dynamic_pointer_cast<WinFontDescriptor>(font); + assert(f); + return new WinTextLayout(graph_manager_, std::move(f), std::move(text)); +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_painter.cpp b/src/win/graph/win_painter.cpp new file mode 100644 index 00000000..69ce1141 --- /dev/null +++ b/src/win/graph/win_painter.cpp @@ -0,0 +1,99 @@ +#include "cru/win/graph/win_painter.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/d2d_util.hpp" +#include "cru/win/graph/graph_manager.hpp" +#include "cru/win/graph/win_brush.hpp" +#include "cru/win/graph/win_geometry.hpp" +#include "cru/win/graph/win_text_layout.hpp" + +#include <cassert> + +namespace cru::win::graph { +WinPainter::WinPainter(ID2D1RenderTarget* render_target) { + assert(render_target); + render_target_ = render_target; +} + +WinPainter::~WinPainter() { EndDraw(); } + +platform::Matrix WinPainter::GetTransform() { + assert(!IsDisposed()); + D2D1_MATRIX_3X2_F m; + render_target_->GetTransform(&m); + return util::Convert(m); +} + +void WinPainter::SetTransform(const platform::Matrix& matrix) { + assert(!IsDisposed()); + render_target_->SetTransform(util::Convert(matrix)); +} + +void WinPainter::Clear(const ui::Color& color) { + assert(!IsDisposed()); + render_target_->Clear(util::Convert(color)); +} + +void WinPainter::StrokeRectangle(const ui::Rect& rectangle, + platform::graph::Brush* brush, float width) { + assert(!IsDisposed()); + const auto b = dynamic_cast<WinBrush*>(brush); + assert(b); + render_target_->DrawRectangle(util::Convert(rectangle), b->GetD2DBrush(), + width); +} + +void WinPainter::FillRectangle(const ui::Rect& rectangle, + platform::graph::Brush* brush) { + assert(!IsDisposed()); + const auto b = dynamic_cast<WinBrush*>(brush); + assert(b); + render_target_->FillRectangle(util::Convert(rectangle), b->GetD2DBrush()); +} + +void WinPainter::StrokeGeometry(platform::graph::Geometry* geometry, + platform::graph::Brush* brush, float width) { + assert(!IsDisposed()); + const auto g = dynamic_cast<WinGeometry*>(geometry); + assert(g); + const auto b = dynamic_cast<WinBrush*>(brush); + assert(b); + + render_target_->DrawGeometry(g->GetNative(), b->GetD2DBrush(), width); +} + +void WinPainter::FillGeometry(platform::graph::Geometry* geometry, + platform::graph::Brush* brush) { + assert(!IsDisposed()); + const auto g = dynamic_cast<WinGeometry*>(geometry); + assert(g); + const auto b = dynamic_cast<WinBrush*>(brush); + assert(b); + + render_target_->FillGeometry(g->GetNative(), b->GetD2DBrush()); +} + +void WinPainter::DrawText(const ui::Point& offset, + platform::graph::TextLayout* text_layout, + platform::graph::Brush* brush) { + assert(!IsDisposed()); + const auto t = dynamic_cast<WinTextLayout*>(text_layout); + assert(t); + const auto b = dynamic_cast<WinBrush*>(brush); + assert(b); + + render_target_->DrawTextLayout(util::Convert(offset), + t->GetDWriteTextLayout(), b->GetD2DBrush()); +} + +void WinPainter::EndDraw() { + if (!IsDisposed()) { + DoEndDraw(); + } +} + +void WinPainter::DoEndDraw() { + ThrowIfFailed(render_target_->EndDraw()); + is_disposed_ = true; +} +} // namespace cru::win::graph diff --git a/src/win/graph/win_text_layout.cpp b/src/win/graph/win_text_layout.cpp new file mode 100644 index 00000000..0506320a --- /dev/null +++ b/src/win/graph/win_text_layout.cpp @@ -0,0 +1,94 @@ +#include "cru/win/graph/win_text_layout.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/graph_manager.hpp" +#include "cru/win/graph/win_font.hpp" + +#include <cassert> +#include <utility> + +namespace cru::win::graph { +WinTextLayout::WinTextLayout(GraphManager* graph_manager, + std::shared_ptr<WinFontDescriptor> font, + std::wstring text) { + assert(graph_manager); + assert(font); + graph_manager_ = graph_manager; + text_.swap(text); + font_descriptor_.swap(font); + + ThrowIfFailed(graph_manager_->GetDWriteFactory()->CreateTextLayout( + text_.c_str(), static_cast<UINT32>(text_.size()), + font_descriptor_->GetDWriteTextFormat(), max_width_, max_height_, + &text_layout_)); +} + +std::wstring WinTextLayout::GetText() { return text_; } + +void WinTextLayout::SetText(std::wstring new_text) { + text_.swap(new_text); + ThrowIfFailed(graph_manager_->GetDWriteFactory()->CreateTextLayout( + text_.c_str(), static_cast<UINT32>(text_.size()), + font_descriptor_->GetDWriteTextFormat(), max_width_, max_height_, + &text_layout_)); +} + +std::shared_ptr<platform::graph::FontDescriptor> WinTextLayout::GetFont() { + return font_descriptor_; +} + +void WinTextLayout::SetFont( + std::shared_ptr<platform::graph::FontDescriptor> font) { + auto f = std::dynamic_pointer_cast<WinFontDescriptor>(font); + assert(f); + f.swap(font_descriptor_); + ThrowIfFailed(graph_manager_->GetDWriteFactory()->CreateTextLayout( + text_.c_str(), static_cast<UINT32>(text_.size()), + font_descriptor_->GetDWriteTextFormat(), max_width_, max_height_, + &text_layout_)); +} + +void WinTextLayout::SetMaxWidth(float max_width) { + max_width_ = max_width; + ThrowIfFailed(text_layout_->SetMaxWidth(max_width_)); +} + +void WinTextLayout::SetMaxHeight(float max_height) { + max_height_ = max_height; + ThrowIfFailed(text_layout_->SetMaxHeight(max_height_)); +} + +ui::Rect WinTextLayout::GetTextBounds() { + DWRITE_TEXT_METRICS metrics; + ThrowIfFailed(text_layout_->GetMetrics(&metrics)); + return ui::Rect{metrics.left, metrics.top, metrics.width, metrics.height}; +} + +std::vector<ui::Rect> WinTextLayout::TextRangeRect( + const ui::TextRange& text_range) { + DWRITE_TEXT_METRICS text_metrics; + ThrowIfFailed(text_layout_->GetMetrics(&text_metrics)); + const auto metrics_count = + text_metrics.lineCount * text_metrics.maxBidiReorderingDepth; + + std::vector<DWRITE_HIT_TEST_METRICS> hit_test_metrics(metrics_count); + UINT32 actual_count; + text_layout_->HitTestTextRange(text_range.position, text_range.count, 0, 0, + hit_test_metrics.data(), metrics_count, + &actual_count); + + hit_test_metrics.erase(hit_test_metrics.cbegin() + actual_count, + hit_test_metrics.cend()); + + std::vector<ui::Rect> result; + result.reserve(actual_count); + + for (const auto& metrics : hit_test_metrics) { + result.push_back(ui::Rect{metrics.left, metrics.top, + metrics.left + metrics.width, + metrics.top + metrics.height}); + } + + return result; +} +} // namespace cru::win::graph diff --git a/src/win/native/CMakeLists.txt b/src/win/native/CMakeLists.txt new file mode 100644 index 00000000..421f7515 --- /dev/null +++ b/src/win/native/CMakeLists.txt @@ -0,0 +1,10 @@ +add_library(cru_win_native STATIC + god_window.cpp + timer.cpp + win_application.cpp + win_native_window.cpp + window_class.cpp + window_manager.cpp + window_painter.cpp + window_render_target.cpp) +target_link_libraries(cru_win_native PUBLIC cru_win_graph) diff --git a/src/win/native/dpi_util.hpp b/src/win/native/dpi_util.hpp new file mode 100644 index 00000000..d459e8c6 --- /dev/null +++ b/src/win/native/dpi_util.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include "cru/platform/native/basic_types.hpp" + +// The dpi awareness needs to be implemented in the future. Currently we use 96 +// as default. + +namespace cru::win::native { +inline platform::native::Dpi GetDpi() { + return platform::native::Dpi{96.0f, 96.0f}; +} + +inline int DipToPixelInternal(const float dip, const float dpi) { + return static_cast<int>(dip * dpi / 96.0f); +} + +inline int DipToPixelX(const float dip_x) { + return DipToPixelInternal(dip_x, GetDpi().x); +} + +inline int DipToPixelY(const float dip_y) { + return DipToPixelInternal(dip_y, GetDpi().y); +} + +inline float DipToPixelInternal(const int pixel, const float dpi) { + return static_cast<float>(pixel) * 96.0f / dpi; +} + +inline float PixelToDipX(const int pixel_x) { + return DipToPixelInternal(pixel_x, GetDpi().x); +} + +inline float PixelToDipY(const int pixel_y) { + return DipToPixelInternal(pixel_y, GetDpi().y); +} +} // namespace cru::win::native diff --git a/src/win/native/god_window.cpp b/src/win/native/god_window.cpp new file mode 100644 index 00000000..58fb663c --- /dev/null +++ b/src/win/native/god_window.cpp @@ -0,0 +1,73 @@ +#include "cru/win/native/god_window.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/native/win_application.hpp" +#include "cru/win/native/window_class.hpp" +#include "god_window_message.hpp" +#include "timer.hpp" + +namespace cru::win::native { +constexpr auto god_window_class_name = L"GodWindowClass"; + +LRESULT CALLBACK GodWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, + LPARAM lParam) { + const auto app = WinApplication::GetInstance(); + + if (app) { + LRESULT result; + const auto handled = app->GetGodWindow()->HandleGodWindowMessage( + hWnd, uMsg, wParam, lParam, &result); + if (handled) + return result; + else + return DefWindowProcW(hWnd, uMsg, wParam, lParam); + } else + return DefWindowProcW(hWnd, uMsg, wParam, lParam); +} + +GodWindow::GodWindow(WinApplication* application) { + application_ = application; + + const auto h_instance = application->GetInstanceHandle(); + + god_window_class_ = std::make_shared<WindowClass>(god_window_class_name, + GodWndProc, h_instance); + + hwnd_ = CreateWindowEx(0, god_window_class_name, L"", 0, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + HWND_MESSAGE, nullptr, h_instance, nullptr); + + if (hwnd_ == nullptr) + throw Win32Error(::GetLastError(), "Failed to create god window."); +} + +GodWindow::~GodWindow() { ::DestroyWindow(hwnd_); } + +bool GodWindow::HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, + LPARAM l_param, LRESULT* result) { + switch (msg) { + case invoke_later_message_id: { + const auto p_action = reinterpret_cast<std::function<void()>*>(w_param); + (*p_action)(); + delete p_action; + *result = 0; + return true; + } + case WM_TIMER: { + const auto id = static_cast<UINT_PTR>(w_param); + const auto action = application_->GetTimerManager()->GetAction(id); + if (action.has_value()) { + (action.value().second)(); + if (!action.value().first) + application_->GetTimerManager()->KillTimer(id); + result = 0; + return true; + } + break; + } + default: + return false; + } + return false; +} +} // namespace cru::win::native diff --git a/src/win/native/god_window_message.hpp b/src/win/native/god_window_message.hpp new file mode 100644 index 00000000..10268625 --- /dev/null +++ b/src/win/native/god_window_message.hpp @@ -0,0 +1,6 @@ +#pragma once +#include "cru/win/win_pre_config.hpp" + +namespace cru::win::native { +constexpr int invoke_later_message_id = WM_USER + 2000; +} diff --git a/src/win/native/timer.cpp b/src/win/native/timer.cpp new file mode 100644 index 00000000..9e3bbde6 --- /dev/null +++ b/src/win/native/timer.cpp @@ -0,0 +1,28 @@ +#include "timer.hpp" + +namespace cru::win::native { +TimerManager::TimerManager(GodWindow* god_window) { god_window_ = god_window; } + +UINT_PTR TimerManager::CreateTimer(const UINT milliseconds, const bool loop, + const TimerAction& action) { + const auto id = current_count_++; + ::SetTimer(god_window_->GetHandle(), id, milliseconds, nullptr); + map_.emplace(id, std::make_pair(loop, action)); + return id; +} + +void TimerManager::KillTimer(const UINT_PTR id) { + const auto find_result = map_.find(id); + if (find_result != map_.cend()) { + ::KillTimer(god_window_->GetHandle(), id); + map_.erase(find_result); + } +} + +std::optional<std::pair<bool, TimerAction>> TimerManager::GetAction( + const UINT_PTR id) { + const auto find_result = map_.find(id); + if (find_result == map_.cend()) return std::nullopt; + return find_result->second; +} +} // namespace cru::win::native diff --git a/src/win/native/timer.hpp b/src/win/native/timer.hpp new file mode 100644 index 00000000..f30d9b91 --- /dev/null +++ b/src/win/native/timer.hpp @@ -0,0 +1,34 @@ +#pragma once +#include "cru/win/win_pre_config.hpp" + +#include "cru/common/base.hpp" +#include "cru/win/native/god_window.hpp" + +#include <chrono> +#include <functional> +#include <map> +#include <optional> + +namespace cru::win::native { +using TimerAction = std::function<void()>; + +class TimerManager : public Object { + public: + TimerManager(GodWindow* god_window); + TimerManager(const TimerManager& other) = delete; + TimerManager(TimerManager&& other) = delete; + TimerManager& operator=(const TimerManager& other) = delete; + TimerManager& operator=(TimerManager&& other) = delete; + ~TimerManager() override = default; + + UINT_PTR CreateTimer(UINT milliseconds, bool loop, const TimerAction& action); + void KillTimer(UINT_PTR id); + std::optional<std::pair<bool, TimerAction>> GetAction(UINT_PTR id); + + private: + GodWindow* god_window_; + + std::map<UINT_PTR, std::pair<bool, TimerAction>> map_{}; + UINT_PTR current_count_ = 0; +}; +} // namespace cru::win::native diff --git a/src/win/native/win_application.cpp b/src/win/native/win_application.cpp new file mode 100644 index 00000000..72e12fa0 --- /dev/null +++ b/src/win/native/win_application.cpp @@ -0,0 +1,100 @@ +#include "cru/win/native/win_application.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/native/god_window.hpp" +#include "cru/win/native/win_native_window.hpp" +#include "god_window_message.hpp" +#include "timer.hpp" +#include "window_manager.hpp" + +#include <VersionHelpers.h> +#include <cassert> + +namespace cru::platform::native { +UiApplication* UiApplication::GetInstance() { + return win::native::WinApplication::GetInstance(); +} +} // namespace cru::platform::native + +namespace cru::win::native { +WinApplication* WinApplication::instance_ = nullptr; + +WinApplication* WinApplication::GetInstance() { + if (instance_ == nullptr) + instance_ = new WinApplication(::GetModuleHandleW(nullptr)); + return instance_; +} + +WinApplication::WinApplication(HINSTANCE h_instance) : h_instance_(h_instance) { + if (instance_) + throw std::runtime_error("A application instance already exists."); + + instance_ = this; + + if (!::IsWindows8OrGreater()) + throw std::runtime_error("Must run on Windows 8 or later."); + + god_window_ = std::make_shared<GodWindow>(this); + timer_manager_ = std::make_shared<TimerManager>(god_window_.get()); + window_manager_ = std::make_shared<WindowManager>(this); +} + +WinApplication::~WinApplication() { instance_ = nullptr; } + +int WinApplication::Run() { + MSG msg; + while (GetMessageW(&msg, nullptr, 0, 0)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + return static_cast<int>(msg.wParam); +} + +void WinApplication::Quit(const int quit_code) { ::PostQuitMessage(quit_code); } + +void WinApplication::InvokeLater(const std::function<void()>& action) { + // copy the action to a safe place + auto p_action_copy = new std::function<void()>(action); + + if (PostMessageW(GetGodWindow()->GetHandle(), invoke_later_message_id, + reinterpret_cast<WPARAM>(p_action_copy), 0) == 0) + throw Win32Error(::GetLastError(), "InvokeLater failed to post message."); +} + +unsigned long WinApplication::SetTimeout(std::chrono::milliseconds milliseconds, + const std::function<void()>& action) { + return static_cast<unsigned long>(timer_manager_->CreateTimer( + static_cast<UINT>(milliseconds.count()), false, action)); +} + +unsigned long WinApplication::SetInterval( + std::chrono::milliseconds milliseconds, + const std::function<void()>& action) { + return static_cast<unsigned long>(timer_manager_->CreateTimer( + static_cast<UINT>(milliseconds.count()), true, action)); +} + +void WinApplication::CancelTimer(unsigned long id) { + timer_manager_->KillTimer(static_cast<UINT_PTR>(id)); +} + +std::vector<platform::native::NativeWindow*> WinApplication::GetAllWindow() { + const auto&& windows = window_manager_->GetAllWindows(); + std::vector<platform::native::NativeWindow*> result; + for (const auto w : windows) { + result.push_back(static_cast<platform::native::NativeWindow*>(w)); + } + return result; +} + +platform::native::NativeWindow* WinApplication::CreateWindow( + platform::native::NativeWindow* parent) { + WinNativeWindow* p = nullptr; + if (parent != nullptr) { + p = dynamic_cast<WinNativeWindow*>(parent); + assert(p); + } + return new WinNativeWindow(this, window_manager_->GetGeneralWindowClass(), + WS_OVERLAPPEDWINDOW, p); +} +} // namespace cru::win::native diff --git a/src/win/native/win_native_window.cpp b/src/win/native/win_native_window.cpp new file mode 100644 index 00000000..0afad4e6 --- /dev/null +++ b/src/win/native/win_native_window.cpp @@ -0,0 +1,340 @@ +#include "cru/win/native/win_native_window.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/graph_manager.hpp" +#include "cru/win/native/win_application.hpp" +#include "cru/win/native/window_class.hpp" +#include "cru/win/native/window_render_target.hpp" +#include "dpi_util.hpp" +#include "window_manager.hpp" +#include "window_painter.hpp" + +#include <assert.h> +#include <windowsx.h> + +namespace cru::win::native { +WinNativeWindow::WinNativeWindow(WinApplication* application, + std::shared_ptr<WindowClass> window_class, + DWORD window_style, WinNativeWindow* parent) { + assert(application); // application can't be null. + assert(parent == nullptr || + parent->IsValid()); // Parent window is not valid. + + application_ = application; + parent_window_ = parent; + + const auto window_manager = application->GetWindowManager(); + + hwnd_ = CreateWindowExW( + 0, window_manager->GetGeneralWindowClass()->GetName(), L"", window_style, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + parent == nullptr ? nullptr : parent->GetWindowHandle(), nullptr, + application->GetInstanceHandle(), nullptr); + + if (hwnd_ == nullptr) + throw Win32Error(::GetLastError(), "Failed to create window."); + + window_manager->RegisterWindow(hwnd_, this); + + window_render_target_.reset( + new WindowRenderTarget(graph::GraphManager::GetInstance(), hwnd_)); +} + +WinNativeWindow::~WinNativeWindow() { + if (IsValid()) { + SetDeleteThisOnDestroy(false); // avoid double delete. + Close(); + } +} + +bool WinNativeWindow::IsValid() { return hwnd_ != nullptr; } + +void WinNativeWindow::SetDeleteThisOnDestroy(bool value) { + delete_this_on_destroy_ = value; +} + +void WinNativeWindow::Close() { + if (IsValid()) DestroyWindow(hwnd_); +} + +bool WinNativeWindow::IsVisible() { + if (IsValid()) return ::IsWindowVisible(hwnd_); + return false; +} + +void WinNativeWindow::SetVisible(bool is_visible) { + if (!IsValid()) return; + is_visible ? ShowWindow(hwnd_, SW_SHOWNORMAL) : ShowWindow(hwnd_, SW_HIDE); +} +ui::Size WinNativeWindow::GetClientSize() { + if (!IsValid()) return ui::Size{}; + + const auto pixel_rect = GetClientRectPixel(); + return ui::Size(PixelToDipX(pixel_rect.right), + PixelToDipY(pixel_rect.bottom)); +} + +void WinNativeWindow::SetClientSize(const ui::Size& size) { + if (IsValid()) { + const auto window_style = + static_cast<DWORD>(GetWindowLongPtr(hwnd_, GWL_STYLE)); + const auto window_ex_style = + static_cast<DWORD>(GetWindowLongPtr(hwnd_, GWL_EXSTYLE)); + + RECT rect; + rect.left = 0; + rect.top = 0; + rect.right = DipToPixelX(size.width); + rect.bottom = DipToPixelY(size.height); + if (!AdjustWindowRectEx(&rect, window_style, FALSE, window_ex_style)) + throw Win32Error(::GetLastError(), + "Failed to invoke AdjustWindowRectEx."); + + if (!SetWindowPos(hwnd_, nullptr, 0, 0, rect.right - rect.left, + rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE)) + throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); + } +} + +ui::Rect WinNativeWindow::GetWindowRect() { + if (!IsValid()) return ui::Rect{}; + + RECT rect; + if (!::GetWindowRect(hwnd_, &rect)) + throw Win32Error(::GetLastError(), "Failed to invoke GetWindowRect."); + + return ui::Rect::FromVertices(PixelToDipX(rect.left), PixelToDipY(rect.top), + PixelToDipX(rect.right), + PixelToDipY(rect.bottom)); +} + +void WinNativeWindow::SetWindowRect(const ui::Rect& rect) { + if (IsValid()) { + if (!SetWindowPos(hwnd_, nullptr, DipToPixelX(rect.left), + DipToPixelY(rect.top), DipToPixelX(rect.GetRight()), + DipToPixelY(rect.GetBottom()), SWP_NOZORDER)) + throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); + } +} + +platform::graph::Painter* WinNativeWindow::BeginPaint() { + return new WindowPainter(this); +} + +bool WinNativeWindow::HandleNativeWindowMessage(HWND hwnd, UINT msg, + WPARAM w_param, LPARAM l_param, + LRESULT* result) { + WindowNativeMessageEventArgs args{ + WindowNativeMessage{hwnd, msg, w_param, l_param}}; + native_message_event_.Raise(args); + if (args.IsHandled()) { + *result = args.GetResult(); + return true; + } + + switch (msg) { + case WM_PAINT: + OnPaintInternal(); + *result = 0; + return true; + case WM_ERASEBKGND: + *result = 1; + return true; + case WM_SETFOCUS: + OnSetFocusInternal(); + *result = 0; + return true; + case WM_KILLFOCUS: + OnKillFocusInternal(); + *result = 0; + return true; + case WM_MOUSEMOVE: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseMoveInternal(point); + *result = 0; + return true; + } + case WM_LBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::native::MouseButton::Left, point); + *result = 0; + return true; + } + case WM_LBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::native::MouseButton::Left, point); + *result = 0; + return true; + } + case WM_RBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::native::MouseButton::Right, point); + *result = 0; + return true; + } + case WM_RBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::native::MouseButton::Right, point); + *result = 0; + return true; + } + case WM_MBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::native::MouseButton::Middle, point); + *result = 0; + return true; + } + case WM_MBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::native::MouseButton::Middle, point); + *result = 0; + return true; + } + case WM_MOUSEWHEEL: + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + ScreenToClient(hwnd, &point); + OnMouseWheelInternal(GET_WHEEL_DELTA_WPARAM(w_param), point); + *result = 0; + return true; + case WM_KEYDOWN: + OnKeyDownInternal(static_cast<int>(w_param)); + *result = 0; + return true; + case WM_KEYUP: + OnKeyUpInternal(static_cast<int>(w_param)); + *result = 0; + return true; + case WM_CHAR: + OnCharInternal(static_cast<wchar_t>(w_param)); + *result = 0; + return true; + case WM_SIZE: + OnResizeInternal(LOWORD(l_param), HIWORD(l_param)); + *result = 0; + return true; + case WM_ACTIVATE: + if (w_param == WA_ACTIVE || w_param == WA_CLICKACTIVE) + OnActivatedInternal(); + else if (w_param == WA_INACTIVE) + OnDeactivatedInternal(); + *result = 0; + return true; + case WM_DESTROY: + OnDestroyInternal(); + *result = 0; + return true; + default: + return false; + } +} + +RECT WinNativeWindow::GetClientRectPixel() { + RECT rect; + if (!GetClientRect(hwnd_, &rect)) + throw Win32Error(::GetLastError(), "Failed to invoke GetClientRect."); + return rect; +} + +void WinNativeWindow::OnDestroyInternal() { + application_->GetWindowManager()->UnregisterWindow(hwnd_); + hwnd_ = nullptr; + if (delete_this_on_destroy_) + application_->InvokeLater([this] { delete this; }); +} + +void WinNativeWindow::OnPaintInternal() { + paint_event_.Raise(); + ValidateRect(hwnd_, nullptr); +} + +void WinNativeWindow::OnResizeInternal(const int new_width, + const int new_height) { + if (!(new_width == 0 && new_height == 0)) { + window_render_target_->ResizeBuffer(new_width, new_height); + resize_event_.Raise( + ui::Size{PixelToDipX(new_width), PixelToDipY(new_height)}); + } +} + +void WinNativeWindow::OnSetFocusInternal() { + has_focus_ = true; + focus_event_.Raise(true); +} + +void WinNativeWindow::OnKillFocusInternal() { + has_focus_ = false; + focus_event_.Raise(false); +} + +inline ui::Point PiToDip(const POINT& pi_point) { + return ui::Point(PixelToDipX(pi_point.x), PixelToDipY(pi_point.y)); +} + +void WinNativeWindow::OnMouseMoveInternal(const POINT point) { + // when mouse was previous outside the window + if (!is_mouse_in_) { + // invoke TrackMouseEvent to have WM_MOUSELEAVE sent. + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof tme; + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hwnd_; + + TrackMouseEvent(&tme); + + is_mouse_in_ = true; + mouse_enter_leave_event_.Raise(true); + } + + const auto dip_point = PiToDip(point); + mouse_move_event_.Raise(dip_point); +} + +void WinNativeWindow::OnMouseLeaveInternal() { + is_mouse_in_ = false; + mouse_enter_leave_event_.Raise(false); +} + +void WinNativeWindow::OnMouseDownInternal(platform::native::MouseButton button, + POINT point) { + const auto dip_point = PiToDip(point); + mouse_down_event_.Raise(button, dip_point); +} + +void WinNativeWindow::OnMouseUpInternal(platform::native::MouseButton button, + POINT point) { + const auto dip_point = PiToDip(point); + mouse_up_event_.Raise(button, dip_point); +} + +void WinNativeWindow::OnMouseWheelInternal(short delta, POINT point) {} + +void WinNativeWindow::OnKeyDownInternal(int virtual_code) { + key_down_event_.Raise(virtual_code); +} + +void WinNativeWindow::OnKeyUpInternal(int virtual_code) { + key_up_event_.Raise(virtual_code); +} + +void WinNativeWindow::OnCharInternal(wchar_t c) {} + +void WinNativeWindow::OnActivatedInternal() {} + +void WinNativeWindow::OnDeactivatedInternal() {} +} // namespace cru::win::native diff --git a/src/win/native/window_class.cpp b/src/win/native/window_class.cpp new file mode 100644 index 00000000..6c7d0d3d --- /dev/null +++ b/src/win/native/window_class.cpp @@ -0,0 +1,28 @@ +#include "cru/win/native/window_class.hpp" + +#include "cru/win/exception.hpp" + +namespace cru::win::native { +WindowClass::WindowClass(const std::wstring& name, WNDPROC window_proc, + HINSTANCE h_instance) + : name_(name) { + WNDCLASSEXW window_class; + window_class.cbSize = sizeof(WNDCLASSEXW); + + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.lpfnWndProc = window_proc; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = h_instance; + window_class.hIcon = LoadIcon(NULL, IDI_APPLICATION); + window_class.hCursor = LoadCursor(NULL, IDC_ARROW); + window_class.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); + window_class.lpszMenuName = NULL; + window_class.lpszClassName = name.c_str(); + window_class.hIconSm = NULL; + + atom_ = ::RegisterClassExW(&window_class); + if (atom_ == 0) + throw Win32Error(::GetLastError(), "Failed to create window class."); +} +} // namespace cru::win::native diff --git a/src/win/native/window_manager.cpp b/src/win/native/window_manager.cpp new file mode 100644 index 00000000..a2fcdb54 --- /dev/null +++ b/src/win/native/window_manager.cpp @@ -0,0 +1,54 @@ +#include "window_manager.hpp" + +#include "cru/win/native/win_application.hpp" +#include "cru/win/native/win_native_window.hpp" +#include "cru/win/native/window_class.hpp" + +#include <assert.h> + +namespace cru::win::native { +LRESULT __stdcall GeneralWndProc(HWND hWnd, UINT Msg, WPARAM wParam, + LPARAM lParam) { + auto window = + WinApplication::GetInstance()->GetWindowManager()->FromHandle(hWnd); + + LRESULT result; + if (window != nullptr && + window->HandleNativeWindowMessage(hWnd, Msg, wParam, lParam, &result)) + return result; + + return DefWindowProc(hWnd, Msg, wParam, lParam); +} + +WindowManager::WindowManager(WinApplication* application) { + application_ = application; + general_window_class_ = std::make_shared<WindowClass>( + L"CruUIWindowClass", GeneralWndProc, application->GetInstanceHandle()); +} + +void WindowManager::RegisterWindow(HWND hwnd, WinNativeWindow* window) { + assert(window_map_.count(hwnd) == 0); // The hwnd is already in the map. + window_map_.emplace(hwnd, window); +} + +void WindowManager::UnregisterWindow(HWND hwnd) { + const auto find_result = window_map_.find(hwnd); + assert(find_result != window_map_.end()); // The hwnd is not in the map. + window_map_.erase(find_result); + if (window_map_.empty()) application_->Quit(0); +} + +WinNativeWindow* WindowManager::FromHandle(HWND hwnd) { + const auto find_result = window_map_.find(hwnd); + if (find_result == window_map_.end()) + return nullptr; + else + return find_result->second; +} + +std::vector<WinNativeWindow*> WindowManager::GetAllWindows() const { + std::vector<WinNativeWindow*> windows; + for (auto [key, value] : window_map_) windows.push_back(value); + return windows; +} +} // namespace cru::win::native diff --git a/src/win/native/window_manager.hpp b/src/win/native/window_manager.hpp new file mode 100644 index 00000000..fa5bbe9d --- /dev/null +++ b/src/win/native/window_manager.hpp @@ -0,0 +1,52 @@ +#pragma once +#include "cru/win/win_pre_config.hpp" + +#include "cru/common/base.hpp" + +#include <map> +#include <memory> +#include <vector> + +namespace cru::win::native { +class WinApplication; +class WinNativeWindow; +class WindowClass; + +class WindowManager : public Object { + public: + WindowManager(WinApplication* application); + WindowManager(const WindowManager& other) = delete; + WindowManager(WindowManager&& other) = delete; + WindowManager& operator=(const WindowManager& other) = delete; + WindowManager& operator=(WindowManager&& other) = delete; + ~WindowManager() override = default; + + // Get the general window class for creating ordinary window. + std::shared_ptr<WindowClass> GetGeneralWindowClass() const { + return general_window_class_; + } + + // Register a window newly created. + // This function adds the hwnd to hwnd-window map. + // It should be called immediately after a window was created. + void RegisterWindow(HWND hwnd, WinNativeWindow* window); + + // Unregister a window that is going to be destroyed. + // This function removes the hwnd from the hwnd-window map. + // It should be called immediately before a window is going to be destroyed, + void UnregisterWindow(HWND hwnd); + + // Return a pointer to the Window object related to the HWND or nullptr if the + // hwnd is not in the map. + WinNativeWindow* FromHandle(HWND hwnd); + + std::vector<WinNativeWindow*> GetAllWindows() const; + + private: + WinApplication* application_; + + std::shared_ptr<WindowClass> general_window_class_; + std::map<HWND, WinNativeWindow*> window_map_; +}; + +} // namespace cru::win::native diff --git a/src/win/native/window_painter.cpp b/src/win/native/window_painter.cpp new file mode 100644 index 00000000..46364cdd --- /dev/null +++ b/src/win/native/window_painter.cpp @@ -0,0 +1,24 @@ +#include "window_painter.hpp" + +#include "cru/win/graph/graph_manager.hpp" +#include "cru/win/native/window_render_target.hpp" + +#include <cassert> + +namespace cru::win::native { +WindowPainter::WindowPainter(WinNativeWindow* window) + : WinPainter(window->GetWindowRenderTarget() + ->GetGraphManager() + ->GetD2D1DeviceContext()), + window_(window) { + window->GetWindowRenderTarget()->SetAsTarget(); + window->GetWindowRenderTarget() + ->GetGraphManager() + ->GetD2D1DeviceContext() + ->BeginDraw(); +} + +void WindowPainter::DoEndDraw() { + WinPainter::DoEndDraw(); + window_->GetWindowRenderTarget()->Present(); } +} // namespace cru::win::native diff --git a/src/win/native/window_painter.hpp b/src/win/native/window_painter.hpp new file mode 100644 index 00000000..0e6ab2cb --- /dev/null +++ b/src/win/native/window_painter.hpp @@ -0,0 +1,21 @@ +#pragma once +#include "cru/win/graph/win_painter.hpp" +#include "cru/win/native/win_native_window.hpp" + +namespace cru::win::native { +class WindowPainter : public graph::WinPainter { + public: + explicit WindowPainter(WinNativeWindow* window); + WindowPainter(const WindowPainter& other) = delete; + WindowPainter& operator=(const WindowPainter& other) = delete; + WindowPainter(WindowPainter&& other) = delete; + WindowPainter& operator=(WindowPainter&& other) = delete; + ~WindowPainter() override = default; + + protected: + void DoEndDraw() override; + + private: + WinNativeWindow* window_; +}; +} // namespace cru::win::native diff --git a/src/win/native/window_render_target.cpp b/src/win/native/window_render_target.cpp new file mode 100644 index 00000000..c49a920e --- /dev/null +++ b/src/win/native/window_render_target.cpp @@ -0,0 +1,90 @@ +#include "cru/win/native/window_render_target.hpp" + +#include "cru/win/exception.hpp" +#include "cru/win/graph/graph_manager.hpp" +#include "dpi_util.hpp" + +#include <cassert> + +namespace cru::win::native { +WindowRenderTarget::WindowRenderTarget(graph::GraphManager* graph_manager, + HWND hwnd) { + this->graph_manager_ = graph_manager; + + const auto d3d11_device = graph_manager->GetD3D11Device(); + const auto dxgi_factory = graph_manager->GetDxgiFactory(); + + // Allocate a descriptor. + DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = {0}; + swap_chain_desc.Width = 0; // use automatic sizing + swap_chain_desc.Height = 0; + swap_chain_desc.Format = + DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format + swap_chain_desc.Stereo = false; + swap_chain_desc.SampleDesc.Count = 1; // don't use multi-sampling + swap_chain_desc.SampleDesc.Quality = 0; + swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swap_chain_desc.BufferCount = 2; // use double buffering to enable flip + swap_chain_desc.Scaling = DXGI_SCALING_NONE; + swap_chain_desc.SwapEffect = + DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // all apps must use this SwapEffect + swap_chain_desc.Flags = 0; + + // Get the final swap chain for this window from the DXGI factory. + ThrowIfFailed(dxgi_factory->CreateSwapChainForHwnd( + d3d11_device, hwnd, &swap_chain_desc, nullptr, nullptr, + &dxgi_swap_chain_)); + + CreateTargetBitmap(); +} + +void WindowRenderTarget::ResizeBuffer(const int width, const int height) { + const auto graph_manager = graph_manager_; + const auto d2d1_device_context = graph_manager->GetD2D1DeviceContext(); + + Microsoft::WRL::ComPtr<ID2D1Image> old_target; + d2d1_device_context->GetTarget(&old_target); + const auto target_this = old_target == this->target_bitmap_; + if (target_this) d2d1_device_context->SetTarget(nullptr); + + old_target = nullptr; + target_bitmap_ = nullptr; + + ThrowIfFailed(dxgi_swap_chain_->ResizeBuffers(0, width, height, + DXGI_FORMAT_UNKNOWN, 0)); + + CreateTargetBitmap(); + + if (target_this) d2d1_device_context->SetTarget(target_bitmap_.Get()); +} + +void WindowRenderTarget::SetAsTarget() { + graph_manager_->GetD2D1DeviceContext()->SetTarget(target_bitmap_.Get()); +} + +void WindowRenderTarget::Present() { + ThrowIfFailed(dxgi_swap_chain_->Present(1, 0)); +} + +void WindowRenderTarget::CreateTargetBitmap() { + assert(target_bitmap_ == nullptr); // target bitmap must not exist. + + // Direct2D needs the dxgi version of the backbuffer surface pointer. + Microsoft::WRL::ComPtr<IDXGISurface> dxgi_back_buffer; + ThrowIfFailed( + dxgi_swap_chain_->GetBuffer(0, IID_PPV_ARGS(&dxgi_back_buffer))); + + const auto dpi = GetDpi(); + + auto bitmap_properties = D2D1::BitmapProperties1( + D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, + D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE), + dpi.x, dpi.y); + + // Get a D2D surface from the DXGI back buffer to use as the D2D render + // target. + ThrowIfFailed( + graph_manager_->GetD2D1DeviceContext()->CreateBitmapFromDxgiSurface( + dxgi_back_buffer.Get(), &bitmap_properties, &target_bitmap_)); +} +} // namespace cru::win::native diff --git a/src/win/string_util.cpp b/src/win/string_util.cpp new file mode 100644 index 00000000..dd513b12 --- /dev/null +++ b/src/win/string_util.cpp @@ -0,0 +1,20 @@ +#include "cru/platform/string_util.hpp" + +#include "cru/win/exception.hpp" + +namespace cru::platform { +std::string ToUtf8String(const std::wstring_view& string) { + if (string.empty()) return std::string(); + + const auto length = ::WideCharToMultiByte(CP_UTF8, 0, string.data(), -1, + nullptr, 0, nullptr, nullptr); + std::string result; + result.resize(length); + if (::WideCharToMultiByte(CP_UTF8, 0, string.data(), -1, result.data(), + static_cast<int>(result.size()), nullptr, + nullptr) == 0) + throw win::Win32Error(::GetLastError(), + "Failed to convert wide string to UTF-8."); + return result; +} +} // namespace cru::platform |