aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/common/Logger.cpp34
-rw-r--r--src/common/StringUtil.cpp179
-rw-r--r--src/ui/ClickDetector.cpp14
-rw-r--r--src/ui/RoutedEventDispatch.hpp21
-rw-r--r--src/ui/UiHost.cpp17
-rw-r--r--src/ui/UiManager.cpp2
-rw-r--r--src/ui/Window.cpp2
-rw-r--r--src/ui/controls/TextBlock.cpp4
-rw-r--r--src/ui/controls/TextControlService.hpp15
-rw-r--r--src/ui/render/BorderRenderObject.cpp10
-rw-r--r--src/ui/render/FlexLayoutRenderObject.cpp8
-rw-r--r--src/ui/render/LayoutHelper.cpp4
-rw-r--r--src/ui/render/RenderObject.cpp8
-rw-r--r--src/ui/render/ScrollRenderObject.cpp1
-rw-r--r--src/ui/render/StackLayoutRenderObject.cpp8
-rw-r--r--src/ui/render/TextRenderObject.cpp10
-rw-r--r--src/win/CMakeLists.txt2
-rw-r--r--src/win/DebugLogger.hpp6
-rw-r--r--src/win/Exception.cpp12
-rw-r--r--src/win/String.cpp129
-rw-r--r--src/win/graph/direct/Factory.cpp10
-rw-r--r--src/win/graph/direct/Font.cpp12
-rw-r--r--src/win/graph/direct/TextLayout.cpp51
-rw-r--r--src/win/native/Cursor.cpp2
-rw-r--r--src/win/native/GodWindow.cpp2
-rw-r--r--src/win/native/InputMethod.cpp72
-rw-r--r--src/win/native/Window.cpp23
27 files changed, 298 insertions, 360 deletions
diff --git a/src/common/Logger.cpp b/src/common/Logger.cpp
index da55047a..dfa25347 100644
--- a/src/common/Logger.cpp
+++ b/src/common/Logger.cpp
@@ -10,7 +10,6 @@ namespace cru::log {
namespace {
Logger *CreateLogger() {
const auto logger = new Logger();
- logger->AddSource(std::make_unique<StdioLogSource>());
return logger;
}
} // namespace
@@ -31,39 +30,43 @@ void Logger::RemoveSource(ILogSource *source) {
}
namespace {
-std::string_view LogLevelToString(LogLevel level) {
+std::u16string_view LogLevelToString(LogLevel level) {
switch (level) {
case LogLevel::Debug:
- return "DEBUG";
+ return u"DEBUG";
case LogLevel::Info:
- return "INFO";
+ return u"INFO";
case LogLevel::Warn:
- return "WARN";
+ return u"WARN";
case LogLevel::Error:
- return "ERROR";
+ return u"ERROR";
default:
std::terminate();
}
}
+
+std::u16string GetLogTime() {
+ auto time = std::time(nullptr);
+ auto calendar = std::localtime(&time);
+ return fmt::format(u"{}:{}:{}", calendar->tm_hour, calendar->tm_min,
+ calendar->tm_sec);
+}
} // namespace
-void Logger::Log(LogLevel level, std::string_view s) {
+void Logger::Log(LogLevel level, std::u16string_view s) {
#ifndef CRU_DEBUG
if (level == LogLevel::Debug) {
return;
}
#endif
for (const auto &source : sources_) {
- auto now = std::time(nullptr);
- std::array<char, 50> buffer;
- std::strftime(buffer.data(), 50, "%c", std::localtime(&now));
-
- source->Write(level, fmt::format("[{}] {}: {}\n", buffer.data(),
+ source->Write(level, fmt::format(u"[{}] {}: {}\n", GetLogTime(),
LogLevelToString(level), s));
}
}
-void Logger::Log(LogLevel level, std::string_view tag, std::string_view s) {
+void Logger::Log(LogLevel level, std::u16string_view tag,
+ std::u16string_view s) {
#ifndef CRU_DEBUG
if (level == LogLevel::Debug) {
return;
@@ -71,10 +74,7 @@ void Logger::Log(LogLevel level, std::string_view tag, std::string_view s) {
#endif
for (const auto &source : sources_) {
auto now = std::time(nullptr);
- std::array<char, 50> buffer;
- std::strftime(buffer.data(), 50, "%c", std::localtime(&now));
-
- source->Write(level, fmt::format("[{}] {} {}: {}\n", buffer.data(),
+ source->Write(level, fmt::format(u"[{}] {} {}: {}\n", GetLogTime(),
LogLevelToString(level), tag, s));
}
}
diff --git a/src/common/StringUtil.cpp b/src/common/StringUtil.cpp
index 31a5effd..0b6332ce 100644
--- a/src/common/StringUtil.cpp
+++ b/src/common/StringUtil.cpp
@@ -1,5 +1,7 @@
#include "cru/common/StringUtil.hpp"
+#include <codecvt>
+
namespace cru {
template <typename UInt, int number_of_bit>
inline std::enable_if_t<std::is_unsigned_v<UInt>, CodePoint> ExtractBits(
@@ -7,63 +9,154 @@ inline std::enable_if_t<std::is_unsigned_v<UInt>, CodePoint> ExtractBits(
return static_cast<CodePoint>(n & ((1u << number_of_bit) - 1));
}
-CodePoint Utf8Iterator::Next() {
- if (position_ == static_cast<Index>(string_.length()))
- return k_code_point_end;
+CodePoint Utf16Iterator::Previous() {
+ if (position_ <= 0) return k_invalid_code_point;
- const auto cu0 = static_cast<std::uint8_t>(string_[position_++]);
+ const auto cu0 = static_cast<std::uint16_t>(string_[--position_]);
- auto read_next_folowing_code = [this]() -> CodePoint {
- if (this->position_ == static_cast<Index>(string_.length()))
+ if (cu0 < 0xd800u || cu0 >= 0xe000u) { // 1-length code point
+ return static_cast<CodePoint>(cu0);
+ } else if (cu0 < 0xdc00u || cu0 > 0xdfffu) { // 2-length code point
+ if (position_ <= 0) {
throw TextEncodeException(
- "Unexpected end when read continuing byte of multi-byte code point.");
+ "Unexpected end when reading first code unit of surrogate pair "
+ "during backward.");
+ }
+ const auto cu1 = static_cast<std::uint16_t>(string_[--position_]);
#ifdef CRU_DEBUG
- const auto u = static_cast<std::uint8_t>(string_[position_]);
- if (!(u & (1u << 7)) || (u & (1u << 6))) {
+ if (cu1 <= 0xdbffu) {
throw TextEncodeException(
- "Unexpected bad-format (not 0b10xxxxxx) continuing byte of "
- "multi-byte code point.");
+ "Unexpected bad-range first code unit of surrogate pair during "
+ "backward.");
}
#endif
- return ExtractBits<std::uint8_t, 6>(string_[position_++]);
- };
+ const auto s0 = ExtractBits<std::uint16_t, 10>(cu1) << 10;
+ const auto s1 = ExtractBits<std::uint16_t, 10>(cu0);
- if ((1u << 7) & cu0) {
- if ((1u << 6) & cu0) { // 2~4-length code point
- if ((1u << 5) & cu0) { // 3~4-length code point
- if ((1u << 4) & cu0) { // 4-length code point
-#ifdef CRU_DEBUG
- if (cu0 & (1u << 3)) {
- throw TextEncodeException(
- "Unexpected bad-format begin byte (not 0b10xxxxxx) of 4-byte "
- "code point.");
- }
-#endif
+ return s0 + s1 + 0x10000;
+
+ } else {
+ throw TextEncodeException(
+ "Unexpected bad-range second code unit of surrogate pair during "
+ "backward.");
+ }
+}
- const CodePoint s0 = ExtractBits<std::uint8_t, 3>(cu0) << (6 * 3);
- const CodePoint s1 = read_next_folowing_code() << (6 * 2);
- const CodePoint s2 = read_next_folowing_code() << 6;
- const CodePoint s3 = read_next_folowing_code();
- return s0 + s1 + s2 + s3;
- } else { // 3-length code point
- const CodePoint s0 = ExtractBits<std::uint8_t, 4>(cu0) << (6 * 2);
- const CodePoint s1 = read_next_folowing_code() << 6;
- const CodePoint s2 = read_next_folowing_code();
- return s0 + s1 + s2;
- }
- } else { // 2-length code point
- const CodePoint s0 = ExtractBits<std::uint8_t, 5>(cu0) << 6;
- const CodePoint s1 = read_next_folowing_code();
- return s0 + s1;
- }
- } else {
+CodePoint Utf16Iterator::Next() {
+ if (position_ >= static_cast<Index>(string_.length()))
+ return k_invalid_code_point;
+
+ const auto cu0 = static_cast<std::uint16_t>(string_[position_++]);
+
+ if (cu0 < 0xd800u || cu0 >= 0xe000u) { // 1-length code point
+ return static_cast<CodePoint>(cu0);
+ } else if (cu0 <= 0xdbffu) { // 2-length code point
+ if (position_ >= static_cast<Index>(string_.length())) {
throw TextEncodeException(
- "Unexpected bad-format (0b10xxxxxx) begin byte of a code point.");
+ "Unexpected end when reading second code unit of surrogate pair "
+ "during forward.");
}
+ const auto cu1 = static_cast<std::uint16_t>(string_[position_++]);
+
+#ifdef CRU_DEBUG
+ if (cu1 < 0xdc00u || cu1 > 0xdfffu) {
+ throw TextEncodeException(
+ "Unexpected bad-format second code unit of surrogate pair during "
+ "forward.");
+ }
+#endif
+
+ const auto s0 = ExtractBits<std::uint16_t, 10>(cu0) << 10;
+ const auto s1 = ExtractBits<std::uint16_t, 10>(cu1);
+
+ return s0 + s1 + 0x10000;
+
} else {
- return static_cast<CodePoint>(cu0);
+ throw TextEncodeException(
+ "Unexpected bad-format first code unit of surrogate pair during "
+ "forward.");
}
}
+
+Index PreviousIndex(std::u16string_view string, Index current) {
+ Utf16Iterator iterator{string, current};
+ iterator.Previous();
+ return iterator.CurrentPosition();
+}
+
+Index NextIndex(std::u16string_view string, Index current) {
+ Utf16Iterator iterator{string, current};
+ iterator.Next();
+ return iterator.CurrentPosition();
+}
+
+std::string ToUtf8(const std::u16string& s) {
+ // TODO: Implement this by myself.
+ return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}
+ .to_bytes(s);
+}
+
+// CodePoint Utf8Iterator::Next() {
+// if (position_ == static_cast<Index>(string_.length()))
+// return k_invalid_code_point;
+
+// const auto cu0 = static_cast<std::uint8_t>(string_[position_++]);
+
+// auto read_next_folowing_code = [this]() -> CodePoint {
+// if (this->position_ == static_cast<Index>(string_.length()))
+// throw TextEncodeException(
+// "Unexpected end when read continuing byte of multi-byte code
+// point.");
+
+// #ifdef CRU_DEBUG
+// const auto u = static_cast<std::uint8_t>(string_[position_]);
+// if (!(u & (1u << 7)) || (u & (1u << 6))) {
+// throw TextEncodeException(
+// "Unexpected bad-format (not 0b10xxxxxx) continuing byte of "
+// "multi-byte code point.");
+// }
+// #endif
+
+// return ExtractBits<std::uint8_t, 6>(string_[position_++]);
+// };
+
+// if ((1u << 7) & cu0) {
+// if ((1u << 6) & cu0) { // 2~4-length code point
+// if ((1u << 5) & cu0) { // 3~4-length code point
+// if ((1u << 4) & cu0) { // 4-length code point
+// #ifdef CRU_DEBUG
+// if (cu0 & (1u << 3)) {
+// throw TextEncodeException(
+// "Unexpected bad-format begin byte (not 0b10xxxxxx) of 4-byte
+// " "code point.");
+// }
+// #endif
+
+// const CodePoint s0 = ExtractBits<std::uint8_t, 3>(cu0) << (6 * 3);
+// const CodePoint s1 = read_next_folowing_code() << (6 * 2);
+// const CodePoint s2 = read_next_folowing_code() << 6;
+// const CodePoint s3 = read_next_folowing_code();
+// return s0 + s1 + s2 + s3;
+// } else { // 3-length code point
+// const CodePoint s0 = ExtractBits<std::uint8_t, 4>(cu0) << (6 * 2);
+// const CodePoint s1 = read_next_folowing_code() << 6;
+// const CodePoint s2 = read_next_folowing_code();
+// return s0 + s1 + s2;
+// }
+// } else { // 2-length code point
+// const CodePoint s0 = ExtractBits<std::uint8_t, 5>(cu0) << 6;
+// const CodePoint s1 = read_next_folowing_code();
+// return s0 + s1;
+// }
+// } else {
+// throw TextEncodeException(
+// "Unexpected bad-format (0b10xxxxxx) begin byte of a code point.");
+// }
+// } else {
+// return static_cast<CodePoint>(cu0);
+// }
+// }
+
} // namespace cru
diff --git a/src/ui/ClickDetector.cpp b/src/ui/ClickDetector.cpp
index 93e6f303..09f208cd 100644
--- a/src/ui/ClickDetector.cpp
+++ b/src/ui/ClickDetector.cpp
@@ -45,7 +45,7 @@ ClickDetector::ClickDetector(Control* control) {
this->state_ == ClickState::Hover) {
if (!this->control_->CaptureMouse()) {
log::TagDebug(log_tag,
- "Failed to capture mouse when begin click.");
+ u"Failed to capture mouse when begin click.");
return;
}
this->down_point_ = args.GetPoint();
@@ -107,21 +107,21 @@ void ClickDetector::SetTriggerButton(MouseButton trigger_button) {
void ClickDetector::SetState(ClickState state) {
#ifdef CRU_DEBUG
- auto to_string = [](ClickState state) -> std::string_view {
+ auto to_string = [](ClickState state) -> std::u16string_view {
switch (state) {
case ClickState::None:
- return "None";
+ return u"None";
case ClickState::Hover:
- return "Hover";
+ return u"Hover";
case ClickState::Press:
- return "Press";
+ return u"Press";
case ClickState::PressInactive:
- return "PressInvactive";
+ return u"PressInvactive";
default:
UnreachableCode();
}
};
- log::TagDebug(log_tag, "Click state changed, new state: {}.",
+ log::TagDebug(log_tag, u"Click state changed, new state: {}.",
to_string(state));
#endif
diff --git a/src/ui/RoutedEventDispatch.hpp b/src/ui/RoutedEventDispatch.hpp
index 5ff21a74..9337e9ec 100644
--- a/src/ui/RoutedEventDispatch.hpp
+++ b/src/ui/RoutedEventDispatch.hpp
@@ -20,7 +20,7 @@ namespace cru::ui {
// "original_sender", which is unchanged. And "args" will be perfectly forwarded
// as the rest arguments.
template <typename EventArgs, typename... Args>
-void DispatchEvent(const std::string_view& event_name,
+void DispatchEvent(const std::u16string_view& event_name,
Control* const original_sender,
event::RoutedEvent<EventArgs>* (Control::*event_ptr)(),
Control* const last_receiver, Args&&... args) {
@@ -30,7 +30,7 @@ void DispatchEvent(const std::string_view& event_name,
#ifdef CRU_DEBUG
bool do_log = true;
- if (event_name == "MouseMove") do_log = false;
+ if (event_name == u"MouseMove") do_log = false;
#endif
if (original_sender == last_receiver) {
@@ -56,14 +56,14 @@ void DispatchEvent(const std::string_view& event_name,
#ifdef CRU_DEBUG
if (do_log) {
- std::string log = "Dispatch routed event ";
+ std::u16string log = u"Dispatch routed event ";
log += event_name;
- log += ". Path (parent first): ";
+ log += u". Path (parent first): ";
auto i = receive_list.crbegin();
const auto end = --receive_list.crend();
for (; i != end; ++i) {
log += (*i)->GetControlType();
- log += " -> ";
+ log += u" -> ";
}
log += (*i)->GetControlType();
log::Debug(log);
@@ -89,8 +89,8 @@ void DispatchEvent(const std::string_view& event_name,
#ifdef CRU_DEBUG
if (do_log)
log::Debug(
- "Routed event is short-circuit in TUNNEL at {}-st control (count "
- "from parent).",
+ u"Routed event is short-circuit in TUNNEL at {}-st control (count "
+ u"from parent).",
count);
#endif
break;
@@ -110,9 +110,8 @@ void DispatchEvent(const std::string_view& event_name,
#ifdef CRU_DEBUG
if (do_log)
log::Debug(
- "Routed event is short-circuit in BUBBLE at {}-st control "
- "(count "
- "from parent).",
+ u"Routed event is short-circuit in BUBBLE at {}-st control "
+ u"(count from parent).",
count);
#endif
break;
@@ -128,7 +127,7 @@ void DispatchEvent(const std::string_view& event_name,
}
#ifdef CRU_DEBUG
- if (do_log) log::Debug("Routed event dispatch finished.");
+ if (do_log) log::Debug(u"Routed event dispatch finished.");
#endif
}
} // namespace cru::ui
diff --git a/src/ui/UiHost.cpp b/src/ui/UiHost.cpp
index 975d0ffe..5eee3925 100644
--- a/src/ui/UiHost.cpp
+++ b/src/ui/UiHost.cpp
@@ -14,9 +14,11 @@ using platform::native::IUiApplication;
namespace event_names {
#ifdef CRU_DEBUG
-#define CRU_DEFINE_EVENT_NAME(name) constexpr const char* name = #name;
+// clang-format off
+#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u#name;
+// clang-format on
#else
-#define CRU_DEFINE_EVENT_NAME(name) constexpr const char* name = "";
+#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u"";
#endif
CRU_DEFINE_EVENT_NAME(LoseFocus)
@@ -146,7 +148,7 @@ void UiHost::InvalidatePaint() {
}
void UiHost::InvalidateLayout() {
- log::TagDebug(log_tag, "A relayout is requested.");
+ log::TagDebug(log_tag, u"A relayout is requested.");
if (!need_layout_) {
platform::native::IUiApplication::GetInstance()->InvokeLater(
[resolver = this->CreateResolver()] {
@@ -171,7 +173,7 @@ void UiHost::Relayout() {
render::MeasureSize::NotSpecified());
root_render_object_->Layout(Point{});
after_layout_event_.Raise(AfterLayoutEventArgs{});
- log::TagDebug(log_tag, "A relayout is finished.");
+ log::TagDebug(log_tag, u"A relayout is finished.");
}
bool UiHost::RequestFocusFor(Control* control) {
@@ -368,6 +370,11 @@ void UiHost::UpdateCursor() {
Control* UiHost::HitTest(const Point& point) {
const auto render_object = root_render_object_->HitTest(point);
- return render_object ? render_object->GetAttachedControl() : nullptr;
+ if (render_object) {
+ const auto control = render_object->GetAttachedControl();
+ Ensures(control);
+ return control;
+ }
+ return window_control_;
}
} // namespace cru::ui
diff --git a/src/ui/UiManager.cpp b/src/ui/UiManager.cpp
index b8effdfd..b50a9775 100644
--- a/src/ui/UiManager.cpp
+++ b/src/ui/UiManager.cpp
@@ -30,7 +30,7 @@ UiManager* UiManager::GetInstance() {
UiManager::UiManager() {
const auto factory = GetGraphFactory();
- theme_resource_.default_font = factory->CreateFont("等线", 24.0f);
+ theme_resource_.default_font = factory->CreateFont(u"等线", 24.0f);
const auto black_brush = std::shared_ptr<platform::graph::ISolidColorBrush>(
CreateSolidColorBrush(factory, colors::black));
diff --git a/src/ui/Window.cpp b/src/ui/Window.cpp
index de7044dd..dca95ebb 100644
--- a/src/ui/Window.cpp
+++ b/src/ui/Window.cpp
@@ -17,7 +17,7 @@ Window::~Window() {
managed_ui_host_.reset();
}
-std::string_view Window::GetControlType() const { return control_type; }
+std::u16string_view Window::GetControlType() const { return control_type; }
render::RenderObject* Window::GetRenderObject() const { return render_object_; }
diff --git a/src/ui/controls/TextBlock.cpp b/src/ui/controls/TextBlock.cpp
index 5ec15796..7f7ee38b 100644
--- a/src/ui/controls/TextBlock.cpp
+++ b/src/ui/controls/TextBlock.cpp
@@ -30,11 +30,11 @@ render::RenderObject* TextBlock::GetRenderObject() const {
return text_render_object_.get();
}
-std::string TextBlock::GetText() const {
+std::u16string TextBlock::GetText() const {
return text_render_object_->GetText();
}
-void TextBlock::SetText(std::string text) {
+void TextBlock::SetText(std::u16string text) {
text_render_object_->SetText(std::move(text));
}
diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp
index 94d9ebf8..93a48c44 100644
--- a/src/ui/controls/TextControlService.hpp
+++ b/src/ui/controls/TextControlService.hpp
@@ -19,7 +19,7 @@ constexpr int k_default_caret_blink_duration = 500;
// ```
template <typename TControl>
class TextControlService : public Object {
- CRU_DEFINE_CLASS_LOG_TAG("cru::ui::controls::TextControlService")
+ CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::controls::TextControlService")
public:
TextControlService(gsl::not_null<TControl*> control) : control_(control) {}
@@ -126,22 +126,21 @@ class TextControlService : public Object {
const auto text_render_object = this->GetTextRenderObject();
text_render_object->SetSelectionRange(TextRange{start, 0});
text_render_object->SetCaretPosition(start);
- log::TagDebug(log_tag, "Text selection started, position: {}.", position);
+ log::TagDebug(log_tag, u"Text selection started, position: {}.", start);
}
void UpdateSelection(Index new_end) {
- if (!old_selection.has_value()) return;
-
const auto text_render_object = this->GetTextRenderObject();
const auto old_selection = text_render_object->GetSelectionRange();
+ if (!old_selection.has_value()) return;
const auto old_start = old_selection->GetStart();
this->GetTextRenderObject()->SetSelectionRange(
TextRange::FromTwoSides(old_start, new_end));
text_render_object->SetCaretPosition(new_end);
- log::TagDebug(log_tag, "Text selection updated, range: {}, {}.", old_start,
+ log::TagDebug(log_tag, u"Text selection updated, range: {}, {}.", old_start,
new_end);
if (const auto scroll_render_object = this->GetScrollRenderObject()) {
- //TODO: Implement this.
+ // TODO: Implement this.
}
}
@@ -194,9 +193,9 @@ class TextControlService : public Object {
}
}
- void KeyDownHandler(event::KeyEventArgs& args) {}
+ void KeyDownHandler(event::KeyEventArgs& args) { CRU_UNUSED(args); }
- void KeyUpHandler(event::KeyEventArgs& args) {}
+ void KeyUpHandler(event::KeyEventArgs& args) { CRU_UNUSED(args); }
void LoseFocusHandler(event::FocusChangeEventArgs& args) {
if (!args.IsWindow()) this->AbortSelection();
diff --git a/src/ui/render/BorderRenderObject.cpp b/src/ui/render/BorderRenderObject.cpp
index f2e3eb9b..b7e1e709 100644
--- a/src/ui/render/BorderRenderObject.cpp
+++ b/src/ui/render/BorderRenderObject.cpp
@@ -57,7 +57,7 @@ void BorderRenderObject::OnDrawCore(platform::graph::IPainter* painter) {
background_brush_.get());
if (is_border_enabled_) {
if (border_brush_ == nullptr) {
- log::TagWarn(log_tag, "Border is enabled but border brush is null.");
+ log::TagWarn(log_tag, u"Border is enabled but border brush is null.");
} else {
painter->FillGeometry(geometry_.get(), border_brush_.get());
}
@@ -94,8 +94,8 @@ Size BorderRenderObject::OnMeasureCore(const MeasureRequirement& requirement,
const auto max_width = requirement.max.width.GetLengthOrMax();
if (coerced_space_size.width > max_width) {
log::TagWarn(log_tag,
- "(Measure) Horizontal length of padding, border and margin "
- "is bigger than required max length.");
+ u"(Measure) Horizontal length of padding, border and margin "
+ u"is bigger than required max length.");
coerced_space_size.width = max_width;
}
content_requirement.max.width = max_width - coerced_space_size.width;
@@ -110,8 +110,8 @@ Size BorderRenderObject::OnMeasureCore(const MeasureRequirement& requirement,
const auto max_height = requirement.max.height.GetLengthOrMax();
if (coerced_space_size.height > max_height) {
log::TagWarn(log_tag,
- "(Measure) Vertical length of padding, border and margin is "
- "bigger than required max length.");
+ u"(Measure) Vertical length of padding, border and margin is "
+ u"bigger than required max length.");
coerced_space_size.height = max_height;
}
content_requirement.max.height = max_height - coerced_space_size.height;
diff --git a/src/ui/render/FlexLayoutRenderObject.cpp b/src/ui/render/FlexLayoutRenderObject.cpp
index 8e6b41fe..ade230b5 100644
--- a/src/ui/render/FlexLayoutRenderObject.cpp
+++ b/src/ui/render/FlexLayoutRenderObject.cpp
@@ -88,7 +88,7 @@ Size FlexLayoutMeasureContentImpl(
const MeasureRequirement& requirement, const MeasureSize& preferred_size,
const std::vector<RenderObject*>& children,
const std::vector<FlexChildLayoutData>& layout_data,
- std::string_view log_tag) {
+ std::u16string_view log_tag) {
Expects(children.size() == layout_data.size());
direction_tag_t direction_tag;
@@ -111,8 +111,8 @@ Size FlexLayoutMeasureContentImpl(
StackLayoutCalculateChildMaxLength(
preferred_cross_length, max_cross_length,
GetCross(child->GetMinSize(), direction_tag), log_tag,
- "(Measure) Child's min cross size is bigger than parent's max "
- "cross size."));
+ u"(Measure) Child's min cross size is bigger than parent's max "
+ u"cross size."));
}
// step 1.
@@ -315,7 +315,7 @@ Size FlexLayoutMeasureContentImpl(
total_length > max_main_length.GetLengthOrUndefined()) {
log::TagWarn(
log_tag,
- "(Measure) Children's main axis length exceeds required max length.");
+ u"(Measure) Children's main axis length exceeds required max length.");
total_length = max_main_length.GetLengthOrUndefined();
} else if (min_main_length.IsSpecified() &&
total_length < min_main_length.GetLengthOrUndefined()) {
diff --git a/src/ui/render/LayoutHelper.cpp b/src/ui/render/LayoutHelper.cpp
index 9f94b84d..9ad2d862 100644
--- a/src/ui/render/LayoutHelper.cpp
+++ b/src/ui/render/LayoutHelper.cpp
@@ -19,8 +19,8 @@ float CalculateAnchorByAlignment(Alignment alignment, float start_point,
MeasureLength StackLayoutCalculateChildMaxLength(
MeasureLength parent_preferred_size, MeasureLength parent_max_size,
- MeasureLength child_min_size, std::string_view log_tag,
- std::string_view exceeds_message) {
+ MeasureLength child_min_size, std::u16string_view log_tag,
+ std::u16string_view exceeds_message) {
if (parent_max_size.GetLengthOrMax() < child_min_size.GetLengthOr0()) {
log::TagWarn(log_tag, exceeds_message);
return parent_max_size;
diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp
index 66b62e6e..30433868 100644
--- a/src/ui/render/RenderObject.cpp
+++ b/src/ui/render/RenderObject.cpp
@@ -152,8 +152,8 @@ Size RenderObject::OnMeasureCore(const MeasureRequirement& requirement,
const auto max_width = requirement.max.width.GetLengthOrMax();
if (coerced_space_size.width > max_width) {
log::TagWarn(log_tag,
- "(Measure) Horizontal length of padding and margin is "
- "bigger than required max length.");
+ u"(Measure) Horizontal length of padding and margin is "
+ u"bigger than required max length.");
coerced_space_size.width = max_width;
}
content_requirement.max.width = max_width - coerced_space_size.width;
@@ -168,8 +168,8 @@ Size RenderObject::OnMeasureCore(const MeasureRequirement& requirement,
const auto max_height = requirement.max.height.GetLengthOrMax();
if (coerced_space_size.height > max_height) {
log::TagWarn(log_tag,
- "(Measure) Vertical length of padding and margin is bigger "
- "than required max length.");
+ u"(Measure) Vertical length of padding and margin is bigger "
+ u"than required max length.");
coerced_space_size.height = max_height;
}
content_requirement.max.height = max_height - coerced_space_size.height;
diff --git a/src/ui/render/ScrollRenderObject.cpp b/src/ui/render/ScrollRenderObject.cpp
index 77367970..d3996b98 100644
--- a/src/ui/render/ScrollRenderObject.cpp
+++ b/src/ui/render/ScrollRenderObject.cpp
@@ -69,6 +69,7 @@ void ScrollRenderObject::SetScrollOffset(const Point& offset) {
void ScrollToContain(const Rect& rect) {
// TODO: Implement this.
+ CRU_UNUSED(rect);
throw std::runtime_error("Not implemented.");
}
diff --git a/src/ui/render/StackLayoutRenderObject.cpp b/src/ui/render/StackLayoutRenderObject.cpp
index 168ff379..75ab0ee3 100644
--- a/src/ui/render/StackLayoutRenderObject.cpp
+++ b/src/ui/render/StackLayoutRenderObject.cpp
@@ -15,13 +15,13 @@ Size StackLayoutRenderObject::OnMeasureContent(
MeasureSize{StackLayoutCalculateChildMaxLength(
preferred_size.width, requirement.max.width,
child->GetMinSize().width, log_tag,
- "(Measure) Child's min width is bigger than "
- "parent's max width."),
+ u"(Measure) Child's min width is bigger than "
+ u"parent's max width."),
StackLayoutCalculateChildMaxLength(
preferred_size.height, requirement.max.height,
child->GetMinSize().height, log_tag,
- "(Measure) Child's min height is bigger than "
- "parent's max height.")},
+ u"(Measure) Child's min height is bigger than "
+ u"parent's max height.")},
MeasureSize::NotSpecified()},
MeasureSize::NotSpecified());
const auto size = child->GetSize();
diff --git a/src/ui/render/TextRenderObject.cpp b/src/ui/render/TextRenderObject.cpp
index 87a3c352..8a4a4ba1 100644
--- a/src/ui/render/TextRenderObject.cpp
+++ b/src/ui/render/TextRenderObject.cpp
@@ -28,16 +28,16 @@ TextRenderObject::TextRenderObject(
caret_brush.swap(caret_brush_);
const auto graph_factory = GetGraphFactory();
- text_layout_ = graph_factory->CreateTextLayout(font_, "");
+ text_layout_ = graph_factory->CreateTextLayout(font_, u"");
}
TextRenderObject::~TextRenderObject() = default;
-std::string TextRenderObject::GetText() const {
+std::u16string TextRenderObject::GetText() const {
return text_layout_->GetText();
}
-void TextRenderObject::SetText(std::string new_text) {
+void TextRenderObject::SetText(std::u16string new_text) {
text_layout_->SetText(std::move(new_text));
}
@@ -171,7 +171,7 @@ Size TextRenderObject::OnMeasureContent(const MeasureRequirement& requirement,
if (requirement.max.width.IsSpecified() &&
text_size.width > requirement.max.width.GetLengthOrUndefined()) {
log::TagWarn(log_tag,
- "(Measure) Text actual width exceeds the required max width.");
+ u"(Measure) Text actual width exceeds the required max width.");
result.width = requirement.max.width.GetLengthOrUndefined();
} else {
result.width = std::max(result.width, preferred_size.width.GetLengthOr0());
@@ -182,7 +182,7 @@ Size TextRenderObject::OnMeasureContent(const MeasureRequirement& requirement,
text_size.height > requirement.max.height.GetLengthOrUndefined()) {
log::TagWarn(
log_tag,
- "(Measure) Text actual height exceeds the required max height.");
+ u"(Measure) Text actual height exceeds the required max height.");
result.height = requirement.max.height.GetLengthOrUndefined();
} else {
result.height =
diff --git a/src/win/CMakeLists.txt b/src/win/CMakeLists.txt
index f4062411..75b0a7ca 100644
--- a/src/win/CMakeLists.txt
+++ b/src/win/CMakeLists.txt
@@ -5,11 +5,9 @@ add_library(cru_win_base STATIC
Exception.cpp
HeapDebug.cpp
- String.cpp
)
target_sources(cru_win_base PUBLIC
${CRU_WIN_BASE_INCLUDE_DIR}/Exception.hpp
- ${CRU_WIN_BASE_INCLUDE_DIR}/String.hpp
${CRU_WIN_BASE_INCLUDE_DIR}/WinPreConfig.hpp
)
target_compile_definitions(cru_win_base PUBLIC UNICODE _UNICODE) # use unicode
diff --git a/src/win/DebugLogger.hpp b/src/win/DebugLogger.hpp
index 4ca1567b..598ee9e8 100644
--- a/src/win/DebugLogger.hpp
+++ b/src/win/DebugLogger.hpp
@@ -1,7 +1,6 @@
#include "cru/win/WinPreConfig.hpp"
#include "cru/common/Logger.hpp"
-#include "cru/win/String.hpp"
namespace cru::platform::win {
@@ -14,11 +13,10 @@ class WinDebugLoggerSource : public ::cru::log::ILogSource {
~WinDebugLoggerSource() = default;
- void Write(::cru::log::LogLevel level, std::string_view s) override {
+ void Write(::cru::log::LogLevel level, const std::u16string& s) override {
CRU_UNUSED(level)
- const std::wstring&& ws = ToUtf16String(s);
- ::OutputDebugStringW(ws.data());
+ ::OutputDebugStringW(reinterpret_cast<const wchar_t*>(s.c_str()));
}
};
} // namespace cru::platform::win
diff --git a/src/win/Exception.cpp b/src/win/Exception.cpp
index 9f9fb03d..8d2eee23 100644
--- a/src/win/Exception.cpp
+++ b/src/win/Exception.cpp
@@ -5,8 +5,8 @@
namespace cru::platform::win {
-inline std::string HResultMakeMessage(HRESULT h_result,
- std::optional<std::string_view> message) {
+inline std::string HResultMakeMessage(
+ HRESULT h_result, std::optional<std::string_view> message) {
if (message.has_value())
return fmt::format(FMT_STRING("HRESULT: {:#08x}. Message: {}"), h_result,
*message);
@@ -19,20 +19,20 @@ HResultError::HResultError(HRESULT h_result)
h_result_(h_result) {}
HResultError::HResultError(HRESULT h_result,
- const std::string_view& additional_message)
+ std::string_view additional_message)
: PlatformException(HResultMakeMessage(h_result, additional_message)),
h_result_(h_result) {}
inline std::string Win32MakeMessage(DWORD error_code,
- std::string_view message) {
+ std::string_view message) {
return fmt::format("Last error code: {:#04x}.\nMessage: {}\n", error_code,
message);
}
-Win32Error::Win32Error(const std::string_view& message)
+Win32Error::Win32Error(std::string_view message)
: Win32Error(::GetLastError(), message) {}
-Win32Error::Win32Error(DWORD error_code, const std::string_view& message)
+Win32Error::Win32Error(DWORD error_code, std::string_view message)
: PlatformException(Win32MakeMessage(error_code, message)),
error_code_(error_code) {}
} // namespace cru::platform::win
diff --git a/src/win/String.cpp b/src/win/String.cpp
deleted file mode 100644
index eb585523..00000000
--- a/src/win/String.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-#include "cru/win/String.hpp"
-
-#include "cru/win/Exception.hpp"
-
-#include <type_traits>
-
-namespace cru::platform::win {
-std::string ToUtf8String(const std::wstring_view& string) {
- if (string.empty()) return std::string{};
-
- const auto length = ::WideCharToMultiByte(
- CP_UTF8, WC_ERR_INVALID_CHARS, string.data(),
- static_cast<int>(string.size()), nullptr, 0, nullptr, nullptr);
- if (length == 0) {
- throw Win32Error(::GetLastError(),
- "Failed to convert wide string to UTF-8.");
- }
-
- std::string result;
- result.resize(length);
- if (::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, string.data(),
- static_cast<int>(string.size()), result.data(),
- static_cast<int>(result.size()), nullptr,
- nullptr) == 0)
- throw Win32Error(::GetLastError(),
- "Failed to convert wide string to UTF-8.");
- return result;
-}
-
-std::wstring ToUtf16String(const std::string_view& string) {
- if (string.empty()) return std::wstring{};
-
- const auto length =
- ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string.data(),
- static_cast<int>(string.size()), nullptr, 0);
- if (length == 0) {
- throw Win32Error(::GetLastError(),
- "Failed to convert wide string to UTF-16.");
- }
-
- std::wstring result;
- result.resize(length);
- if (::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, string.data(),
- static_cast<int>(string.size()), result.data(),
- static_cast<int>(result.size())) == 0)
- throw win::Win32Error(::GetLastError(),
- "Failed to convert wide string to UTF-16.");
- return result;
-}
-
-template <typename UInt, int number_of_bit>
-inline std::enable_if_t<std::is_unsigned_v<UInt>, CodePoint> ExtractBits(
- UInt n) {
- return static_cast<CodePoint>(n & ((1u << number_of_bit) - 1));
-}
-
-CodePoint Utf16Iterator::Next() {
- if (position_ == static_cast<Index>(string_.length()))
- return k_code_point_end;
-
- const auto cu0 = static_cast<std::uint16_t>(string_[position_++]);
-
- if (cu0 < 0xd800u || cu0 >= 0xe000u) { // 1-length code point
- return static_cast<CodePoint>(cu0);
- } else if (cu0 <= 0xdbffu) { // 2-length code point
- if (position_ == static_cast<Index>(string_.length())) {
- throw TextEncodeException(
- "Unexpected end when reading second code unit of surrogate pair.");
- }
- const auto cu1 = static_cast<std::uint16_t>(string_[position_++]);
-
-#ifdef CRU_DEBUG
- if (cu1 < 0xDC00u || cu1 > 0xdfffu) {
- throw TextEncodeException(
- "Unexpected bad-format second code unit of surrogate pair.");
- }
-#endif
-
- const auto s0 = ExtractBits<std::uint16_t, 10>(cu0) << 10;
- const auto s1 = ExtractBits<std::uint16_t, 10>(cu1);
-
- return s0 + s1 + 0x10000;
-
- } else {
- throw TextEncodeException(
- "Unexpected bad-format first code unit of surrogate pair.");
- }
-}
-
-Index IndexUtf8ToUtf16(const std::string_view& utf8_string, Index utf8_index,
- const std::wstring_view& utf16_string) {
- if (utf8_index >= static_cast<Index>(utf8_string.length()))
- return utf16_string.length();
-
- Index cp_index = 0;
- Utf8Iterator iter{utf8_string};
- while (iter.CurrentPosition() <= utf8_index) {
- iter.Next();
- cp_index++;
- }
-
- Utf16Iterator result_iter{utf16_string};
- for (Index i = 0; i < cp_index - 1; i++) {
- if (result_iter.Next() == k_code_point_end) break;
- }
-
- return result_iter.CurrentPosition();
-}
-
-Index IndexUtf16ToUtf8(const std::wstring_view& utf16_string, Index utf16_index,
- const std::string_view& utf8_string) {
- if (utf16_index >= static_cast<Index>(utf16_string.length()))
- return utf8_string.length();
-
- Index cp_index = 0;
- Utf16Iterator iter{utf16_string};
- while (iter.CurrentPosition() <= utf16_index) {
- iter.Next();
- cp_index++;
- }
-
- Utf8Iterator result_iter{utf8_string};
- for (Index i = 0; i < cp_index - 1; i++) {
- if (result_iter.Next() == k_code_point_end) break;
- }
-
- return result_iter.CurrentPosition();
-}
-} // namespace cru::platform::win
diff --git a/src/win/graph/direct/Factory.cpp b/src/win/graph/direct/Factory.cpp
index d9213994..03e64e13 100644
--- a/src/win/graph/direct/Factory.cpp
+++ b/src/win/graph/direct/Factory.cpp
@@ -19,8 +19,8 @@ void InitializeCom() {
}
if (hresult == S_FALSE) {
log::Debug(
- "Try to call CoInitializeEx, but it seems COM is already "
- "initialized.");
+ u"Try to call CoInitializeEx, but it seems COM is already "
+ u"initialized.");
}
}
@@ -95,12 +95,12 @@ std::unique_ptr<IGeometryBuilder> DirectGraphFactory::CreateGeometryBuilder() {
}
std::unique_ptr<IFont> DirectGraphFactory::CreateFont(
- const std::string_view& font_family, float font_size) {
- return std::make_unique<DWriteFont>(this, font_family, font_size);
+ std::u16string font_family, float font_size) {
+ return std::make_unique<DWriteFont>(this, std::move(font_family), font_size);
}
std::unique_ptr<ITextLayout> DirectGraphFactory::CreateTextLayout(
- std::shared_ptr<IFont> font, std::string text) {
+ std::shared_ptr<IFont> font, std::u16string text) {
return std::make_unique<DWriteTextLayout>(this, std::move(font),
std::move(text));
}
diff --git a/src/win/graph/direct/Font.cpp b/src/win/graph/direct/Font.cpp
index edbbc59d..34de5b71 100644
--- a/src/win/graph/direct/Font.cpp
+++ b/src/win/graph/direct/Font.cpp
@@ -2,15 +2,14 @@
#include "cru/win/graph/direct/Exception.hpp"
#include "cru/win/graph/direct/Factory.hpp"
-#include "cru/win/String.hpp"
#include <array>
#include <utility>
namespace cru::platform::graph::win::direct {
-DWriteFont::DWriteFont(DirectGraphFactory* factory,
- const std::string_view& font_family, float font_size)
- : DirectGraphResource(factory) {
+DWriteFont::DWriteFont(DirectGraphFactory* factory, std::u16string font_family,
+ float font_size)
+ : DirectGraphResource(factory), font_family_(std::move(font_family)) {
// Get locale
std::array<wchar_t, LOCALE_NAME_MAX_LENGTH> buffer;
if (!::GetUserDefaultLocaleName(buffer.data(),
@@ -18,10 +17,9 @@ DWriteFont::DWriteFont(DirectGraphFactory* factory,
throw platform::win::Win32Error(
::GetLastError(), "Failed to get locale when create dwrite font.");
- const std::wstring&& wff = cru::platform::win::ToUtf16String(font_family);
-
ThrowIfFailed(factory->GetDWriteFactory()->CreateTextFormat(
- wff.data(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL,
+ 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));
diff --git a/src/win/graph/direct/TextLayout.cpp b/src/win/graph/direct/TextLayout.cpp
index 16db77f0..7b5b230f 100644
--- a/src/win/graph/direct/TextLayout.cpp
+++ b/src/win/graph/direct/TextLayout.cpp
@@ -5,38 +5,33 @@
#include "cru/win/graph/direct/Exception.hpp"
#include "cru/win/graph/direct/Factory.hpp"
#include "cru/win/graph/direct/Font.hpp"
-#include "cru/win/String.hpp"
#include <utility>
namespace cru::platform::graph::win::direct {
-using cru::platform::win::IndexUtf16ToUtf8;
-using cru::platform::win::IndexUtf8ToUtf16;
-
DWriteTextLayout::DWriteTextLayout(DirectGraphFactory* factory,
std::shared_ptr<IFont> font,
- std::string text)
+ std::u16string text)
: DirectGraphResource(factory), text_(std::move(text)) {
Expects(font);
font_ = CheckPlatform<DWriteFont>(font, GetPlatformId());
- w_text_ = cru::platform::win::ToUtf16String(text_);
-
ThrowIfFailed(factory->GetDWriteFactory()->CreateTextLayout(
- w_text_.c_str(), static_cast<UINT32>(w_text_.size()),
- font_->GetComInterface(), max_width_, max_height_, &text_layout_));
+ reinterpret_cast<const wchar_t*>(text_.c_str()),
+ static_cast<UINT32>(text_.size()), font_->GetComInterface(), max_width_,
+ max_height_, &text_layout_));
}
DWriteTextLayout::~DWriteTextLayout() = default;
-std::string DWriteTextLayout::GetText() { return text_; }
+std::u16string DWriteTextLayout::GetText() { return text_; }
-void DWriteTextLayout::SetText(std::string new_text) {
+void DWriteTextLayout::SetText(std::u16string new_text) {
text_.swap(new_text);
- w_text_ = cru::platform::win::ToUtf16String(text_);
ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout(
- w_text_.c_str(), static_cast<UINT32>(w_text_.size()),
- font_->GetComInterface(), max_width_, max_height_, &text_layout_));
+ 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() {
@@ -46,8 +41,9 @@ std::shared_ptr<IFont> DWriteTextLayout::GetFont() {
void DWriteTextLayout::SetFont(std::shared_ptr<IFont> font) {
font_ = CheckPlatform<DWriteFont>(font, GetPlatformId());
ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout(
- w_text_.c_str(), static_cast<UINT32>(w_text_.size()),
- font_->GetComInterface(), max_width_, max_height_, &text_layout_));
+ 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) {
@@ -73,12 +69,6 @@ std::vector<Rect> DWriteTextLayout::TextRangeRect(
}
const auto text_range = text_range_arg.Normalize();
- // TODO: This can be faster with one iteration.
- const int start_index =
- IndexUtf8ToUtf16(text_, static_cast<int>(text_range.position), w_text_);
- const int end_index = IndexUtf8ToUtf16(
- text_, static_cast<int>(text_range.position + text_range.count), w_text_);
-
DWRITE_TEXT_METRICS text_metrics;
ThrowIfFailed(text_layout_->GetMetrics(&text_metrics));
const auto metrics_count =
@@ -87,9 +77,9 @@ std::vector<Rect> DWriteTextLayout::TextRangeRect(
std::vector<DWRITE_HIT_TEST_METRICS> hit_test_metrics(metrics_count);
UINT32 actual_count;
ThrowIfFailed(text_layout_->HitTestTextRange(
- static_cast<UINT32>(start_index),
- static_cast<UINT32>(end_index - start_index), 0, 0,
- hit_test_metrics.data(), metrics_count, &actual_count));
+ 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());
@@ -105,14 +95,11 @@ std::vector<Rect> DWriteTextLayout::TextRangeRect(
return result;
}
-Point DWriteTextLayout::TextSinglePoint(gsl::index position, bool trailing) {
- const auto index =
- IndexUtf8ToUtf16(text_, static_cast<int>(position), w_text_);
-
+Point DWriteTextLayout::TextSinglePoint(Index position, bool trailing) {
DWRITE_HIT_TEST_METRICS metrics;
FLOAT left;
FLOAT top;
- ThrowIfFailed(text_layout_->HitTestTextPosition(static_cast<UINT32>(index),
+ ThrowIfFailed(text_layout_->HitTestTextPosition(static_cast<UINT32>(position),
static_cast<BOOL>(trailing),
&left, &top, &metrics));
return Point{left, top};
@@ -126,10 +113,8 @@ TextHitTestResult DWriteTextLayout::HitTest(const Point& point) {
ThrowIfFailed(text_layout_->HitTestPoint(point.x, point.y, &trailing, &inside,
&metrics));
- const auto index =
- IndexUtf16ToUtf8(w_text_, static_cast<int>(metrics.textPosition), text_);
TextHitTestResult result;
- result.position = index;
+ result.position = metrics.textPosition;
result.trailing = trailing != 0;
result.insideText = inside != 0;
return result;
diff --git a/src/win/native/Cursor.cpp b/src/win/native/Cursor.cpp
index a6ab5bfc..429f6e7c 100644
--- a/src/win/native/Cursor.cpp
+++ b/src/win/native/Cursor.cpp
@@ -16,7 +16,7 @@ WinCursor::~WinCursor() {
if (!::DestroyCursor(handle_)) {
// This is not a fetal error but might still need notice because it may
// cause leak.
- log::TagWarn(log_tag, "Failed to destroy a cursor. Last error code: {}",
+ log::TagWarn(log_tag, u"Failed to destroy a cursor. Last error code: {}",
::GetLastError());
}
}
diff --git a/src/win/native/GodWindow.cpp b/src/win/native/GodWindow.cpp
index 8ef2788e..b1e7275e 100644
--- a/src/win/native/GodWindow.cpp
+++ b/src/win/native/GodWindow.cpp
@@ -45,7 +45,7 @@ GodWindow::GodWindow(WinUiApplication* application) {
GodWindow::~GodWindow() {
if (!::DestroyWindow(hwnd_)) {
// Although this could be "safely" ignore.
- log::TagWarn(log_tag, "Failed to destroy god window.");
+ log::TagWarn(log_tag, u"Failed to destroy god window.");
}
}
diff --git a/src/win/native/InputMethod.cpp b/src/win/native/InputMethod.cpp
index d3d989f3..5fc6c934 100644
--- a/src/win/native/InputMethod.cpp
+++ b/src/win/native/InputMethod.cpp
@@ -2,9 +2,9 @@
#include "DpiUtil.hpp"
#include "cru/common/Logger.hpp"
+#include "cru/common/StringUtil.hpp"
#include "cru/platform/Check.hpp"
#include "cru/win/Exception.hpp"
-#include "cru/win/String.hpp"
#include "cru/win/native/Window.hpp"
#include <vector>
@@ -35,7 +35,7 @@ AutoHIMC& AutoHIMC::operator=(AutoHIMC&& other) {
AutoHIMC::~AutoHIMC() {
if (handle_) {
if (!::ImmReleaseContext(hwnd_, handle_))
- log::TagWarn(log_tag, "Failed to release HIMC.");
+ log::TagWarn(log_tag, u"Failed to release HIMC.");
}
}
@@ -104,19 +104,19 @@ CompositionClauses GetCompositionClauses(HIMC imm_context, int target_start,
return result;
}
-std::wstring GetString(HIMC imm_context) {
+std::u16string GetString(HIMC imm_context) {
LONG string_size =
::ImmGetCompositionString(imm_context, GCS_COMPSTR, NULL, 0);
- std::wstring result((string_size / sizeof(wchar_t)), 0);
+ std::u16string result((string_size / sizeof(char16_t)), 0);
::ImmGetCompositionString(imm_context, GCS_COMPSTR, result.data(),
string_size);
return result;
}
-std::wstring GetResultString(HIMC imm_context) {
+std::u16string GetResultString(HIMC imm_context) {
LONG string_size =
::ImmGetCompositionString(imm_context, GCS_RESULTSTR, NULL, 0);
- std::wstring result((string_size / sizeof(wchar_t)), 0);
+ std::u16string result((string_size / sizeof(char16_t)), 0);
::ImmGetCompositionString(imm_context, GCS_RESULTSTR, result.data(),
string_size);
return result;
@@ -126,25 +126,17 @@ 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 w_text = GetString(imm_context);
+ auto text = GetString(imm_context);
- int w_length = static_cast<int>(w_text.length());
+ int length = static_cast<int>(text.length());
// Find out the range selected by the user.
- int w_target_start = w_length;
- int w_target_end = w_length;
- GetCompositionTargetRange(imm_context, &w_target_start, &w_target_end);
+ int target_start = length;
+ int target_end = length;
+ GetCompositionTargetRange(imm_context, &target_start, &target_end);
- auto clauses =
- GetCompositionClauses(imm_context, w_target_start, w_target_end);
+ auto clauses = GetCompositionClauses(imm_context, target_start, target_end);
- int w_cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0);
-
- auto text = platform::win::ToUtf8String(w_text);
- for (auto& clause : clauses) {
- clause.start = platform::win::IndexUtf16ToUtf8(w_text, clause.start, text);
- clause.end = platform::win::IndexUtf16ToUtf8(w_text, clause.end, text);
- }
- int cursor = platform::win::IndexUtf16ToUtf8(w_text, w_cursor, text);
+ int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0);
return CompositionText{std::move(text), std::move(clauses),
TextRange{cursor}};
@@ -169,7 +161,7 @@ void WinInputMethodContext::EnableIME() {
const auto hwnd = native_window->GetWindowHandle();
if (::ImmAssociateContextEx(hwnd, nullptr, IACE_DEFAULT) == FALSE) {
- log::TagWarn(log_tag, "Failed to enable ime.");
+ log::TagWarn(log_tag, u"Failed to enable ime.");
}
}
@@ -181,11 +173,12 @@ void WinInputMethodContext::DisableIME() {
AutoHIMC himc{hwnd};
if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) {
- log::TagWarn(log_tag, "Failed to complete composition before disable ime.");
+ log::TagWarn(log_tag,
+ u"Failed to complete composition before disable ime.");
}
if (::ImmAssociateContextEx(hwnd, nullptr, 0) == FALSE) {
- log::TagWarn(log_tag, "Failed to disable ime.");
+ log::TagWarn(log_tag, u"Failed to disable ime.");
}
}
@@ -195,7 +188,7 @@ void WinInputMethodContext::CompleteComposition() {
auto himc = *std::move(optional_himc);
if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) {
- log::TagWarn(log_tag, "Failed to complete composition.");
+ log::TagWarn(log_tag, u"Failed to complete composition.");
}
}
@@ -205,7 +198,7 @@ void WinInputMethodContext::CancelComposition() {
auto himc = *std::move(optional_himc);
if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0)) {
- log::TagWarn(log_tag, "Failed to complete composition.");
+ log::TagWarn(log_tag, u"Failed to complete composition.");
}
}
@@ -229,7 +222,7 @@ void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) {
if (!::ImmSetCandidateWindow(himc.Get(), &form))
log::TagDebug(log_tag,
- "Failed to set input method candidate window position.");
+ u"Failed to set input method candidate window position.");
}
IEvent<std::nullptr_t>* WinInputMethodContext::CompositionStartEvent() {
@@ -244,7 +237,7 @@ IEvent<std::nullptr_t>* WinInputMethodContext::CompositionEvent() {
return &composition_event_;
}
-IEvent<std::string_view>* WinInputMethodContext::TextEvent() {
+IEvent<std::u16string_view>* WinInputMethodContext::TextEvent() {
return &text_event_;
}
@@ -253,18 +246,17 @@ void WinInputMethodContext::OnWindowNativeMessage(
const auto& message = args.GetWindowMessage();
switch (message.msg) {
case WM_CHAR: {
- const auto c = static_cast<wchar_t>(message.w_param);
- if (platform::win::IsSurrogatePair(c)) {
+ const auto c = static_cast<char16_t>(message.w_param);
+ if (IsSurrogatePair(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.
log::TagWarn(log_tag,
- "A WM_CHAR message for character from supplementary "
- "planes is ignored.");
+ u"A WM_CHAR message for character from supplementary "
+ u"planes is ignored.");
} else {
- wchar_t s[1] = {c};
- auto str = platform::win::ToUtf8String({s, 1});
- text_event_.Raise(str);
+ char16_t s[1] = {c};
+ text_event_.Raise({s, 1});
}
args.HandleWithResult(0);
break;
@@ -272,8 +264,6 @@ void WinInputMethodContext::OnWindowNativeMessage(
case WM_IME_COMPOSITION: {
composition_event_.Raise(nullptr);
auto composition_text = GetCompositionText();
- log::TagDebug(log_tag, "WM_IME_COMPOSITION composition text:\n{}",
- composition_text);
if (message.l_param & GCS_RESULTSTR) {
auto result_string = GetResultString();
text_event_.Raise(result_string);
@@ -291,13 +281,13 @@ void WinInputMethodContext::OnWindowNativeMessage(
}
}
-std::string WinInputMethodContext::GetResultString() {
+std::u16string WinInputMethodContext::GetResultString() {
auto optional_himc = TryGetHIMC();
- if (!optional_himc.has_value()) return "";
+ if (!optional_himc.has_value()) return u"";
auto himc = *std::move(optional_himc);
- auto w_result = win::GetResultString(himc.Get());
- return platform::win::ToUtf8String(w_result);
+ auto result = win::GetResultString(himc.Get());
+ return result;
}
std::optional<AutoHIMC> WinInputMethodContext::TryGetHIMC() {
diff --git a/src/win/native/Window.cpp b/src/win/native/Window.cpp
index 22505bd6..81642451 100644
--- a/src/win/native/Window.cpp
+++ b/src/win/native/Window.cpp
@@ -5,7 +5,6 @@
#include "WindowManager.hpp"
#include "cru/common/Logger.hpp"
#include "cru/platform/Check.hpp"
-#include "cru/win/String.hpp"
#include "cru/win/native/Cursor.hpp"
#include "cru/win/native/Exception.hpp"
#include "cru/win/native/Keyboard.hpp"
@@ -124,7 +123,7 @@ bool WinNativeWindow::ReleaseMouse() {
}
void WinNativeWindow::RequestRepaint() {
- log::TagDebug(log_tag, "A repaint is requested.");
+ log::TagDebug(log_tag, u"A repaint is requested.");
if (!::InvalidateRect(hwnd_, nullptr, FALSE))
throw Win32Error(::GetLastError(), "Failed to invalidate window.");
if (!::UpdateWindow(hwnd_))
@@ -145,43 +144,43 @@ void WinNativeWindow::SetCursor(std::shared_ptr<ICursor> cursor) {
if (!::SetClassLongPtrW(hwnd_, GCLP_HCURSOR,
reinterpret_cast<LONG_PTR>(cursor_->GetHandle()))) {
log::TagWarn(log_tag,
- "Failed to set cursor because failed to set class long. Last "
- "error code: {}.",
+ u"Failed to set cursor because failed to set class long. Last "
+ u"error code: {}.",
::GetLastError());
return;
}
if (!IsVisible()) return;
- auto lg = [](const std::string_view& reason) {
+ auto lg = [](const std::u16string_view& reason) {
log::TagWarn(
log_tag,
- "Failed to set cursor because {} when window is visible. (We need to "
- "update cursor if it is inside the window.) Last error code: {}.",
+ 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("failed to get cursor pos");
+ lg(u"failed to get cursor pos");
return;
}
::RECT rect;
if (!::GetClientRect(hwnd_, &rect)) {
- lg("failed to get window's client 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("failed to call ClientToScreen on lefttop");
+ lg(u"failed to call ClientToScreen on lefttop");
return;
}
if (!::ClientToScreen(hwnd_, &rightbottom)) {
- lg("failed to call ClientToScreen on rightbottom");
+ lg(u"failed to call ClientToScreen on rightbottom");
return;
}
@@ -354,7 +353,7 @@ void WinNativeWindow::OnDestroyInternal() {
void WinNativeWindow::OnPaintInternal() {
paint_event_.Raise(nullptr);
ValidateRect(hwnd_, nullptr);
- log::TagDebug(log_tag, "A repaint is finished.");
+ log::TagDebug(log_tag, u"A repaint is finished.");
}
void WinNativeWindow::OnResizeInternal(const int new_width,