aboutsummaryrefslogtreecommitdiff
path: root/src/win
diff options
context:
space:
mode:
Diffstat (limited to 'src/win')
-rw-r--r--src/win/CMakeLists.txt9
-rw-r--r--src/win/ForDllExport.cpp5
-rw-r--r--src/win/graphics/CMakeLists.txt1
-rw-r--r--src/win/graphics/direct/Brush.cpp17
-rw-r--r--src/win/graphics/direct/CMakeLists.txt16
-rw-r--r--src/win/graphics/direct/Factory.cpp99
-rw-r--r--src/win/graphics/direct/Font.cpp34
-rw-r--r--src/win/graphics/direct/Geometry.cpp125
-rw-r--r--src/win/graphics/direct/Image.cpp45
-rw-r--r--src/win/graphics/direct/ImageFactory.cpp159
-rw-r--r--src/win/graphics/direct/Painter.cpp183
-rw-r--r--src/win/graphics/direct/Resource.cpp16
-rw-r--r--src/win/graphics/direct/TextLayout.cpp162
-rw-r--r--src/win/graphics/direct/WindowPainter.cpp15
-rw-r--r--src/win/graphics/direct/WindowRenderTarget.cpp81
-rw-r--r--src/win/gui/CMakeLists.txt16
-rw-r--r--src/win/gui/Clipboard.cpp81
-rw-r--r--src/win/gui/Cursor.cpp54
-rw-r--r--src/win/gui/GodWindow.cpp63
-rw-r--r--src/win/gui/InputMethod.cpp286
-rw-r--r--src/win/gui/Keyboard.cpp74
-rw-r--r--src/win/gui/Resource.cpp6
-rw-r--r--src/win/gui/TimerManager.cpp99
-rw-r--r--src/win/gui/TimerManager.h61
-rw-r--r--src/win/gui/UiApplication.cpp113
-rw-r--r--src/win/gui/Window.cpp593
-rw-r--r--src/win/gui/WindowClass.cpp28
-rw-r--r--src/win/gui/WindowManager.cpp57
-rw-r--r--src/win/gui/WindowManager.h51
29 files changed, 0 insertions, 2549 deletions
diff --git a/src/win/CMakeLists.txt b/src/win/CMakeLists.txt
deleted file mode 100644
index 607d8b61..00000000
--- a/src/win/CMakeLists.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-add_library(CruWinBase SHARED
- ForDllExport.cpp
-)
-target_compile_definitions(CruWinBase PUBLIC UNICODE _UNICODE) # use unicode
-target_compile_definitions(CruWinBase PRIVATE CRU_WIN_EXPORT_API)
-target_link_libraries(CruWinBase PUBLIC CruBase)
-
-add_subdirectory(graphics)
-add_subdirectory(gui)
diff --git a/src/win/ForDllExport.cpp b/src/win/ForDllExport.cpp
deleted file mode 100644
index e49a3626..00000000
--- a/src/win/ForDllExport.cpp
+++ /dev/null
@@ -1,5 +0,0 @@
-#include "cru/win/Base.h"
-
-namespace cru::platform::win {
-CRU_WIN_API void Dummy() {}
-} // namespace cru::platform::win
diff --git a/src/win/graphics/CMakeLists.txt b/src/win/graphics/CMakeLists.txt
deleted file mode 100644
index c90537ac..00000000
--- a/src/win/graphics/CMakeLists.txt
+++ /dev/null
@@ -1 +0,0 @@
-add_subdirectory(direct)
diff --git a/src/win/graphics/direct/Brush.cpp b/src/win/graphics/direct/Brush.cpp
deleted file mode 100644
index 362a32ea..00000000
--- a/src/win/graphics/direct/Brush.cpp
+++ /dev/null
@@ -1,17 +0,0 @@
-#include "cru/win/graphics/direct/Brush.h"
-
-#include "cru/win/graphics/direct/ConvertUtil.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-
-namespace cru::platform::graphics::win::direct {
-D2DSolidColorBrush::D2DSolidColorBrush(DirectGraphicsFactory* factory)
- : DirectGraphicsResource(factory) {
- ThrowIfFailed(factory->GetDefaultD2D1DeviceContext()->CreateSolidColorBrush(
- Convert(color_), &brush_));
-}
-
-void D2DSolidColorBrush::SetColor(const Color& color) {
- brush_->SetColor(Convert(color));
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/CMakeLists.txt b/src/win/graphics/direct/CMakeLists.txt
deleted file mode 100644
index a9d5900b..00000000
--- a/src/win/graphics/direct/CMakeLists.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-add_library(CruPlatformGraphicsDirect2d SHARED
- Brush.cpp
- Font.cpp
- Geometry.cpp
- Image.cpp
- ImageFactory.cpp
- Factory.cpp
- Painter.cpp
- Resource.cpp
- TextLayout.cpp
- WindowPainter.cpp
- WindowRenderTarget.cpp
-)
-target_link_libraries(CruPlatformGraphicsDirect2d PUBLIC D3D11 D2d1 DWrite)
-target_link_libraries(CruPlatformGraphicsDirect2d PUBLIC CruWinBase CruPlatformGraphics)
-target_compile_definitions(CruPlatformGraphicsDirect2d PRIVATE CRU_WIN_GRAPHICS_DIRECT_EXPORT_API)
diff --git a/src/win/graphics/direct/Factory.cpp b/src/win/graphics/direct/Factory.cpp
deleted file mode 100644
index e8b3f107..00000000
--- a/src/win/graphics/direct/Factory.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-#include "cru/win/graphics/direct/Factory.h"
-
-#include "cru/common/log/Logger.h"
-#include "cru/win/graphics/direct/Brush.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Font.h"
-#include "cru/win/graphics/direct/Geometry.h"
-#include "cru/win/graphics/direct/ImageFactory.h"
-#include "cru/win/graphics/direct/TextLayout.h"
-
-#include <cstdlib>
-#include <utility>
-
-namespace cru::platform::graphics::win::direct {
-
-DirectGraphicsFactory::DirectGraphicsFactory() {
- // TODO: Detect repeated creation. Because I don't think we can create two d2d
- // and dwrite factory so we need to prevent the "probably dangerous" behavior.
-
- 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_)));
-
- ThrowIfFailed(d2d1_factory_->CreateDevice(dxgi_device.Get(), &d2d1_device_));
-
- d2d1_device_context_ = CreateD2D1DeviceContext();
-
- // 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_));
-
- image_factory_ = std::make_unique<WinImageFactory>(this);
-}
-
-DirectGraphicsFactory::~DirectGraphicsFactory() {}
-
-Microsoft::WRL::ComPtr<ID2D1DeviceContext1>
-DirectGraphicsFactory::CreateD2D1DeviceContext() {
- Microsoft::WRL::ComPtr<ID2D1DeviceContext1> d2d1_device_context;
- ThrowIfFailed(d2d1_device_->CreateDeviceContext(
- D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2d1_device_context));
- return d2d1_device_context;
-}
-
-std::unique_ptr<ISolidColorBrush>
-DirectGraphicsFactory::CreateSolidColorBrush() {
- return std::make_unique<D2DSolidColorBrush>(this);
-}
-
-std::unique_ptr<IGeometryBuilder>
-DirectGraphicsFactory::CreateGeometryBuilder() {
- return std::make_unique<D2DGeometryBuilder>(this);
-}
-
-std::unique_ptr<IFont> DirectGraphicsFactory::CreateFont(String font_family,
- float font_size) {
- return std::make_unique<DWriteFont>(this, std::move(font_family), font_size);
-}
-
-std::unique_ptr<ITextLayout> DirectGraphicsFactory::CreateTextLayout(
- std::shared_ptr<IFont> font, String text) {
- return std::make_unique<DWriteTextLayout>(this, std::move(font),
- std::move(text));
-}
-
-IImageFactory* DirectGraphicsFactory::GetImageFactory() {
- return image_factory_.get();
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/Font.cpp b/src/win/graphics/direct/Font.cpp
deleted file mode 100644
index 9e493948..00000000
--- a/src/win/graphics/direct/Font.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "cru/win/graphics/direct/Font.h"
-
-#include "cru/common/Format.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-
-#include <array>
-#include <utility>
-
-namespace cru::platform::graphics::win::direct {
-DWriteFont::DWriteFont(DirectGraphicsFactory* factory, String font_family,
- float font_size)
- : DirectGraphicsResource(factory), font_family_(std::move(font_family)) {
- // Get locale
- std::array<wchar_t, LOCALE_NAME_MAX_LENGTH> buffer;
- if (!::GetUserDefaultLocaleName(buffer.data(),
- static_cast<int>(buffer.size())))
- throw platform::win::Win32Error(
- ::GetLastError(), u"Failed to get locale when create dwrite font.");
-
- ThrowIfFailed(factory->GetDWriteFactory()->CreateTextFormat(
- reinterpret_cast<const wchar_t*>(font_family_.c_str()), 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_LEADING));
- ThrowIfFailed(
- text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
-}
-
-String DWriteFont::GetFontName() { return font_family_; }
-
-float DWriteFont::GetFontSize() { return text_format_->GetFontSize(); }
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/Geometry.cpp b/src/win/graphics/direct/Geometry.cpp
deleted file mode 100644
index f377356c..00000000
--- a/src/win/graphics/direct/Geometry.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-#include "cru/win/graphics/direct/Geometry.h"
-
-#include "cru/common/platform/win/Exception.h"
-#include "cru/win/graphics/direct/ConvertUtil.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-
-#include <d2d1.h>
-#include <d2d1helper.h>
-
-namespace cru::platform::graphics::win::direct {
-D2DGeometryBuilder::D2DGeometryBuilder(DirectGraphicsFactory* factory)
- : DirectGraphicsResource(factory) {
- ThrowIfFailed(factory->GetD2D1Factory()->CreatePathGeometry(&geometry_));
- ThrowIfFailed(geometry_->Open(&geometry_sink_));
-}
-
-void D2DGeometryBuilder::CheckValidation() {
- if (!IsValid())
- throw ReuseException(u"The geometry builder is already disposed.");
-}
-
-Point D2DGeometryBuilder::GetCurrentPosition() {
- CheckValidation();
- return current_position_;
-}
-
-void D2DGeometryBuilder::MoveTo(const Point& point) {
- CheckValidation();
- geometry_sink_->BeginFigure(Convert(point), D2D1_FIGURE_BEGIN_FILLED);
- start_point_ = current_position_ = point;
-}
-
-void D2DGeometryBuilder::LineTo(const Point& point) {
- CheckValidation();
- geometry_sink_->AddLine(Convert(point));
- current_position_ = point;
-}
-
-void D2DGeometryBuilder::CubicBezierTo(const Point& start_control_point,
- const Point& end_control_point,
- const Point& end_point) {
- CheckValidation();
- geometry_sink_->AddBezier(D2D1::BezierSegment(Convert(start_control_point),
- Convert(end_control_point),
- Convert(end_point)));
- current_position_ = end_point;
-}
-
-void D2DGeometryBuilder::QuadraticBezierTo(const Point& control_point,
- const Point& end_point) {
- CheckValidation();
- geometry_sink_->AddQuadraticBezier(
- D2D1::QuadraticBezierSegment(Convert(control_point), Convert(end_point)));
- current_position_ = end_point;
-}
-
-void D2DGeometryBuilder::ArcTo(const Point& radius, float angle,
- bool is_large_arc, bool is_clockwise,
- const Point& end_point) {
- CheckValidation();
- geometry_sink_->AddArc(D2D1::ArcSegment(
- Convert(end_point), {radius.x, radius.y}, angle,
- is_clockwise ? D2D1_SWEEP_DIRECTION_CLOCKWISE
- : D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE,
- is_large_arc ? D2D1_ARC_SIZE_LARGE : D2D1_ARC_SIZE_SMALL));
- current_position_ = end_point;
-}
-
-void D2DGeometryBuilder::CloseFigure(bool close) {
- CheckValidation();
- geometry_sink_->EndFigure(close ? D2D1_FIGURE_END_CLOSED
- : D2D1_FIGURE_END_OPEN);
- current_position_ = start_point_;
-}
-
-std::unique_ptr<IGeometry> D2DGeometryBuilder::Build() {
- CheckValidation();
- ThrowIfFailed(geometry_sink_->Close());
- geometry_sink_ = nullptr;
- auto geometry =
- std::make_unique<D2DGeometry>(GetDirectFactory(), std::move(geometry_));
- geometry_ = nullptr;
- return geometry;
-}
-
-D2DGeometry::D2DGeometry(DirectGraphicsFactory* factory,
- Microsoft::WRL::ComPtr<ID2D1Geometry> geometry)
- : DirectGraphicsResource(factory), geometry_(std::move(geometry)) {}
-
-bool D2DGeometry::FillContains(const Point& point) {
- BOOL result;
- ThrowIfFailed(geometry_->FillContainsPoint(
- Convert(point), D2D1::Matrix3x2F::Identity(), &result));
- return result != 0;
-}
-
-Rect D2DGeometry::GetBounds() {
- D2D1_RECT_F bounds;
- ThrowIfFailed(geometry_->GetBounds(D2D1::Matrix3x2F::Identity(), &bounds));
- return Convert(bounds);
-}
-
-std::unique_ptr<IGeometry> D2DGeometry::Transform(const Matrix& matrix) {
- Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> d2d1_geometry;
- ThrowIfFailed(GetDirectFactory()->GetD2D1Factory()->CreateTransformedGeometry(
- geometry_.Get(), Convert(matrix), &d2d1_geometry));
- return std::make_unique<D2DGeometry>(GetDirectFactory(),
- std::move(d2d1_geometry));
-}
-
-std::unique_ptr<IGeometry> D2DGeometry::CreateStrokeGeometry(float width) {
- Microsoft::WRL::ComPtr<ID2D1PathGeometry> d2d1_geometry;
- ThrowIfFailed(
- GetDirectFactory()->GetD2D1Factory()->CreatePathGeometry(&d2d1_geometry));
- Microsoft::WRL::ComPtr<ID2D1GeometrySink> d2d1_geometry_sink;
- ThrowIfFailed(d2d1_geometry->Open(&d2d1_geometry_sink));
- ThrowIfFailed(
- geometry_->Widen(width, nullptr, nullptr, d2d1_geometry_sink.Get()));
- d2d1_geometry_sink->Close();
-
- return std::make_unique<D2DGeometry>(GetDirectFactory(),
- std::move(d2d1_geometry));
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/Image.cpp b/src/win/graphics/direct/Image.cpp
deleted file mode 100644
index 518b9516..00000000
--- a/src/win/graphics/direct/Image.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-#include "cru/win/graphics/direct/Image.h"
-#include <d2d1_1.h>
-#include "cru/common/platform/win/Exception.h"
-#include "cru/win/graphics/direct/ConvertUtil.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-#include "cru/win/graphics/direct/Painter.h"
-
-namespace cru::platform::graphics::win::direct {
-Direct2DImage::Direct2DImage(DirectGraphicsFactory* graphics_factory,
- Microsoft::WRL::ComPtr<ID2D1Bitmap1> d2d_bitmap)
- : DirectGraphicsResource(graphics_factory),
- d2d_bitmap_(std::move(d2d_bitmap)) {
- Expects(d2d_bitmap_);
-}
-
-Direct2DImage::~Direct2DImage() {}
-
-float Direct2DImage::GetWidth() { return d2d_bitmap_->GetSize().width; }
-
-float Direct2DImage::GetHeight() { return d2d_bitmap_->GetSize().height; }
-
-std::unique_ptr<IImage> Direct2DImage::CreateWithRect(const Rect& rect) {
- auto device_context = GetDirectFactory()->CreateD2D1DeviceContext();
- Microsoft::WRL::ComPtr<ID2D1Bitmap1> bitmap;
- ThrowIfFailed(device_context->CreateBitmap(
- D2D1::SizeU(rect.width, rect.height), nullptr, 0,
- D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
- D2D1_ALPHA_MODE_PREMULTIPLIED)),
- &bitmap));
- device_context->SetTarget(bitmap.Get());
- device_context->BeginDraw();
- device_context->DrawBitmap(d2d_bitmap_.Get(), Convert(rect));
- ThrowIfFailed(device_context->EndDraw());
- return std::make_unique<Direct2DImage>(GetDirectFactory(), std::move(bitmap));
-}
-
-std::unique_ptr<IPainter> Direct2DImage::CreatePainter() {
- auto device_context = GetDirectFactory()->CreateD2D1DeviceContext();
- device_context->SetTarget(d2d_bitmap_.Get());
- return std::make_unique<D2DDeviceContextPainter>(device_context.Detach(),
- true);
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/ImageFactory.cpp b/src/win/graphics/direct/ImageFactory.cpp
deleted file mode 100644
index 0e8eb1b6..00000000
--- a/src/win/graphics/direct/ImageFactory.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-#include "cru/win/graphics/direct/ImageFactory.h"
-#include "cru/common/platform/win/Exception.h"
-#include "cru/common/platform/win/StreamConvert.h"
-#include "cru/platform/Check.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-#include "cru/win/graphics/direct/Image.h"
-
-#include <d2d1_1.h>
-#include <d2d1_1helper.h>
-#include <wincodec.h>
-#include <wrl/client.h>
-
-namespace cru::platform::graphics::win::direct {
-WinImageFactory::WinImageFactory(DirectGraphicsFactory* graphics_factory)
- : DirectGraphicsResource(graphics_factory) {
- HRESULT hr =
- CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
- IID_PPV_ARGS(&wic_imaging_factory_));
- ThrowIfFailed(hr);
-}
-
-WinImageFactory::~WinImageFactory() {}
-
-std::unique_ptr<IImage> WinImageFactory::DecodeFromStream(io::Stream* stream) {
- auto graphics_factory = GetDirectFactory();
-
- HRESULT hr;
-
- Microsoft::WRL::ComPtr<IStream> com_stream(
- platform::win::ConvertStreamToComStream(stream));
-
- Microsoft::WRL::ComPtr<IWICBitmapDecoder> wic_bitmap_decoder;
- hr = wic_imaging_factory_->CreateDecoderFromStream(
- com_stream.Get(), NULL, WICDecodeMetadataCacheOnDemand,
- &wic_bitmap_decoder);
- ThrowIfFailed(hr);
-
- Microsoft::WRL::ComPtr<IWICBitmapFrameDecode> wic_bitmap_frame_decode;
- hr = wic_bitmap_decoder->GetFrame(0, &wic_bitmap_frame_decode);
- ThrowIfFailed(hr);
-
- auto d2d_context = graphics_factory->GetDefaultD2D1DeviceContext();
-
- Microsoft::WRL::ComPtr<ID2D1Bitmap1> d2d_image;
- d2d_context->CreateBitmapFromWicBitmap(
- wic_bitmap_frame_decode.Get(),
- D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
- D2D1_ALPHA_MODE_PREMULTIPLIED)),
- &d2d_image);
-
- return std::make_unique<Direct2DImage>(graphics_factory,
- std::move(d2d_image));
-}
-
-GUID ConvertImageFormatToGUID(ImageFormat format) {
- GUID format_guid;
- switch (format) {
- case ImageFormat::Png:
- format_guid = GUID_ContainerFormatPng;
- break;
- case ImageFormat::Jpeg:
- format_guid = GUID_ContainerFormatJpeg;
- break;
- case ImageFormat::Gif:
- format_guid = GUID_ContainerFormatGif;
- break;
- default:
- throw Exception(u"Unknown image format");
- }
- return format_guid;
-}
-
-void WinImageFactory::EncodeToStream(IImage* image, io::Stream* stream,
- ImageFormat format, float quality) {
- auto direct_image = CheckPlatform<Direct2DImage>(image, GetPlatformId());
-
- Microsoft::WRL::ComPtr<IStream> com_stream(
- platform::win::ConvertStreamToComStream(stream));
-
- auto d2d_bitmap = direct_image->GetD2DBitmap();
- auto size = d2d_bitmap->GetPixelSize();
- FLOAT dpi_x, dpi_y;
- d2d_bitmap->GetDpi(&dpi_x, &dpi_y);
- auto pixel_format = d2d_bitmap->GetPixelFormat();
- Ensures(pixel_format.format == DXGI_FORMAT_B8G8R8A8_UNORM);
- Ensures(pixel_format.alphaMode == D2D1_ALPHA_MODE_PREMULTIPLIED);
-
- Microsoft::WRL::ComPtr<ID2D1Bitmap1> cpu_bitmap;
- ThrowIfFailed(GetDirectFactory()->GetDefaultD2D1DeviceContext()->CreateBitmap(
- size, nullptr, 0,
- D2D1::BitmapProperties1(
- D2D1_BITMAP_OPTIONS_CANNOT_DRAW | D2D1_BITMAP_OPTIONS_CPU_READ,
- pixel_format, dpi_x, dpi_y),
- &cpu_bitmap));
-
- ThrowIfFailed(cpu_bitmap->CopyFromBitmap(nullptr, d2d_bitmap.Get(), nullptr));
-
- D2D1_MAPPED_RECT mapped_rect;
- ThrowIfFailed(cpu_bitmap->Map(D2D1_MAP_OPTIONS_READ, &mapped_rect));
-
- Microsoft::WRL::ComPtr<IWICBitmap> wic_bitmap;
- ThrowIfFailed(wic_imaging_factory_->CreateBitmapFromMemory(
- size.width, size.height, GUID_WICPixelFormat32bppPBGRA, mapped_rect.pitch,
- mapped_rect.pitch * size.height, mapped_rect.bits, &wic_bitmap));
-
- ThrowIfFailed(cpu_bitmap->Unmap());
-
- Microsoft::WRL::ComPtr<IWICBitmapEncoder> wic_bitmap_encoder;
-
- ThrowIfFailed(wic_imaging_factory_->CreateEncoder(
- ConvertImageFormatToGUID(format), nullptr, &wic_bitmap_encoder));
-
- ThrowIfFailed(wic_bitmap_encoder->Initialize(com_stream.Get(),
- WICBitmapEncoderNoCache));
-
- Microsoft::WRL::ComPtr<IWICBitmapFrameEncode> wic_bitmap_frame_encode;
- Microsoft::WRL::ComPtr<IPropertyBag2> property_bag;
- ThrowIfFailed(wic_bitmap_encoder->CreateNewFrame(&wic_bitmap_frame_encode,
- &property_bag));
-
- if (format == ImageFormat::Jpeg) {
- PROPBAG2 option = {0};
- option.pstrName = const_cast<wchar_t*>(L"ImageQuality");
- VARIANT varValue;
- VariantInit(&varValue);
- varValue.vt = VT_R4;
- varValue.fltVal = quality;
- ThrowIfFailed(property_bag->Write(1, &option, &varValue));
- }
-
- ThrowIfFailed(wic_bitmap_frame_encode->Initialize(property_bag.Get()));
- ThrowIfFailed(wic_bitmap_frame_encode->SetResolution(dpi_x, dpi_y));
- ThrowIfFailed(wic_bitmap_frame_encode->WriteSource(wic_bitmap.Get(), NULL));
- ThrowIfFailed(wic_bitmap_frame_encode->Commit());
-
- ThrowIfFailed(wic_bitmap_encoder->Commit());
-}
-
-std::unique_ptr<IImage> WinImageFactory::CreateBitmap(int width, int height) {
- if (width <= 0) throw Exception(u"Bitmap width must be greater than 0.");
- if (height <= 0) throw Exception(u"Bitmap height must be greater than 0.");
-
- auto graphics_factory = GetDirectFactory();
-
- Microsoft::WRL::ComPtr<ID2D1Bitmap1> bitmap;
-
- auto d2d_context = graphics_factory->GetDefaultD2D1DeviceContext();
- ThrowIfFailed(d2d_context->CreateBitmap(
- D2D1::SizeU(width, height), nullptr, 0,
- D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
- D2D1_ALPHA_MODE_PREMULTIPLIED)),
- &bitmap));
-
- return std::make_unique<Direct2DImage>(graphics_factory, std::move(bitmap));
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/Painter.cpp b/src/win/graphics/direct/Painter.cpp
deleted file mode 100644
index 3e8bd5c1..00000000
--- a/src/win/graphics/direct/Painter.cpp
+++ /dev/null
@@ -1,183 +0,0 @@
-#include "cru/win/graphics/direct/Painter.h"
-
-#include "cru/common/log/Logger.h"
-#include "cru/platform/Check.h"
-#include "cru/win/graphics/direct/Brush.h"
-#include "cru/win/graphics/direct/ConvertUtil.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Geometry.h"
-#include "cru/win/graphics/direct/Image.h"
-#include "cru/win/graphics/direct/TextLayout.h"
-
-#include <type_traits>
-
-namespace cru::platform::graphics::win::direct {
-D2DDeviceContextPainter::D2DDeviceContextPainter(
- ID2D1DeviceContext1* device_context, bool release) {
- Expects(device_context);
- device_context_ = device_context;
- release_ = release;
- device_context->BeginDraw();
-}
-
-D2DDeviceContextPainter::~D2DDeviceContextPainter() {
- if (is_drawing_) {
- CRU_LOG_INFO(u"You may forget to call EndDraw before destroying painter.");
- }
-
- if (release_) {
- device_context_->Release();
- device_context_ = nullptr;
- }
-}
-
-platform::Matrix D2DDeviceContextPainter::GetTransform() {
- CheckValidation();
- D2D1_MATRIX_3X2_F m;
- device_context_->GetTransform(&m);
- return Convert(m);
-}
-
-void D2DDeviceContextPainter::SetTransform(const platform::Matrix& matrix) {
- CheckValidation();
- device_context_->SetTransform(Convert(matrix));
-}
-
-void D2DDeviceContextPainter::ConcatTransform(const Matrix& matrix) {
- SetTransform(GetTransform() * matrix);
-}
-
-void D2DDeviceContextPainter::Clear(const Color& color) {
- CheckValidation();
- device_context_->Clear(Convert(color));
-}
-
-void D2DDeviceContextPainter::DrawLine(const Point& start, const Point& end,
- IBrush* brush, float width) {
- CheckValidation();
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->DrawLine(Convert(start), Convert(end),
- b->GetD2DBrushInterface(), width);
-}
-
-void D2DDeviceContextPainter::StrokeRectangle(const Rect& rectangle,
- IBrush* brush, float width) {
- CheckValidation();
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->DrawRectangle(Convert(rectangle), b->GetD2DBrushInterface(),
- width);
-}
-
-void D2DDeviceContextPainter::FillRectangle(const Rect& rectangle,
- IBrush* brush) {
- CheckValidation();
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->FillRectangle(Convert(rectangle), b->GetD2DBrushInterface());
-}
-
-void D2DDeviceContextPainter::StrokeEllipse(const Rect& outline_rect,
- IBrush* brush, float width) {
- CheckValidation();
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->DrawEllipse(
- D2D1::Ellipse(Convert(outline_rect.GetCenter()),
- outline_rect.width / 2.0f, outline_rect.height / 2.0f),
- b->GetD2DBrushInterface(), width);
-}
-void D2DDeviceContextPainter::FillEllipse(const Rect& outline_rect,
- IBrush* brush) {
- CheckValidation();
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->FillEllipse(
- D2D1::Ellipse(Convert(outline_rect.GetCenter()),
- outline_rect.width / 2.0f, outline_rect.height / 2.0f),
- b->GetD2DBrushInterface());
-}
-
-void D2DDeviceContextPainter::StrokeGeometry(IGeometry* geometry, IBrush* brush,
- float width) {
- CheckValidation();
- const auto g = CheckPlatform<D2DGeometry>(geometry, GetPlatformId());
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->DrawGeometry(g->GetComInterface(), b->GetD2DBrushInterface(),
- width);
-}
-
-void D2DDeviceContextPainter::FillGeometry(IGeometry* geometry, IBrush* brush) {
- CheckValidation();
- const auto g = CheckPlatform<D2DGeometry>(geometry, GetPlatformId());
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->FillGeometry(g->GetComInterface(),
- b->GetD2DBrushInterface());
-}
-
-void D2DDeviceContextPainter::DrawText(const Point& offset,
- ITextLayout* text_layout,
- IBrush* brush) {
- CheckValidation();
- const auto t = CheckPlatform<DWriteTextLayout>(text_layout, GetPlatformId());
- const auto b = CheckPlatform<ID2DBrush>(brush, GetPlatformId());
- device_context_->DrawTextLayout(Convert(offset), t->GetComInterface(),
- b->GetD2DBrushInterface());
-}
-
-void D2DDeviceContextPainter::DrawImage(const Point& offset, IImage* image) {
- CheckValidation();
- const auto i = CheckPlatform<Direct2DImage>(image, GetPlatformId());
-
- Microsoft::WRL::ComPtr<ID2D1DeviceContext> device_context;
-
- device_context_->QueryInterface(device_context.GetAddressOf());
- device_context->DrawImage(i->GetD2DBitmap().Get(), Convert(offset));
-}
-
-void D2DDeviceContextPainter::PushLayer(const Rect& bounds) {
- CheckValidation();
-
- Microsoft::WRL::ComPtr<ID2D1Layer> layer;
- ThrowIfFailed(device_context_->CreateLayer(&layer));
-
- device_context_->PushLayer(D2D1::LayerParameters(Convert(bounds)),
- layer.Get());
-
- layers_.push_back(std::move(layer));
-}
-
-void D2DDeviceContextPainter::PopLayer() {
- device_context_->PopLayer();
- layers_.pop_back();
-}
-
-void D2DDeviceContextPainter::PushState() {
- Microsoft::WRL::ComPtr<ID2D1Factory> factory = nullptr;
- device_context_->GetFactory(&factory);
-
- Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock> state_block;
- factory->CreateDrawingStateBlock(&state_block);
- device_context_->SaveDrawingState(state_block.Get());
-
- drawing_state_stack_.push_back(std::move(state_block));
-}
-
-void D2DDeviceContextPainter::PopState() {
- Expects(!drawing_state_stack_.empty());
- auto drawing_state = drawing_state_stack_.back();
- drawing_state_stack_.pop_back();
- device_context_->RestoreDrawingState(drawing_state.Get());
-}
-
-void D2DDeviceContextPainter::EndDraw() {
- if (is_drawing_) {
- is_drawing_ = false;
- ThrowIfFailed(device_context_->EndDraw());
- DoEndDraw();
- }
-}
-
-void D2DDeviceContextPainter::CheckValidation() {
- if (!is_drawing_) {
- throw cru::platform::ReuseException(
- u"Can't do that on painter after end drawing.");
- }
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/Resource.cpp b/src/win/graphics/direct/Resource.cpp
deleted file mode 100644
index a9c53ee0..00000000
--- a/src/win/graphics/direct/Resource.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#include "cru/win/graphics/direct/Resource.h"
-
-#include "cru/win/graphics/direct/Factory.h"
-
-namespace cru::platform::graphics::win::direct {
-String DirectResource::kPlatformId = u"Windows Direct";
-
-DirectGraphicsResource::DirectGraphicsResource(DirectGraphicsFactory* factory)
- : factory_(factory) {
- Expects(factory);
-}
-
-IGraphicsFactory* DirectGraphicsResource::GetGraphicsFactory() {
- return factory_;
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/TextLayout.cpp b/src/win/graphics/direct/TextLayout.cpp
deleted file mode 100644
index ffef5e0c..00000000
--- a/src/win/graphics/direct/TextLayout.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-#include "cru/win/graphics/direct/TextLayout.h"
-#include <dwrite.h>
-
-#include "cru/common/log/Logger.h"
-#include "cru/platform/Check.h"
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-#include "cru/win/graphics/direct/Font.h"
-
-#include <utility>
-
-namespace cru::platform::graphics::win::direct {
-DWriteTextLayout::DWriteTextLayout(DirectGraphicsFactory* factory,
- std::shared_ptr<IFont> font, String text)
- : DirectGraphicsResource(factory), text_(std::move(text)) {
- Expects(font);
- font_ = CheckPlatform<DWriteFont>(font, GetPlatformId());
-
- ThrowIfFailed(factory->GetDWriteFactory()->CreateTextLayout(
- reinterpret_cast<const wchar_t*>(text_.c_str()),
- static_cast<UINT32>(text_.size()), font_->GetComInterface(), max_width_,
- max_height_, &text_layout_));
-}
-
-DWriteTextLayout::~DWriteTextLayout() = default;
-
-String DWriteTextLayout::GetText() { return text_; }
-
-void DWriteTextLayout::SetText(String new_text) {
- text_ = std::move(new_text);
- ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout(
- reinterpret_cast<const wchar_t*>(text_.c_str()),
- static_cast<UINT32>(text_.size()), font_->GetComInterface(), max_width_,
- max_height_, &text_layout_));
-}
-
-std::shared_ptr<IFont> DWriteTextLayout::GetFont() {
- return std::dynamic_pointer_cast<IFont>(font_);
-}
-
-void DWriteTextLayout::SetFont(std::shared_ptr<IFont> font) {
- font_ = CheckPlatform<DWriteFont>(font, GetPlatformId());
- ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout(
- reinterpret_cast<const wchar_t*>(text_.c_str()),
- static_cast<UINT32>(text_.size()), font_->GetComInterface(), max_width_,
- max_height_, &text_layout_));
-}
-
-void DWriteTextLayout::SetMaxWidth(float max_width) {
- max_width_ = max_width;
- ThrowIfFailed(text_layout_->SetMaxWidth(max_width_));
-}
-
-void DWriteTextLayout::SetMaxHeight(float max_height) {
- max_height_ = max_height;
- ThrowIfFailed(text_layout_->SetMaxHeight(max_height_));
-}
-
-bool DWriteTextLayout::IsEditMode() { return edit_mode_; }
-
-void DWriteTextLayout::SetEditMode(bool enable) {
- edit_mode_ = enable;
- // TODO: Implement this.
-}
-
-Index DWriteTextLayout::GetLineIndexFromCharIndex(Index char_index) {
- if (char_index < 0 || char_index >= text_.size()) {
- return -1;
- }
-
- auto line_index = 0;
- for (Index i = 0; i < char_index; ++i) {
- if (text_[i] == u'\n') {
- line_index++;
- }
- }
-
- return line_index;
-}
-
-float DWriteTextLayout::GetLineHeight(Index line_index) {
- Index count = GetLineCount();
- std::vector<DWRITE_LINE_METRICS> line_metrics(count);
-
- UINT32 actual_line_count = 0;
- text_layout_->GetLineMetrics(line_metrics.data(), static_cast<UINT32>(count),
- &actual_line_count);
- return line_metrics[line_index].height;
-}
-
-Index DWriteTextLayout::GetLineCount() {
- UINT32 line_count = 0;
- text_layout_->GetLineMetrics(nullptr, 0, &line_count);
- return line_count;
-}
-
-Rect DWriteTextLayout::GetTextBounds(bool includingTrailingSpace) {
- DWRITE_TEXT_METRICS metrics;
- ThrowIfFailed(text_layout_->GetMetrics(&metrics));
- return Rect{metrics.left, metrics.top,
- includingTrailingSpace ? metrics.widthIncludingTrailingWhitespace
- : metrics.width,
- metrics.height};
-}
-
-std::vector<Rect> DWriteTextLayout::TextRangeRect(
- const TextRange& text_range_arg) {
- if (text_range_arg.count == 0) {
- return {};
- }
- const auto text_range = text_range_arg.Normalize();
-
- 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;
- ThrowIfFailed(text_layout_->HitTestTextRange(
- static_cast<UINT32>(text_range.position),
- static_cast<UINT32>(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<Rect> result;
- result.reserve(actual_count);
-
- for (const auto& metrics : hit_test_metrics) {
- result.push_back(
- Rect{metrics.left, metrics.top, metrics.width, metrics.height});
- }
-
- return result;
-}
-
-Rect DWriteTextLayout::TextSinglePoint(Index position, bool trailing) {
- DWRITE_HIT_TEST_METRICS metrics;
- FLOAT left;
- FLOAT top;
- ThrowIfFailed(text_layout_->HitTestTextPosition(static_cast<UINT32>(position),
- static_cast<BOOL>(trailing),
- &left, &top, &metrics));
- return Rect{left, top, 0, GetFont()->GetFontSize()};
-}
-
-TextHitTestResult DWriteTextLayout::HitTest(const Point& point) {
- BOOL trailing;
- BOOL inside;
- DWRITE_HIT_TEST_METRICS metrics;
-
- ThrowIfFailed(text_layout_->HitTestPoint(point.x, point.y, &trailing, &inside,
- &metrics));
-
- TextHitTestResult result;
- result.position = metrics.textPosition;
- result.trailing = trailing != 0;
- return result;
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/WindowPainter.cpp b/src/win/graphics/direct/WindowPainter.cpp
deleted file mode 100644
index c0808887..00000000
--- a/src/win/graphics/direct/WindowPainter.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
-#include "cru/win/graphics/direct/WindowPainter.h"
-
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-#include "cru/win/graphics/direct/WindowRenderTarget.h"
-
-namespace cru::platform::graphics::win::direct {
-D2DWindowPainter::D2DWindowPainter(D2DWindowRenderTarget* render_target)
- : D2DDeviceContextPainter(render_target->GetD2D1DeviceContext()),
- render_target_(render_target) {}
-
-D2DWindowPainter::~D2DWindowPainter() {}
-
-void D2DWindowPainter::DoEndDraw() { render_target_->Present(); }
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/graphics/direct/WindowRenderTarget.cpp b/src/win/graphics/direct/WindowRenderTarget.cpp
deleted file mode 100644
index 9cbce6a3..00000000
--- a/src/win/graphics/direct/WindowRenderTarget.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-#include "cru/win/graphics/direct/WindowRenderTarget.h"
-
-#include "cru/win/graphics/direct/Exception.h"
-#include "cru/win/graphics/direct/Factory.h"
-
-namespace cru::platform::graphics::win::direct {
-D2DWindowRenderTarget::D2DWindowRenderTarget(
- gsl::not_null<DirectGraphicsFactory*> factory, HWND hwnd)
- : factory_(factory), hwnd_(hwnd) {
- const auto d3d11_device = factory->GetD3D11Device();
- const auto dxgi_factory = factory->GetDxgiFactory();
-
- d2d1_device_context_ = factory->CreateD2D1DeviceContext();
- d2d1_device_context_->SetUnitMode(D2D1_UNIT_MODE_DIPS);
-
- // Allocate a descriptor.
- DXGI_SWAP_CHAIN_DESC1 swap_chain_desc;
- 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.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
- 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 D2DWindowRenderTarget::SetDpi(float x, float y) {
- d2d1_device_context_->SetDpi(x, y);
-}
-
-void D2DWindowRenderTarget::ResizeBuffer(const int width, const int height) {
- // In order to resize buffer, we need to untarget the buffer first.
- d2d1_device_context_->SetTarget(nullptr);
- target_bitmap_ = nullptr;
- ThrowIfFailed(dxgi_swap_chain_->ResizeBuffers(0, width, height,
- DXGI_FORMAT_UNKNOWN, 0));
- CreateTargetBitmap();
-}
-
-void D2DWindowRenderTarget::Present() {
- ThrowIfFailed(dxgi_swap_chain_->Present(1, 0));
-}
-
-void D2DWindowRenderTarget::CreateTargetBitmap() {
- Expects(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)));
-
- float dpi_x, dpi_y;
- d2d1_device_context_->GetDpi(&dpi_x, &dpi_y);
-
- 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(d2d1_device_context_->CreateBitmapFromDxgiSurface(
- dxgi_back_buffer.Get(), &bitmap_properties, &target_bitmap_));
-
- d2d1_device_context_->SetTarget(target_bitmap_.Get());
-}
-} // namespace cru::platform::graphics::win::direct
diff --git a/src/win/gui/CMakeLists.txt b/src/win/gui/CMakeLists.txt
deleted file mode 100644
index 4a27ffb6..00000000
--- a/src/win/gui/CMakeLists.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-add_library(CruPlatformGuiWin SHARED
- Clipboard.cpp
- Cursor.cpp
- GodWindow.cpp
- InputMethod.cpp
- Keyboard.cpp
- Resource.cpp
- TimerManager.cpp
- UiApplication.cpp
- Window.cpp
- WindowClass.cpp
- WindowManager.cpp
-)
-target_link_libraries(CruPlatformGuiWin PUBLIC imm32)
-target_link_libraries(CruPlatformGuiWin PUBLIC CruPlatformGraphicsDirect2d CruPlatformGui)
-target_compile_definitions(CruPlatformGuiWin PRIVATE CRU_WIN_GUI_EXPORT_API)
diff --git a/src/win/gui/Clipboard.cpp b/src/win/gui/Clipboard.cpp
deleted file mode 100644
index 6eab903c..00000000
--- a/src/win/gui/Clipboard.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-#include "cru/win/gui/Clipboard.h"
-#include "cru/common/log/Logger.h"
-#include "cru/win/gui/GodWindow.h"
-#include "cru/win/gui/UiApplication.h"
-
-namespace cru::platform::gui::win {
-WinClipboard::WinClipboard(WinUiApplication* application)
- : application_(application) {}
-
-WinClipboard::~WinClipboard() {}
-
-String WinClipboard::GetText() {
- auto god_window = application_->GetGodWindow();
-
- if (!::OpenClipboard(god_window->GetHandle())) {
- CRU_LOG_WARN(u"Failed to open clipboard.");
- return {};
- }
-
- if (!::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
- CRU_LOG_WARN(u"Clipboard format for text is not available.");
- return {};
- }
-
- auto handle = ::GetClipboardData(CF_UNICODETEXT);
-
- if (handle == nullptr) {
- CRU_LOG_WARN(u"Failed to get clipboard data.");
- return {};
- }
-
- auto ptr = ::GlobalLock(handle);
- if (ptr == nullptr) {
- CRU_LOG_WARN(u"Failed to lock clipboard data.");
- ::CloseClipboard();
- return {};
- }
-
- String result(static_cast<wchar_t*>(ptr));
-
- ::GlobalUnlock(handle);
- ::CloseClipboard();
-
- return result;
-}
-
-void WinClipboard::SetText(String text) {
- auto god_window = application_->GetGodWindow();
-
- if (!::OpenClipboard(god_window->GetHandle())) {
- CRU_LOG_WARN(u"Failed to open clipboard.");
- return;
- }
-
- auto handle = GlobalAlloc(GMEM_MOVEABLE, (text.size() + 1) * sizeof(wchar_t));
-
- if (handle == nullptr) {
- CRU_LOG_WARN(u"Failed to allocate clipboard data.");
- ::CloseClipboard();
- return;
- }
-
- auto ptr = ::GlobalLock(handle);
- if (ptr == nullptr) {
- CRU_LOG_WARN(u"Failed to lock clipboard data.");
- ::GlobalFree(handle);
- ::CloseClipboard();
- return;
- }
-
- std::memcpy(ptr, text.c_str(), (text.size() + 1) * sizeof(wchar_t));
-
- ::GlobalUnlock(handle);
-
- if (::SetClipboardData(CF_UNICODETEXT, handle) == nullptr) {
- CRU_LOG_WARN(u"Failed to set clipboard data.");
- }
-
- ::CloseClipboard();
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/Cursor.cpp b/src/win/gui/Cursor.cpp
deleted file mode 100644
index d85ba565..00000000
--- a/src/win/gui/Cursor.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-#include "cru/win/gui/Cursor.h"
-
-#include "cru/common/log/Logger.h"
-#include "cru/win/gui/Exception.h"
-
-#include <stdexcept>
-
-namespace cru::platform::gui::win {
-WinCursor::WinCursor(HCURSOR handle, bool auto_destroy) {
- handle_ = handle;
- auto_destroy_ = auto_destroy;
-}
-
-WinCursor::~WinCursor() {
- if (auto_destroy_) {
- if (!::DestroyCursor(handle_)) {
- // This is not a fetal error but might still need notice because it may
- // cause leak.
- CRU_LOG_WARN(u"Failed to destroy a cursor. Last error code: {}",
- ::GetLastError());
- }
- }
-}
-
-namespace {
-WinCursor* LoadWinCursor(const wchar_t* name) {
- const auto handle = static_cast<HCURSOR>(::LoadImageW(
- NULL, name, IMAGE_CURSOR, SM_CYCURSOR, SM_CYCURSOR, LR_SHARED));
- if (handle == NULL) {
- throw Win32Error(::GetLastError(), u"Failed to load system cursor.");
- }
- return new WinCursor(handle, false);
-}
-} // namespace
-
-WinCursorManager::WinCursorManager()
- : sys_arrow_(LoadWinCursor(IDC_ARROW)),
- sys_hand_(LoadWinCursor(IDC_HAND)),
- sys_ibeam_(LoadWinCursor(IDC_IBEAM)) {}
-
-std::shared_ptr<WinCursor> WinCursorManager::GetSystemWinCursor(
- SystemCursorType type) {
- switch (type) {
- case SystemCursorType::Arrow:
- return sys_arrow_;
- case SystemCursorType::Hand:
- return sys_hand_;
- case SystemCursorType::IBeam:
- return sys_ibeam_;
- default:
- throw std::runtime_error("Unknown system cursor value.");
- }
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/GodWindow.cpp b/src/win/gui/GodWindow.cpp
deleted file mode 100644
index 4416870f..00000000
--- a/src/win/gui/GodWindow.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-#include "cru/win/gui/GodWindow.h"
-
-#include "cru/common/log/Logger.h"
-#include "cru/win/gui/Exception.h"
-#include "cru/win/gui/UiApplication.h"
-#include "cru/win/gui/WindowClass.h"
-
-namespace cru::platform::gui::win {
-constexpr auto god_window_class_name = L"GodWindowClass";
-
-LRESULT CALLBACK GodWndProc(HWND hWnd, UINT uMsg, WPARAM wParam,
- LPARAM lParam) {
- const auto app = WinUiApplication::GetInstance();
-
- if (app) {
- LRESULT result;
- auto god_window = app->GetGodWindow();
- if (god_window != nullptr) {
- const auto handled = god_window->HandleGodWindowMessage(
- hWnd, uMsg, wParam, lParam, &result);
- if (handled) return result;
- }
- }
- return DefWindowProcW(hWnd, uMsg, wParam, lParam);
-}
-
-GodWindow::GodWindow(WinUiApplication* application) {
- application_ = application;
-
- const auto h_instance = application->GetInstanceHandle();
-
- god_window_class_ = std::make_unique<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(), u"Failed to create god window.");
-}
-
-GodWindow::~GodWindow() {
- if (!::DestroyWindow(hwnd_)) {
- // Although this could be "safely" ignore.
- CRU_LOG_WARN(u"Failed to destroy god window.");
- }
-}
-
-bool GodWindow::HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param,
- LPARAM l_param, LRESULT* result) {
- WindowNativeMessageEventArgs args(
- WindowNativeMessage{hwnd, msg, w_param, l_param});
- message_event_.Raise(args);
-
- if (args.IsHandled()) {
- *result = args.GetResult();
- return true;
- }
-
- return false;
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/InputMethod.cpp b/src/win/gui/InputMethod.cpp
deleted file mode 100644
index 8a54577b..00000000
--- a/src/win/gui/InputMethod.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-#include "cru/win/gui/InputMethod.h"
-
-#include "cru/common/log/Logger.h"
-#include "cru/common/StringUtil.h"
-#include "cru/platform/Check.h"
-#include "cru/platform/gui/DebugFlags.h"
-#include "cru/win/Exception.h"
-#include "cru/win/gui/Window.h"
-
-#include <vector>
-
-namespace cru::platform::gui::win {
-AutoHIMC::AutoHIMC(HWND hwnd) : hwnd_(hwnd) {
- Expects(hwnd);
- handle_ = ::ImmGetContext(hwnd);
-}
-
-AutoHIMC::AutoHIMC(AutoHIMC&& other)
- : hwnd_(other.hwnd_), handle_(other.handle_) {
- other.hwnd_ = nullptr;
- other.handle_ = nullptr;
-}
-
-AutoHIMC& AutoHIMC::operator=(AutoHIMC&& other) {
- if (this != &other) {
- Object::operator=(std::move(other));
- this->hwnd_ = other.hwnd_;
- this->handle_ = other.handle_;
- other.hwnd_ = nullptr;
- other.handle_ = nullptr;
- }
- return *this;
-}
-
-AutoHIMC::~AutoHIMC() {
- if (handle_) {
- if (!::ImmReleaseContext(hwnd_, handle_))
- CRU_LOG_WARN(u"Failed to release HIMC.");
- }
-}
-
-// copied from chromium
-namespace {
-// Determines whether or not the given attribute represents a target
-// (a.k.a. a selection).
-bool IsTargetAttribute(char attribute) {
- return (attribute == ATTR_TARGET_CONVERTED ||
- attribute == ATTR_TARGET_NOTCONVERTED);
-}
-// Helper function for ImeInput::GetCompositionInfo() method, to get the target
-// range that's selected by the user in the current composition string.
-void GetCompositionTargetRange(HIMC imm_context, int* target_start,
- int* target_end) {
- int attribute_size =
- ::ImmGetCompositionString(imm_context, GCS_COMPATTR, NULL, 0);
- if (attribute_size > 0) {
- int start = 0;
- int end = 0;
- std::vector<char> attribute_data(attribute_size);
- ::ImmGetCompositionString(imm_context, GCS_COMPATTR, attribute_data.data(),
- attribute_size);
- for (start = 0; start < attribute_size; ++start) {
- if (IsTargetAttribute(attribute_data[start])) break;
- }
- for (end = start; end < attribute_size; ++end) {
- if (!IsTargetAttribute(attribute_data[end])) break;
- }
- if (start == attribute_size) {
- // This composition clause does not contain any target clauses,
- // i.e. this clauses is an input clause.
- // We treat the whole composition as a target clause.
- start = 0;
- end = attribute_size;
- }
- *target_start = start;
- *target_end = end;
- }
-}
-// Helper function for ImeInput::GetCompositionInfo() method, to get underlines
-// information of the current composition string.
-CompositionClauses GetCompositionClauses(HIMC imm_context, int target_start,
- int target_end) {
- CompositionClauses result;
- int clause_size =
- ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, NULL, 0);
- int clause_length = clause_size / sizeof(std::uint32_t);
- if (clause_length) {
- result.reserve(clause_length - 1);
- std::vector<std::uint32_t> clause_data(clause_length);
- ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, clause_data.data(),
- clause_size);
- for (int i = 0; i < clause_length - 1; ++i) {
- CompositionClause clause;
- clause.start = clause_data[i];
- clause.end = clause_data[i + 1];
- clause.target = false;
- // Use thick underline for the target clause.
- if (clause.start >= target_start && clause.end <= target_end) {
- clause.target = true;
- }
- result.push_back(clause);
- }
- }
- return result;
-}
-
-String GetString(HIMC imm_context) {
- LONG string_size =
- ::ImmGetCompositionString(imm_context, GCS_COMPSTR, NULL, 0);
- String result((string_size / sizeof(char16_t)), 0);
- ::ImmGetCompositionString(imm_context, GCS_COMPSTR, result.data(),
- string_size);
- return result;
-}
-
-String GetResultString(HIMC imm_context) {
- LONG string_size =
- ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, NULL, 0);
- String result((string_size / sizeof(char16_t)), 0);
- ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, result.data(),
- string_size);
- return result;
-}
-
-CompositionText GetCompositionInfo(HIMC imm_context) {
- // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and
- // convert them into underlines and selection range respectively.
-
- auto text = GetString(imm_context);
-
- int length = static_cast<int>(text.length());
- // Find out the range selected by the user.
- int target_start = length;
- int target_end = length;
- GetCompositionTargetRange(imm_context, &target_start, &target_end);
-
- auto clauses = GetCompositionClauses(imm_context, target_start, target_end);
-
- int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0);
-
- return CompositionText{std::move(text), std::move(clauses),
- TextRange{cursor}};
-}
-
-} // namespace
-
-WinInputMethodContext::WinInputMethodContext(
- gsl::not_null<WinNativeWindow*> window)
- : native_window_(window) {
- event_guard_ += window->NativeMessageEvent()->AddHandler(
- std::bind(&WinInputMethodContext::OnWindowNativeMessage, this,
- std::placeholders::_1));
-}
-
-WinInputMethodContext::~WinInputMethodContext() {}
-
-void WinInputMethodContext::EnableIME() {
- const auto hwnd = native_window_->GetWindowHandle();
- if (::ImmAssociateContextEx(hwnd, nullptr, IACE_DEFAULT) == FALSE) {
- CRU_LOG_WARN(u"Failed to enable ime.");
- }
-}
-
-void WinInputMethodContext::DisableIME() {
- const auto hwnd = native_window_->GetWindowHandle();
- AutoHIMC himc{hwnd};
-
- ::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
-
- if (::ImmAssociateContextEx(hwnd, nullptr, 0) == FALSE) {
- CRU_LOG_WARN(u"Failed to disable ime.");
- }
-}
-
-void WinInputMethodContext::CompleteComposition() {
- auto himc = GetHIMC();
- if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) {
- CRU_LOG_WARN(u"Failed to complete composition.");
- }
-}
-
-void WinInputMethodContext::CancelComposition() {
- auto himc = GetHIMC();
- if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0)) {
- CRU_LOG_WARN(u"Failed to complete composition.");
- }
-}
-
-CompositionText WinInputMethodContext::GetCompositionText() {
- auto himc = GetHIMC();
- return GetCompositionInfo(himc.Get());
-}
-
-void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) {
- auto himc = GetHIMC();
-
- ::CANDIDATEFORM form;
- form.dwIndex = 0;
- form.dwStyle = CFS_CANDIDATEPOS;
-
- form.ptCurrentPos = native_window_->DipToPixel(point);
-
- if (!::ImmSetCandidateWindow(himc.Get(), &form))
- CRU_LOG_DEBUG(
- u"Failed to set input method candidate window position.");
-}
-
-IEvent<std::nullptr_t>* WinInputMethodContext::CompositionStartEvent() {
- return &composition_start_event_;
-}
-
-IEvent<std::nullptr_t>* WinInputMethodContext::CompositionEndEvent() {
- return &composition_end_event_;
-};
-
-IEvent<std::nullptr_t>* WinInputMethodContext::CompositionEvent() {
- return &composition_event_;
-}
-
-IEvent<StringView>* WinInputMethodContext::TextEvent() { return &text_event_; }
-
-void WinInputMethodContext::OnWindowNativeMessage(
- WindowNativeMessageEventArgs& args) {
- const auto& message = args.GetWindowMessage();
- switch (message.msg) {
- case WM_CHAR: {
- auto c = static_cast<char16_t>(message.w_param);
- if (IsUtf16SurrogatePairCodeUnit(c)) {
- // I don't think this will happen because normal key strike without ime
- // should only trigger ascci character. If it is a charater from
- // supplementary planes, it should be handled with ime messages.
- CRU_LOG_WARN(
- u"A WM_CHAR message for character from supplementary "
- u"planes is ignored.");
- } else {
- if (c != '\b') { // ignore backspace
- if (c == '\r') c = '\n'; // Change \r to \n
-
- char16_t s[1] = {c};
- text_event_.Raise({s, 1});
- }
- }
- args.HandleWithResult(0);
- break;
- }
- case WM_IME_COMPOSITION: {
- composition_event_.Raise(nullptr);
- auto composition_text = GetCompositionText();
- if constexpr (DebugFlags::input_method) {
- CRU_LOG_DEBUG(u"WM_IME_COMPOSITION composition text:\n{}",
- composition_text);
- }
- if (message.l_param & GCS_RESULTSTR) {
- auto result_string = GetResultString();
- text_event_.Raise(result_string);
- }
- break;
- }
- case WM_IME_STARTCOMPOSITION: {
- if constexpr (DebugFlags::input_method) {
- CRU_LOG_DEBUG(u"WM_IME_STARTCOMPOSITION received.");
- }
- composition_start_event_.Raise(nullptr);
- break;
- }
- case WM_IME_ENDCOMPOSITION: {
- if constexpr (DebugFlags::input_method) {
- CRU_LOG_DEBUG(u"WM_IME_ENDCOMPOSITION received.");
- }
- composition_end_event_.Raise(nullptr);
- break;
- }
- }
-}
-
-String WinInputMethodContext::GetResultString() {
- auto himc = GetHIMC();
- auto result = win::GetResultString(himc.Get());
- return result;
-}
-
-AutoHIMC WinInputMethodContext::GetHIMC() {
- const auto hwnd = native_window_->GetWindowHandle();
- return AutoHIMC{hwnd};
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/Keyboard.cpp b/src/win/gui/Keyboard.cpp
deleted file mode 100644
index 124d6109..00000000
--- a/src/win/gui/Keyboard.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-#include "cru/win/gui/Keyboard.h"
-
-namespace cru::platform::gui::win {
-KeyCode VirtualKeyToKeyCode(int virtual_key) {
- if (virtual_key >= 0x30 && virtual_key <= 0x39) {
- return KeyCode{static_cast<int>(KeyCode::N0) + (virtual_key - 0x30)};
- } else if (virtual_key >= 0x41 && virtual_key <= 0x5a) {
- return KeyCode{static_cast<int>(KeyCode::A) + (virtual_key - 0x41)};
- } else if (virtual_key >= VK_NUMPAD0 && virtual_key <= VK_NUMPAD9) {
- return KeyCode{static_cast<int>(KeyCode::NumPad0) +
- (virtual_key - VK_NUMPAD0)};
- } else if (virtual_key >= VK_F1 && virtual_key <= VK_F12) {
- return KeyCode{static_cast<int>(KeyCode::F1) + (virtual_key - VK_F1)};
- } else {
- switch (virtual_key) {
-#define CRU_MAP_KEY(virtual_key, keycode) \
- case virtual_key: \
- return KeyCode::keycode;
-
- CRU_MAP_KEY(VK_LBUTTON, LeftButton)
- CRU_MAP_KEY(VK_MBUTTON, MiddleButton)
- CRU_MAP_KEY(VK_RBUTTON, RightButton)
- CRU_MAP_KEY(VK_ESCAPE, Escape)
- CRU_MAP_KEY(VK_OEM_3, GraveAccent)
- CRU_MAP_KEY(VK_TAB, Tab)
- CRU_MAP_KEY(VK_CAPITAL, CapsLock)
- CRU_MAP_KEY(VK_LSHIFT, LeftShift)
- CRU_MAP_KEY(VK_LCONTROL, LeftCtrl)
- CRU_MAP_KEY(VK_LWIN, LeftSuper)
- CRU_MAP_KEY(VK_LMENU, LeftAlt)
- CRU_MAP_KEY(VK_OEM_MINUS, Minus)
- CRU_MAP_KEY(VK_OEM_PLUS, Equal)
- CRU_MAP_KEY(VK_BACK, Backspace)
- CRU_MAP_KEY(VK_OEM_4, LeftSquareBracket)
- CRU_MAP_KEY(VK_OEM_6, RightSquareBracket)
- CRU_MAP_KEY(VK_OEM_5, BackSlash)
- CRU_MAP_KEY(VK_OEM_1, Semicolon)
- CRU_MAP_KEY(VK_OEM_7, Quote)
- CRU_MAP_KEY(VK_OEM_COMMA, Comma)
- CRU_MAP_KEY(VK_OEM_PERIOD, Period)
- CRU_MAP_KEY(VK_OEM_2, Slash)
- CRU_MAP_KEY(VK_RSHIFT, RightShift)
- CRU_MAP_KEY(VK_RCONTROL, RightCtrl)
- CRU_MAP_KEY(VK_RWIN, RightSuper)
- CRU_MAP_KEY(VK_RMENU, RightAlt)
- CRU_MAP_KEY(VK_INSERT, Insert)
- CRU_MAP_KEY(VK_DELETE, Delete)
- CRU_MAP_KEY(VK_HOME, Home)
- CRU_MAP_KEY(VK_END, End)
- CRU_MAP_KEY(VK_PRIOR, PageUp)
- CRU_MAP_KEY(VK_NEXT, PageDown)
- CRU_MAP_KEY(VK_UP, Up)
- CRU_MAP_KEY(VK_LEFT, Left)
- CRU_MAP_KEY(VK_DOWN, Down)
- CRU_MAP_KEY(VK_RIGHT, Right)
- CRU_MAP_KEY(VK_SNAPSHOT, PrintScreen)
- CRU_MAP_KEY(VK_PAUSE, Pause)
-
-#undef CRU_MAP_KEY
-
- default:
- return KeyCode::Unknown;
- }
- }
-}
-
-KeyModifier RetrieveKeyMofifier() {
- KeyModifier result{0};
- if (::GetKeyState(VK_SHIFT) < 0) result |= KeyModifiers::shift;
- if (::GetKeyState(VK_CONTROL) < 0) result |= KeyModifiers::ctrl;
- if (::GetKeyState(VK_MENU) < 0) result |= KeyModifiers::alt;
- return result;
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/Resource.cpp b/src/win/gui/Resource.cpp
deleted file mode 100644
index f45c5df5..00000000
--- a/src/win/gui/Resource.cpp
+++ /dev/null
@@ -1,6 +0,0 @@
-#include "cru/win/gui/Resource.h"
-#include "cru/win/gui/Window.h"
-
-namespace cru::platform::gui::win {
-String WinNativeResource::kPlatformId = u"Windows";
-}
diff --git a/src/win/gui/TimerManager.cpp b/src/win/gui/TimerManager.cpp
deleted file mode 100644
index a09ee0bf..00000000
--- a/src/win/gui/TimerManager.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-#include "TimerManager.h"
-
-#include "cru/win/gui/Base.h"
-#include "cru/win/gui/Exception.h"
-
-#include <functional>
-#include <type_traits>
-
-namespace cru::platform::gui::win {
-constexpr int kSetImmediateWindowMessageId = WM_USER + 2000;
-
-TimerManager::TimerManager(GodWindow* god_window) {
- god_window_ = god_window;
- event_guard_ += god_window->MessageEvent()->AddHandler(std::bind(
- &TimerManager::HandleGodWindowMessage, this, std::placeholders::_1));
-}
-
-long long TimerManager::SetTimer(TimerType type, int period,
- std::function<void()> action) {
- auto id = next_id_++;
- TimerInfo timer_info{id, type, type == TimerType::Immediate ? 0 : period,
- std::move(action)};
- if (type == TimerType::Immediate) {
- if (!::PostMessageW(god_window_->GetHandle(), kSetImmediateWindowMessageId,
- gsl::narrow<UINT_PTR>(id), 0)) {
- throw Win32Error(
- ::GetLastError(),
- u"Failed to post window message to god window for set immediate.");
- }
- } else {
- CreateNativeTimer(&timer_info);
- }
-
- info_map_.emplace(id, std::move(timer_info));
- return id;
-}
-
-void TimerManager::CancelTimer(long long id) {
- if (id <= 0) return;
- auto find_result = this->info_map_.find(id);
- if (find_result != info_map_.cend()) {
- auto& info = find_result->second;
- KillNativeTimer(&info);
- this->info_map_.erase(find_result);
- }
-}
-
-void TimerManager::CreateNativeTimer(TimerInfo* info) {
- info->native_timer_id = gsl::narrow<UINT_PTR>(info->id);
- ::SetTimer(god_window_->GetHandle(), info->native_timer_id, info->period,
- nullptr);
-}
-
-void TimerManager::KillNativeTimer(TimerInfo* info) {
- if (info->native_timer_id == 0) return;
- ::KillTimer(god_window_->GetHandle(), info->native_timer_id);
- info->native_timer_id = 0;
-}
-
-void TimerManager::HandleGodWindowMessage(WindowNativeMessageEventArgs& args) {
- const auto& message = args.GetWindowMessage();
-
- switch (message.msg) {
- case kSetImmediateWindowMessageId: {
- auto find_result =
- this->info_map_.find(static_cast<long long>(message.w_param));
- if (find_result != info_map_.cend()) {
- auto& info = find_result->second;
- info.action();
- info_map_.erase(find_result);
- }
- args.SetResult(0);
- args.SetHandled(true);
- return;
- }
- case WM_TIMER: {
- auto find_result =
- this->info_map_.find(static_cast<long long>(message.w_param));
- if (find_result != info_map_.cend()) {
- auto& info = find_result->second;
- if (info.type == TimerType::Interval) {
- info.action();
- args.SetResult(0);
- args.SetHandled(true);
- } else if (info.type == TimerType::Timeout) {
- info.action();
- KillNativeTimer(&info);
- info_map_.erase(find_result);
- args.SetResult(0);
- args.SetHandled(true);
- }
- }
- return;
- }
- default:
- return;
- }
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/TimerManager.h b/src/win/gui/TimerManager.h
deleted file mode 100644
index c44bd5bd..00000000
--- a/src/win/gui/TimerManager.h
+++ /dev/null
@@ -1,61 +0,0 @@
-#pragma once
-#include "cru/common/Event.h"
-#include "cru/win/WinPreConfig.h"
-
-#include "cru/common/Base.h"
-#include "cru/win/gui/GodWindow.h"
-#include "cru/win/gui/WindowNativeMessageEventArgs.h"
-
-#include <chrono>
-#include <functional>
-#include <optional>
-#include <unordered_map>
-
-namespace cru::platform::gui::win {
-enum class TimerType { Immediate, Timeout, Interval };
-
-struct TimerInfo {
- TimerInfo(long long id, TimerType type, int period,
- std::function<void()> action, UINT_PTR native_timer_id = 0)
- : id(id),
- type(type),
- period(period),
- action(std::move(action)),
- native_timer_id(native_timer_id) {}
-
- long long id;
- TimerType type;
- int period; // in milliseconds
- std::function<void()> action;
- UINT_PTR native_timer_id;
-};
-
-class TimerManager : public Object {
- public:
- TimerManager(GodWindow* god_window);
-
- CRU_DELETE_COPY(TimerManager)
- CRU_DELETE_MOVE(TimerManager)
-
- ~TimerManager() override = default;
-
- // Period is in milliseconds. When type is immediate, it is not checked and
- // used.
- long long SetTimer(TimerType type, int period, std::function<void()> action);
- void CancelTimer(long long id);
-
- private:
- void HandleGodWindowMessage(WindowNativeMessageEventArgs& args);
-
- void CreateNativeTimer(TimerInfo* info);
- void KillNativeTimer(TimerInfo* info);
-
- private:
- GodWindow* god_window_;
-
- EventRevokerListGuard event_guard_;
-
- long long next_id_ = 1;
- std::unordered_map<long long, TimerInfo> info_map_;
-};
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/UiApplication.cpp b/src/win/gui/UiApplication.cpp
deleted file mode 100644
index 1c9321b6..00000000
--- a/src/win/gui/UiApplication.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-#include "cru/win/gui/UiApplication.h"
-
-#include "TimerManager.h"
-#include "WindowManager.h"
-#include "cru/common/log/Logger.h"
-#include "cru/platform/Check.h"
-#include "cru/win/graphics/direct/Factory.h"
-#include "cru/win/gui/Base.h"
-#include "cru/win/gui/Clipboard.h"
-#include "cru/win/gui/Cursor.h"
-#include "cru/win/gui/Exception.h"
-#include "cru/win/gui/GodWindow.h"
-#include "cru/win/gui/InputMethod.h"
-#include "cru/win/gui/Window.h"
-
-namespace cru::platform::gui {
-std::unique_ptr<IUiApplication> CreateUiApplication() {
- return std::make_unique<win::WinUiApplication>();
-}
-} // namespace cru::platform::gui
-
-namespace cru::platform::gui::win {
-WinUiApplication* WinUiApplication::instance = nullptr;
-
-WinUiApplication::WinUiApplication() {
- instance = this;
-
- instance_handle_ = ::GetModuleHandleW(nullptr);
- if (!instance_handle_)
- throw Win32Error(u"Failed to get module(instance) handle.");
-
- ::SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
-
- graph_factory_ = std::make_unique<
- cru::platform::graphics::win::direct::DirectGraphicsFactory>();
-
- god_window_ = std::make_unique<GodWindow>(this);
- timer_manager_ = std::make_unique<TimerManager>(god_window_.get());
- window_manager_ = std::make_unique<WindowManager>(this);
- cursor_manager_ = std::make_unique<WinCursorManager>();
- clipboard_ = std::make_unique<WinClipboard>(this);
-}
-
-WinUiApplication::~WinUiApplication() { instance = nullptr; }
-
-int WinUiApplication::Run() {
- MSG msg;
- while (GetMessageW(&msg, nullptr, 0, 0)) {
- TranslateMessage(&msg);
- DispatchMessageW(&msg);
- }
-
- for (const auto& handler : quit_handlers_) handler();
-
- return static_cast<int>(msg.wParam);
-}
-
-void WinUiApplication::RequestQuit(const int quit_code) {
- ::PostQuitMessage(quit_code);
-}
-
-void WinUiApplication::AddOnQuitHandler(std::function<void()> handler) {
- quit_handlers_.push_back(std::move(handler));
-}
-
-long long WinUiApplication::SetImmediate(std::function<void()> action) {
- return this->timer_manager_->SetTimer(TimerType::Immediate, 0,
- std::move(action));
-}
-
-long long WinUiApplication::SetTimeout(std::chrono::milliseconds milliseconds,
- std::function<void()> action) {
- return this->timer_manager_->SetTimer(TimerType::Timeout,
- gsl::narrow<int>(milliseconds.count()),
- std::move(action));
-}
-
-long long WinUiApplication::SetInterval(std::chrono::milliseconds milliseconds,
- std::function<void()> action) {
- return this->timer_manager_->SetTimer(TimerType::Interval,
- gsl::narrow<int>(milliseconds.count()),
- std::move(action));
-}
-
-void WinUiApplication::CancelTimer(long long id) {
- timer_manager_->CancelTimer(id);
-}
-
-std::vector<INativeWindow*> WinUiApplication::GetAllWindow() {
- const auto&& windows = window_manager_->GetAllWindows();
- std::vector<INativeWindow*> result;
- for (const auto w : windows) {
- result.push_back(static_cast<INativeWindow*>(w));
- }
- return result;
-}
-
-INativeWindow* WinUiApplication::CreateWindow() {
- return new WinNativeWindow(this);
-}
-
-cru::platform::graphics::IGraphicsFactory*
-WinUiApplication::GetGraphicsFactory() {
- return graph_factory_.get();
-}
-
-ICursorManager* WinUiApplication::GetCursorManager() {
- return cursor_manager_.get();
-}
-
-IClipboard* WinUiApplication::GetClipboard() { return clipboard_.get(); }
-
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/Window.cpp b/src/win/gui/Window.cpp
deleted file mode 100644
index cc2038ec..00000000
--- a/src/win/gui/Window.cpp
+++ /dev/null
@@ -1,593 +0,0 @@
-#include "cru/win/gui/Window.h"
-
-#include "WindowManager.h"
-#include "cru/common/log/Logger.h"
-#include "cru/platform/Check.h"
-#include "cru/platform/graphics/NullPainter.h"
-#include "cru/platform/gui/Base.h"
-#include "cru/platform/gui/DebugFlags.h"
-#include "cru/platform/gui/Window.h"
-#include "cru/win/graphics/direct/WindowPainter.h"
-#include "cru/win/gui/Cursor.h"
-#include "cru/win/gui/Exception.h"
-#include "cru/win/gui/InputMethod.h"
-#include "cru/win/gui/Keyboard.h"
-#include "cru/win/gui/UiApplication.h"
-#include "cru/win/gui/WindowClass.h"
-
-#include <windowsx.h>
-#include <winuser.h>
-#include <memory>
-
-namespace cru::platform::gui::win {
-namespace {
-inline int DipToPixel(const float dip, const float dpi) {
- return static_cast<int>(dip * dpi / 96.0f);
-}
-
-inline float PixelToDip(const int pixel, const float dpi) {
- return static_cast<float>(pixel) * 96.0f / dpi;
-}
-
-DWORD CalcWindowStyle(WindowStyleFlag flag) {
- return flag & WindowStyleFlags::NoCaptionAndBorder ? WS_POPUP
- : WS_OVERLAPPEDWINDOW;
-}
-
-Rect CalcWindowRectFromClient(const Rect& rect, WindowStyleFlag style_flag,
- float dpi) {
- RECT r;
- r.left = DipToPixel(rect.left, dpi);
- r.top = DipToPixel(rect.top, dpi);
- r.right = DipToPixel(rect.GetRight(), dpi);
- r.bottom = DipToPixel(rect.GetBottom(), dpi);
- if (!AdjustWindowRectEx(&r, CalcWindowStyle(style_flag), FALSE, 0))
- throw Win32Error(::GetLastError(), u"Failed to invoke AdjustWindowRectEx.");
-
- Rect result =
- Rect::FromVertices(PixelToDip(r.left, dpi), PixelToDip(r.top, dpi),
- PixelToDip(r.right, dpi), PixelToDip(r.bottom, dpi));
- return result;
-}
-
-Rect CalcClientRectFromWindow(const Rect& rect, WindowStyleFlag style_flag,
- float dpi) {
- RECT o{100, 100, 500, 500};
- RECT s = o;
- if (!AdjustWindowRectEx(&s, CalcWindowStyle(style_flag), FALSE, 0))
- throw Win32Error(::GetLastError(), u"Failed to invoke AdjustWindowRectEx.");
-
- Rect result = rect;
- result.Shrink(Thickness(PixelToDip(s.left - o.left, dpi),
- PixelToDip(o.top - s.top, dpi),
- PixelToDip(s.right - o.right, dpi),
- PixelToDip(s.bottom - o.bottom, dpi)));
-
- return result;
-}
-} // namespace
-
-WinNativeWindow::WinNativeWindow(WinUiApplication* application)
- : application_(application) {
- Expects(application); // application can't be null.
-}
-
-WinNativeWindow::~WinNativeWindow() { Close(); }
-
-void WinNativeWindow::Close() {
- if (hwnd_) ::DestroyWindow(hwnd_);
-}
-
-void WinNativeWindow::SetParent(INativeWindow* parent) {
- auto p = CheckPlatform<WinNativeWindow>(parent, GetPlatformId());
- parent_window_ = p;
-
- if (hwnd_) {
- ::SetParent(hwnd_, parent_window_->hwnd_);
- }
-}
-
-String WinNativeWindow::GetTitle() { return title_; }
-
-void WinNativeWindow::SetTitle(String title) {
- title_ = title;
-
- if (hwnd_) {
- ::SetWindowTextW(hwnd_, title_.WinCStr());
- }
-}
-
-void WinNativeWindow::SetStyleFlag(WindowStyleFlag flag) {
- if (flag == style_flag_) return;
-
- style_flag_ = flag;
- if (hwnd_) {
- SetWindowLongPtrW(hwnd_, GWL_STYLE,
- static_cast<LONG_PTR>(CalcWindowStyle(style_flag_)));
- }
-}
-
-void WinNativeWindow::SetVisibility(WindowVisibilityType visibility) {
- if (visibility == visibility_) return;
- visibility_ = visibility;
-
- if (!hwnd_) {
- RecreateWindow();
- }
-
- if (visibility == WindowVisibilityType::Show) {
- ShowWindow(hwnd_, SW_SHOWNORMAL);
- } else if (visibility == WindowVisibilityType::Hide) {
- ShowWindow(hwnd_, SW_HIDE);
- } else if (visibility == WindowVisibilityType::Minimize) {
- ShowWindow(hwnd_, SW_MINIMIZE);
- }
-}
-
-Size WinNativeWindow::GetClientSize() { return GetClientRect().GetSize(); }
-
-void WinNativeWindow::SetClientSize(const Size& size) {
- client_rect_.SetSize(size);
-
- if (hwnd_) {
- RECT rect =
- DipToPixel(CalcWindowRectFromClient(client_rect_, style_flag_, dpi_));
-
- if (!SetWindowPos(hwnd_, nullptr, 0, 0, rect.right - rect.left,
- rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE))
- throw Win32Error(::GetLastError(), u"Failed to invoke SetWindowPos.");
- }
-}
-
-Rect WinNativeWindow::GetClientRect() { return client_rect_; }
-
-void WinNativeWindow::SetClientRect(const Rect& rect) {
- client_rect_ = rect;
-
- if (hwnd_) {
- RECT r =
- DipToPixel(CalcWindowRectFromClient(client_rect_, style_flag_, dpi_));
-
- if (!SetWindowPos(hwnd_, nullptr, 0, 0, r.right - r.left, r.bottom - r.top,
- SWP_NOZORDER | SWP_NOMOVE))
- throw Win32Error(::GetLastError(), u"Failed to invoke SetWindowPos.");
- }
-}
-
-Rect WinNativeWindow::GetWindowRect() {
- if (hwnd_) {
- RECT rect;
- if (!::GetWindowRect(hwnd_, &rect))
- throw Win32Error(::GetLastError(), u"Failed to invoke GetWindowRect.");
-
- return Rect::FromVertices(PixelToDip(rect.left), PixelToDip(rect.top),
- PixelToDip(rect.right), PixelToDip(rect.bottom));
- } else {
- return CalcWindowRectFromClient(client_rect_, style_flag_, dpi_);
- }
-}
-
-void WinNativeWindow::SetWindowRect(const Rect& rect) {
- client_rect_ = CalcClientRectFromWindow(rect, style_flag_, dpi_);
-
- if (hwnd_) {
- if (!SetWindowPos(hwnd_, nullptr, DipToPixel(rect.left),
- DipToPixel(rect.top), DipToPixel(rect.GetRight()),
- DipToPixel(rect.GetBottom()), SWP_NOZORDER))
- throw Win32Error(::GetLastError(), u"Failed to invoke SetWindowPos.");
- }
-}
-
-bool WinNativeWindow::RequestFocus() {
- if (hwnd_) {
- SetFocus(hwnd_);
- return true;
- }
- return false;
-}
-
-Point WinNativeWindow::GetMousePosition() {
- POINT p;
- if (!::GetCursorPos(&p))
- throw Win32Error(::GetLastError(), u"Failed to get cursor position.");
- if (!::ScreenToClient(hwnd_, &p))
- throw Win32Error(::GetLastError(), u"Failed to call ScreenToClient.");
- return PixelToDip(p);
-}
-
-bool WinNativeWindow::CaptureMouse() {
- ::SetCapture(hwnd_);
- return true;
-}
-
-bool WinNativeWindow::ReleaseMouse() {
- const auto result = ::ReleaseCapture();
- return result != 0;
-}
-
-void WinNativeWindow::RequestRepaint() {
- if constexpr (DebugFlags::paint) {
- CRU_LOG_DEBUG(u"A repaint is requested.");
- }
- if (!::InvalidateRect(hwnd_, nullptr, FALSE))
- throw Win32Error(::GetLastError(), u"Failed to invalidate window.");
- if (!::UpdateWindow(hwnd_))
- throw Win32Error(::GetLastError(), u"Failed to update window.");
-}
-
-std::unique_ptr<graphics::IPainter> WinNativeWindow::BeginPaint() {
- if (hwnd_)
- return std::make_unique<graphics::win::direct::D2DWindowPainter>(
- window_render_target_.get());
- else
- return std::make_unique<graphics::NullPainter>();
-}
-
-void WinNativeWindow::SetCursor(std::shared_ptr<ICursor> cursor) {
- if (cursor == nullptr) {
- throw std::runtime_error("Can't use a nullptr as cursor.");
- }
-
- cursor_ = CheckPlatform<WinCursor>(cursor, GetPlatformId());
-
- if (hwnd_) return;
-
- if (!::SetClassLongPtrW(hwnd_, GCLP_HCURSOR,
- reinterpret_cast<LONG_PTR>(cursor_->GetHandle()))) {
- CRU_LOG_WARN(
- u"Failed to set cursor because failed to set class long. Last "
- u"error code: {}.",
- ::GetLastError());
- return;
- }
-
- if (GetVisibility() != WindowVisibilityType::Show) return;
-
- auto lg = [](StringView reason) {
- CRU_LOG_WARN(
-
- u"Failed to set cursor because {} when window is visible. (We need to "
- u"update cursor if it is inside the window.) Last error code: {}.",
- reason, ::GetLastError());
- };
-
- ::POINT point;
- if (!::GetCursorPos(&point)) {
- lg(u"failed to get cursor pos");
- return;
- }
-
- ::RECT rect;
- if (!::GetClientRect(hwnd_, &rect)) {
- lg(u"failed to get window's client rect");
- return;
- }
-
- ::POINT lefttop{rect.left, rect.top};
- ::POINT rightbottom{rect.right, rect.bottom};
- if (!::ClientToScreen(hwnd_, &lefttop)) {
- lg(u"failed to call ClientToScreen on lefttop");
- return;
- }
-
- if (!::ClientToScreen(hwnd_, &rightbottom)) {
- lg(u"failed to call ClientToScreen on rightbottom");
- return;
- }
-
- if (point.x >= lefttop.x && point.y >= lefttop.y &&
- point.x <= rightbottom.x && point.y <= rightbottom.y) {
- ::SetCursor(cursor_->GetHandle());
- }
-}
-
-void WinNativeWindow::SetToForeground() {
- if (hwnd_) {
- if (!::SetForegroundWindow(hwnd_))
- throw Win32Error(::GetLastError(),
- u"Failed to set window to foreground.");
- }
-}
-
-IInputMethodContext* WinNativeWindow::GetInputMethodContext() {
- return static_cast<IInputMethodContext*>(input_method_context_.get());
-}
-
-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::gui::mouse_buttons::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::gui::mouse_buttons::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::gui::mouse_buttons::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::gui::mouse_buttons::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::gui::mouse_buttons::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::gui::mouse_buttons::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_SYSKEYDOWN:
- if (l_param & (1 << 29)) {
- OnKeyDownInternal(static_cast<int>(w_param));
- *result = 0;
- return true;
- }
- return false;
- case WM_SYSKEYUP:
- if (l_param & (1 << 29)) {
- OnKeyUpInternal(static_cast<int>(w_param));
- *result = 0;
- return true;
- }
- return false;
- case WM_CREATE:
- OnCreateInternal();
- *result = 0;
- return true;
- case WM_MOVE:
- OnMoveInternal(LOWORD(l_param), HIWORD(l_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;
- case WM_IME_SETCONTEXT:
- l_param &= ~ISC_SHOWUICOMPOSITIONWINDOW;
- *result = ::DefWindowProcW(hwnd, msg, w_param, l_param);
- return true;
- // We must block these message from DefWindowProc or it will create
- // an ugly composition window.
- case WM_IME_STARTCOMPOSITION:
- case WM_IME_COMPOSITION:
- *result = 0;
- return true;
- case WM_DPICHANGED: {
- dpi_ = static_cast<float>(LOWORD(w_param));
- const RECT* suggest_rect = reinterpret_cast<const RECT*>(l_param);
- window_render_target_->SetDpi(dpi_, dpi_);
- SetWindowPos(hwnd_, NULL, suggest_rect->left, suggest_rect->top,
- suggest_rect->right - suggest_rect->left,
- suggest_rect->bottom - suggest_rect->top,
- SWP_NOZORDER | SWP_NOACTIVATE);
- }
- default:
- return false;
- }
-}
-
-RECT WinNativeWindow::GetClientRectPixel() {
- RECT rect;
- if (!::GetClientRect(hwnd_, &rect))
- throw Win32Error(::GetLastError(), u"Failed to invoke GetClientRect.");
- return rect;
-}
-
-void WinNativeWindow::RecreateWindow() {
- const auto window_manager = application_->GetWindowManager();
- auto window_class = window_manager->GetGeneralWindowClass();
-
- hwnd_ = CreateWindowExW(
- 0, window_class->GetName(), L"", CalcWindowStyle(style_flag_),
- CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
- parent_window_ == nullptr ? nullptr : parent_window_->GetWindowHandle(),
- nullptr, application_->GetInstanceHandle(), nullptr);
-
- if (hwnd_ == nullptr)
- throw Win32Error(::GetLastError(), u"Failed to create window.");
-
- auto dpi = ::GetDpiForWindow(hwnd_);
- if (dpi == 0)
- throw Win32Error(::GetLastError(), u"Failed to get dpi of window.");
- dpi_ = static_cast<float>(dpi);
- CRU_LOG_DEBUG(u"Dpi of window is {}.", dpi_);
-
- window_manager->RegisterWindow(hwnd_, this);
-
- SetCursor(application_->GetCursorManager()->GetSystemCursor(
- cru::platform::gui::SystemCursorType::Arrow));
-
- ::SetWindowTextW(hwnd_, title_.WinCStr());
-
- window_render_target_ =
- std::make_unique<graphics::win::direct::D2DWindowRenderTarget>(
- application_->GetDirectFactory(), hwnd_);
- window_render_target_->SetDpi(dpi_, dpi_);
-
- input_method_context_ = std::make_unique<WinInputMethodContext>(this);
- input_method_context_->DisableIME();
-}
-
-void WinNativeWindow::OnCreateInternal() { create_event_.Raise(nullptr); }
-
-void WinNativeWindow::OnDestroyInternal() {
- destroy_event_.Raise(nullptr);
- application_->GetWindowManager()->UnregisterWindow(hwnd_);
- hwnd_ = nullptr;
-}
-
-void WinNativeWindow::OnPaintInternal() {
- paint_event_.Raise(nullptr);
- ValidateRect(hwnd_, nullptr);
- if constexpr (DebugFlags::paint) {
- CRU_LOG_DEBUG(u"A repaint is finished.");
- }
-}
-
-void WinNativeWindow::OnMoveInternal(const int new_left, const int new_top) {
- client_rect_.left = PixelToDip(new_left);
- client_rect_.top = PixelToDip(new_top);
-}
-
-void WinNativeWindow::OnResizeInternal(const int new_width,
- const int new_height) {
- client_rect_.width = PixelToDip(new_width);
- client_rect_.height = PixelToDip(new_height);
- if (!(new_width == 0 && new_height == 0)) {
- window_render_target_->ResizeBuffer(new_width, new_height);
- resize_event_.Raise(Size{PixelToDip(new_width), PixelToDip(new_height)});
- }
-}
-
-void WinNativeWindow::OnSetFocusInternal() {
- has_focus_ = true;
- focus_event_.Raise(FocusChangeType::Gain);
-}
-
-void WinNativeWindow::OnKillFocusInternal() {
- has_focus_ = false;
- focus_event_.Raise(FocusChangeType::Lose);
-}
-
-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(MouseEnterLeaveType::Enter);
- }
-
- mouse_move_event_.Raise(PixelToDip(point));
-}
-
-void WinNativeWindow::OnMouseLeaveInternal() {
- is_mouse_in_ = false;
- mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Leave);
-}
-
-void WinNativeWindow::OnMouseDownInternal(platform::gui::MouseButton button,
- POINT point) {
- const auto dip_point = PixelToDip(point);
- mouse_down_event_.Raise({button, dip_point, RetrieveKeyMofifier()});
-}
-
-void WinNativeWindow::OnMouseUpInternal(platform::gui::MouseButton button,
- POINT point) {
- const auto dip_point = PixelToDip(point);
- mouse_up_event_.Raise({button, dip_point, RetrieveKeyMofifier()});
-}
-
-void WinNativeWindow::OnMouseWheelInternal(short delta, POINT point) {
- const auto dip_point = PixelToDip(point);
- const float d = -((float)delta / 120.f);
- mouse_wheel_event_.Raise({d, dip_point, RetrieveKeyMofifier()});
-}
-
-void WinNativeWindow::OnKeyDownInternal(int virtual_code) {
- key_down_event_.Raise(
- {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()});
-}
-
-void WinNativeWindow::OnKeyUpInternal(int virtual_code) {
- key_up_event_.Raise(
- {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()});
-}
-
-void WinNativeWindow::OnActivatedInternal() {}
-
-void WinNativeWindow::OnDeactivatedInternal() {}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/WindowClass.cpp b/src/win/gui/WindowClass.cpp
deleted file mode 100644
index 25229406..00000000
--- a/src/win/gui/WindowClass.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include "cru/win/gui/WindowClass.h"
-
-#include "cru/win/gui/Exception.h"
-
-namespace cru::platform::gui::win {
-WindowClass::WindowClass(std::wstring name, WNDPROC window_proc,
- HINSTANCE h_instance)
- : name_(std::move(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(), u"Failed to create window class.");
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/WindowManager.cpp b/src/win/gui/WindowManager.cpp
deleted file mode 100644
index 1e0f797a..00000000
--- a/src/win/gui/WindowManager.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-#include "WindowManager.h"
-
-#include "cru/win/gui/UiApplication.h"
-#include "cru/win/gui/Window.h"
-#include "cru/win/gui/WindowClass.h"
-
-namespace cru::platform::gui::win {
-LRESULT __stdcall GeneralWndProc(HWND hWnd, UINT Msg, WPARAM wParam,
- LPARAM lParam) {
- auto window =
- WinUiApplication::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(WinUiApplication* application) {
- application_ = application;
- general_window_class_ = std::make_unique<WindowClass>(
- L"CruUIWindowClass", GeneralWndProc, application->GetInstanceHandle());
-}
-
-WindowManager::~WindowManager() {
- for (const auto& [key, window] : window_map_) delete window;
-}
-
-void WindowManager::RegisterWindow(HWND hwnd, WinNativeWindow* window) {
- Expects(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);
- Expects(find_result != window_map_.end()); // The hwnd is not in the map.
- window_map_.erase(find_result);
- if (window_map_.empty() && application_->IsQuitOnAllWindowClosed())
- application_->RequestQuit(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 (const auto& [key, value] : window_map_) windows.push_back(value);
- return windows;
-}
-} // namespace cru::platform::gui::win
diff --git a/src/win/gui/WindowManager.h b/src/win/gui/WindowManager.h
deleted file mode 100644
index dba3f0a6..00000000
--- a/src/win/gui/WindowManager.h
+++ /dev/null
@@ -1,51 +0,0 @@
-#pragma once
-#include "cru/win/WinPreConfig.h"
-
-#include "cru/common/Base.h"
-
-#include <map>
-#include <memory>
-#include <vector>
-
-namespace cru::platform::gui::win {
-class WinUiApplication;
-class WinNativeWindow;
-class WindowClass;
-
-class WindowManager : public Object {
- public:
- WindowManager(WinUiApplication* application);
-
- CRU_DELETE_COPY(WindowManager)
- CRU_DELETE_MOVE(WindowManager)
-
- ~WindowManager() override;
-
- // Get the general window class for creating ordinary window.
- WindowClass* GetGeneralWindowClass() const {
- return general_window_class_.get();
- }
-
- // 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:
- WinUiApplication* application_;
-
- std::unique_ptr<WindowClass> general_window_class_;
- std::map<HWND, WinNativeWindow*> window_map_;
-};
-} // namespace cru::platform::gui::win