diff options
author | crupest <crupest@outlook.com> | 2022-02-21 18:44:40 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2022-02-21 18:44:40 +0800 |
commit | ced1a63686e6c64cb574d74a34d1bbd07d0a668e (patch) | |
tree | 4082e4689e5e7cede8d59a0538d0f1ae37064acb | |
parent | 6b00fca7c662301bf657a99cb1e89f21541a46bc (diff) | |
download | cru-ced1a63686e6c64cb574d74a34d1bbd07d0a668e.tar.gz cru-ced1a63686e6c64cb574d74a34d1bbd07d0a668e.tar.bz2 cru-ced1a63686e6c64cb574d74a34d1bbd07d0a668e.zip |
...
56 files changed, 448 insertions, 389 deletions
diff --git a/include/cru/common/Base.h b/include/cru/common/Base.h index 4d4d1f5f..899cfc13 100644 --- a/include/cru/common/Base.h +++ b/include/cru/common/Base.h @@ -94,5 +94,5 @@ inline void hash_combine(std::size_t& s, const T& v) { #define CRU_DEFINE_CLASS_LOG_TAG(tag) \ private: \ - constexpr static StringView log_tag = tag; + constexpr static const char16_t* kLogTag = tag; } // namespace cru diff --git a/include/cru/common/Format.h b/include/cru/common/Format.h index 7628f07d..2b08f03b 100644 --- a/include/cru/common/Format.h +++ b/include/cru/common/Format.h @@ -92,7 +92,7 @@ struct FormatToken { String place_holder_option; }; -std::vector<FormatToken> CRU_BASE_API ParseToFormatTokenList(const String& str); +std::vector<FormatToken> CRU_BASE_API ParseToFormatTokenList(StringView str); void CRU_BASE_API FormatAppendFromFormatTokenList( String& current, const std::vector<FormatToken>& format_token_list, @@ -123,7 +123,7 @@ void FormatAppendFromFormatTokenList( } // namespace details template <typename... T> -String Format(const String& format, T&&... args) { +String Format(StringView format, T&&... args) { String result; details::FormatAppendFromFormatTokenList( diff --git a/include/cru/common/Logger.h b/include/cru/common/Logger.h deleted file mode 100644 index 25875651..00000000 --- a/include/cru/common/Logger.h +++ /dev/null @@ -1,114 +0,0 @@ -#pragma once -#include "Base.h" - -#include "String.h" -#include "Format.h" - -#include <list> -#include <memory> - -namespace cru::log { - -enum class LogLevel { Debug, Info, Warn, Error }; - -struct CRU_BASE_API ILogSource : virtual Interface { - // Write the string s. LogLevel is just a helper. It has no effect on the - // content to write. - virtual void Write(LogLevel level, StringView s) = 0; -}; - -class CRU_BASE_API Logger : public Object { - public: - static Logger* GetInstance(); - - public: - Logger() = default; - - CRU_DELETE_COPY(Logger) - CRU_DELETE_MOVE(Logger) - - ~Logger() override = default; - - public: - void AddSource(std::unique_ptr<ILogSource> source); - void RemoveSource(ILogSource* source); - - public: - void Log(LogLevel level, StringView message); - void Log(LogLevel level, StringView tag, StringView message); - - private: - std::list<std::unique_ptr<ILogSource>> sources_; -}; - -// TODO: Remove argument evaluation in Debug. -template <typename... TArgs> -void Debug([[maybe_unused]] TArgs&&... args) { -#ifdef CRU_DEBUG - Logger::GetInstance()->Log(LogLevel::Debug, - Format(std::forward<TArgs>(args)...)); -#endif -} - -template <typename... TArgs> -void Info(TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Info, - Format(std::forward<TArgs>(args)...)); -} - -template <typename... TArgs> -void Warn(TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Warn, - Format(std::forward<TArgs>(args)...)); -} - -template <typename... TArgs> -void Error(TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Error, - Format(std::forward<TArgs>(args)...)); -} - -// TODO: Remove argument evaluation in Debug. -template <typename... TArgs> -void TagDebug([[maybe_unused]] StringView tag, - [[maybe_unused]] TArgs&&... args) { -#ifdef CRU_DEBUG - Logger::GetInstance()->Log(LogLevel::Debug, tag, - Format(std::forward<TArgs>(args)...)); -#endif -} - -template <typename... TArgs> -void TagInfo(StringView tag, TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Info, tag, - Format(std::forward<TArgs>(args)...)); -} - -template <typename... TArgs> -void TagWarn(StringView tag, TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Warn, tag, - Format(std::forward<TArgs>(args)...)); -} - -template <typename... TArgs> -void TagError(StringView tag, TArgs&&... args) { - Logger::GetInstance()->Log(LogLevel::Error, tag, - Format(std::forward<TArgs>(args)...)); -} - -class StdioLogSource : public Object, public virtual ILogSource { - public: - explicit StdioLogSource(bool use_lock = false); - - CRU_DELETE_COPY(StdioLogSource) - CRU_DELETE_MOVE(StdioLogSource) - - ~StdioLogSource() override; - - public: - void Write(LogLevel level, StringView s) override; - - private: - bool use_lock_; -}; -} // namespace cru::log diff --git a/include/cru/common/String.h b/include/cru/common/String.h index 0b1b031b..be886168 100644 --- a/include/cru/common/String.h +++ b/include/cru/common/String.h @@ -63,7 +63,7 @@ class CRU_BASE_API String { public: String() = default; - explicit String(const_pointer str); + String(const_pointer str); String(const_pointer str, size_type size); template <Index size> diff --git a/include/cru/common/concurrent/ConcurrentQueue.h b/include/cru/common/concurrent/ConcurrentQueue.h new file mode 100644 index 00000000..4f649a41 --- /dev/null +++ b/include/cru/common/concurrent/ConcurrentQueue.h @@ -0,0 +1,110 @@ +#pragma once +#include <condition_variable> +#include <mutex> +#include <optional> +#include <utility> + +namespace cru::concurrent { +namespace details { +template <typename T> +struct ConcurrentQueueNode { + ConcurrentQueueNode(T&& value, ConcurrentQueueNode* next = nullptr) + : value(std::move(value)), next(next) {} + + T value; + ConcurrentQueueNode* next; +}; +} // namespace details + +template <typename T> +class ConcurrentQueue { + public: + ConcurrentQueue() {} + + ConcurrentQueue(const ConcurrentQueue&) = delete; + ConcurrentQueue& operator=(const ConcurrentQueue&) = delete; + + ConcurrentQueue(ConcurrentQueue&& other) + : head_(other.head_), + tail_(other.tail_), + mutex_(std::move(other.mutex_)), + condition_variable_(std::move(other.condition_variable_)) { + other.head_ = nullptr; + other.tail_ = nullptr; + } + + ConcurrentQueue& operator=(ConcurrentQueue&& other) { + if (this != &other) { + head_ = other.head_; + tail_ = other.tail_; + mutex_ = std::move(other.mutex_); + condition_variable_ = std::move(other.condition_variable_); + other.head_ = nullptr; + other.tail_ = nullptr; + return *this; + } + return *this; + } + + ~ConcurrentQueue() { + if (head_) { + auto node = head_; + while (node) { + auto next = node->next; + delete node; + node = next; + } + } + } + + public: + void Push(T&& value) { + std::unique_lock<std::mutex> lock(mutex_); + if (head_ == nullptr) { + head_ = tail_ = new details::ConcurrentQueueNode<T>(std::move(value)); + condition_variable_.notify_one(); + } else { + tail_->next = new details::ConcurrentQueueNode<T>(std::move(value)); + tail_ = tail_->next; + } + } + + T Pull() { + std::unique_lock<std::mutex> lock(mutex_); + if (head_ == nullptr) { + condition_variable_.wait(lock); + } + assert(head_ != nullptr); + auto value = std::move(head_->value); + auto next = head_->next; + delete head_; + head_ = next; + if (next == nullptr) { + tail_ = nullptr; + } + return value; + } + + std::optional<T> Poll() { + std::unique_lock<std::mutex> lock(mutex_); + if (head_ == nullptr) { + return std::nullopt; + } + auto value = std::move(head_->value); + auto next = head_->next; + delete head_; + head_ = next; + if (next == nullptr) { + tail_ = nullptr; + } + return value; + } + + private: + details::ConcurrentQueueNode<T>* head_ = nullptr; + details::ConcurrentQueueNode<T>* tail_ = nullptr; + + std::mutex mutex_; + std::condition_variable condition_variable_; +}; +} // namespace cru::concurrent diff --git a/include/cru/common/log/Logger.h b/include/cru/common/log/Logger.h new file mode 100644 index 00000000..25735e14 --- /dev/null +++ b/include/cru/common/log/Logger.h @@ -0,0 +1,88 @@ +#pragma once +#include "../Base.h" + +#include "../Format.h" +#include "../String.h" +#include "../concurrent/ConcurrentQueue.h" + +#include <memory> +#include <mutex> +#include <thread> +#include <vector> + +namespace cru::log { +enum class LogLevel { Debug, Info, Warn, Error }; + +struct CRU_BASE_API LogInfo { + LogInfo(LogLevel level, String tag, String message) + : level(level), tag(std::move(tag)), message(std::move(message)) {} + + CRU_DEFAULT_COPY(LogInfo) + CRU_DEFAULT_MOVE(LogInfo) + + ~LogInfo() = default; + + LogLevel level; + String tag; + String message; +}; + +struct CRU_BASE_API ILogTarget : virtual Interface { + // Write the string s. LogLevel is just a helper. It has no effect on the + // content to write. + virtual void Write(LogLevel level, StringView s) = 0; +}; + +class CRU_BASE_API Logger : public Object { + public: + static Logger* GetInstance(); + + public: + Logger(); + + CRU_DELETE_COPY(Logger) + CRU_DELETE_MOVE(Logger) + + ~Logger() override; + + public: + void AddLogTarget(std::unique_ptr<ILogTarget> source); + void RemoveLogTarget(ILogTarget* source); + + public: + void Log(LogLevel level, String tag, String message) { + Log(LogInfo(level, std::move(tag), std::move(message))); + } + void Log(LogInfo log_info); + + template <typename... Args> + void FormatLog(LogLevel level, String tag, StringView format, + Args&&... args) { + Log(level, std::move(tag), Format(format, std::forward<Args>(args)...)); + } + + private: + concurrent::ConcurrentQueue<LogInfo> log_queue_; + + std::mutex target_list_mutex_; + std::vector<std::unique_ptr<ILogTarget>> target_list_; + + std::thread log_thread_; +}; +} // namespace cru::log + +#define CRU_LOG_DEBUG(...) \ + cru::log::Logger::GetInstance()->FormatLog(cru::log::LogLevel::Debug, \ + kLogTag, __VA_ARGS__) + +#define CRU_LOG_INFO(...) \ + cru::log::Logger::GetInstance()->FormatLog(cru::log::LogLevel::Info, \ + kLogTag, __VA_ARGS__) + +#define CRU_LOG_WARN(...) \ + cru::log::Logger::GetInstance()->FormatLog(cru::log::LogLevel::Warn, \ + kLogTag, __VA_ARGS__) + +#define CRU_LOG_ERROR(...) \ + cru::log::Logger::GetInstance()->FormatLog(cru::log::LogLevel::Error, \ + kLogTag, __VA_ARGS__) diff --git a/include/cru/common/log/StdioLogTarget.h b/include/cru/common/log/StdioLogTarget.h new file mode 100644 index 00000000..4123766b --- /dev/null +++ b/include/cru/common/log/StdioLogTarget.h @@ -0,0 +1,17 @@ +#pragma once +#include "Logger.h" + +namespace cru::log { +class StdioLogTarget : public Object, public virtual log::ILogTarget { + public: + explicit StdioLogTarget(); + + CRU_DELETE_COPY(StdioLogTarget) + CRU_DELETE_MOVE(StdioLogTarget) + + ~StdioLogTarget() override; + + public: + void Write(log::LogLevel level, StringView s) override; +}; +} // namespace cru::log diff --git a/include/cru/osx/graphics/quartz/Painter.h b/include/cru/osx/graphics/quartz/Painter.h index 19428583..87389437 100644 --- a/include/cru/osx/graphics/quartz/Painter.h +++ b/include/cru/osx/graphics/quartz/Painter.h @@ -11,8 +11,7 @@ namespace cru::platform::graphics::osx::quartz { class QuartzCGContextPainter : public OsxQuartzResource, public virtual IPainter { - CRU_DEFINE_CLASS_LOG_TAG( - u"cru::platform::graphics::osx::quartz::QuartzCGContextPainter") + CRU_DEFINE_CLASS_LOG_TAG(u"QuartzCGContextPainter") public: explicit QuartzCGContextPainter( diff --git a/include/cru/ui/controls/TextHostControlService.h b/include/cru/ui/controls/TextHostControlService.h index 74da1e19..dec9b3e0 100644 --- a/include/cru/ui/controls/TextHostControlService.h +++ b/include/cru/ui/controls/TextHostControlService.h @@ -76,7 +76,7 @@ class TextControlMovePattern : public Object { }; class CRU_UI_API TextHostControlService : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::controls::TextControlService") + CRU_DEFINE_CLASS_LOG_TAG(u"TextControlService") public: TextHostControlService(gsl::not_null<Control*> control); diff --git a/include/cru/ui/helper/ClickDetector.h b/include/cru/ui/helper/ClickDetector.h index 0d74b9c0..3bf28451 100644 --- a/include/cru/ui/helper/ClickDetector.h +++ b/include/cru/ui/helper/ClickDetector.h @@ -41,7 +41,7 @@ enum class ClickState { }; class ClickDetector : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::ClickDetector") + CRU_DEFINE_CLASS_LOG_TAG(u"ClickDetector") public: explicit ClickDetector(controls::Control* control); diff --git a/include/cru/ui/helper/ShortcutHub.h b/include/cru/ui/helper/ShortcutHub.h index 84e786aa..28c41234 100644 --- a/include/cru/ui/helper/ShortcutHub.h +++ b/include/cru/ui/helper/ShortcutHub.h @@ -2,6 +2,7 @@ #include "../Base.h" #include "../events/UiEvents.h" +#include "cru/common/Base.h" #include "cru/common/Event.h" #include "cru/platform/gui/Keyboard.h" @@ -97,6 +98,7 @@ struct ShortcutInfo { }; class CRU_UI_API ShortcutHub : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"ShortcutHub") public: ShortcutHub() = default; diff --git a/include/cru/ui/host/WindowHost.h b/include/cru/ui/host/WindowHost.h index 9fe46ac0..b1d0c998 100644 --- a/include/cru/ui/host/WindowHost.h +++ b/include/cru/ui/host/WindowHost.h @@ -19,7 +19,7 @@ struct AfterLayoutEventArgs {}; // The bridge between control tree and native window. class CRU_UI_API WindowHost : public Object { friend controls::Control; - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::host::WindowHost") + CRU_DEFINE_CLASS_LOG_TAG(u"WindowHost") public: explicit WindowHost(controls::Control* root_control); diff --git a/include/cru/ui/render/BorderRenderObject.h b/include/cru/ui/render/BorderRenderObject.h index 2fc74f0f..a71cd6a0 100644 --- a/include/cru/ui/render/BorderRenderObject.h +++ b/include/cru/ui/render/BorderRenderObject.h @@ -5,7 +5,7 @@ namespace cru::ui::render { class CRU_UI_API BorderRenderObject : public SingleChildRenderObject { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::BorderRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"BorderRenderObject") public: BorderRenderObject(); diff --git a/include/cru/ui/render/FlexLayoutRenderObject.h b/include/cru/ui/render/FlexLayoutRenderObject.h index ff7340cb..4effacb1 100644 --- a/include/cru/ui/render/FlexLayoutRenderObject.h +++ b/include/cru/ui/render/FlexLayoutRenderObject.h @@ -93,7 +93,7 @@ struct FlexChildLayoutData { // class CRU_UI_API FlexLayoutRenderObject : public LayoutRenderObject<FlexChildLayoutData> { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::FlexLayoutRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"FlexLayoutRenderObject") public: FlexLayoutRenderObject() = default; diff --git a/include/cru/ui/render/RenderObject.h b/include/cru/ui/render/RenderObject.h index 311ab044..e8dc3b17 100644 --- a/include/cru/ui/render/RenderObject.h +++ b/include/cru/ui/render/RenderObject.h @@ -36,7 +36,7 @@ namespace cru::ui::render { * void OnLayoutContent(const Rect& content_rect) override; */ class CRU_UI_API RenderObject : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::RenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"RenderObject") protected: RenderObject() = default; diff --git a/include/cru/ui/render/SingleChildRenderObject.h b/include/cru/ui/render/SingleChildRenderObject.h index cc9e4126..a98465f0 100644 --- a/include/cru/ui/render/SingleChildRenderObject.h +++ b/include/cru/ui/render/SingleChildRenderObject.h @@ -3,7 +3,7 @@ namespace cru::ui::render { class CRU_UI_API SingleChildRenderObject : public RenderObject { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::SingleChildRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"SingleChildRenderObject") public: SingleChildRenderObject() = default; diff --git a/include/cru/ui/render/StackLayoutRenderObject.h b/include/cru/ui/render/StackLayoutRenderObject.h index b522ecbb..4da63ea2 100644 --- a/include/cru/ui/render/StackLayoutRenderObject.h +++ b/include/cru/ui/render/StackLayoutRenderObject.h @@ -28,7 +28,7 @@ struct StackChildLayoutData { // to min size. class CRU_UI_API StackLayoutRenderObject : public LayoutRenderObject<StackChildLayoutData> { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render:StackLayoutRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"StackLayoutRenderObject") public: StackLayoutRenderObject() = default; diff --git a/include/cru/ui/render/TextRenderObject.h b/include/cru/ui/render/TextRenderObject.h index db8ff0d0..079c5680 100644 --- a/include/cru/ui/render/TextRenderObject.h +++ b/include/cru/ui/render/TextRenderObject.h @@ -18,7 +18,7 @@ namespace cru::ui::render { // If the result layout box is bigger than actual text box, then text is center // aligned. class CRU_UI_API TextRenderObject : public RenderObject { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::TextRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"TextRenderObject") public: constexpr static float default_caret_width = 2; diff --git a/include/cru/ui/render/TreeRenderObject.h b/include/cru/ui/render/TreeRenderObject.h index 4a176926..8c589d7a 100644 --- a/include/cru/ui/render/TreeRenderObject.h +++ b/include/cru/ui/render/TreeRenderObject.h @@ -49,7 +49,7 @@ class CRU_UI_API TreeRenderObjectItem : public Object { }; class CRU_UI_API TreeRenderObject : public RenderObject { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render:TreeRenderObject") + CRU_DEFINE_CLASS_LOG_TAG(u"TreeRenderObject") public: TreeRenderObject(); diff --git a/include/cru/win/DebugLogger.h b/include/cru/win/DebugLogger.h index 6a7173ea..43e08f20 100644 --- a/include/cru/win/DebugLogger.h +++ b/include/cru/win/DebugLogger.h @@ -1,7 +1,7 @@ #pragma once #include "Base.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" namespace cru::platform::win { diff --git a/include/cru/win/StdOutLogger.h b/include/cru/win/StdOutLogger.h index 831d006f..d6009bb3 100644 --- a/include/cru/win/StdOutLogger.h +++ b/include/cru/win/StdOutLogger.h @@ -1,7 +1,7 @@ #pragma once #include "Base.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" namespace cru::platform::win { class CRU_WIN_API WinStdOutLoggerSource : public ::cru::log::ILogSource { diff --git a/include/cru/win/gui/Cursor.h b/include/cru/win/gui/Cursor.h index 7a9a2198..f9cb0a09 100644 --- a/include/cru/win/gui/Cursor.h +++ b/include/cru/win/gui/Cursor.h @@ -8,7 +8,7 @@ namespace cru::platform::gui::win { class CRU_WIN_GUI_API WinCursor : public WinNativeResource, public virtual ICursor { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinCursor") + CRU_DEFINE_CLASS_LOG_TAG(u"WinCursor") public: WinCursor(HCURSOR handle, bool auto_destroy); diff --git a/include/cru/win/gui/GodWindow.h b/include/cru/win/gui/GodWindow.h index 63051245..fe61c80d 100644 --- a/include/cru/win/gui/GodWindow.h +++ b/include/cru/win/gui/GodWindow.h @@ -9,7 +9,7 @@ namespace cru::platform::gui::win { class CRU_WIN_GUI_API GodWindow : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::GodWindow") + CRU_DEFINE_CLASS_LOG_TAG(u"GodWindow") public: explicit GodWindow(WinUiApplication* application); diff --git a/include/cru/win/gui/InputMethod.h b/include/cru/win/gui/InputMethod.h index 27a621be..8e28f857 100644 --- a/include/cru/win/gui/InputMethod.h +++ b/include/cru/win/gui/InputMethod.h @@ -12,7 +12,7 @@ namespace cru::platform::gui::win { class CRU_WIN_GUI_API AutoHIMC : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::AutoHIMC") + CRU_DEFINE_CLASS_LOG_TAG(u"AutoHIMC") public: explicit AutoHIMC(HWND hwnd); @@ -36,7 +36,7 @@ class CRU_WIN_GUI_API AutoHIMC : public Object { class CRU_WIN_GUI_API WinInputMethodContext : public WinNativeResource, public virtual IInputMethodContext { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinInputMethodContext") + CRU_DEFINE_CLASS_LOG_TAG(u"WinInputMethodContext") public: WinInputMethodContext(gsl::not_null<WinNativeWindow*> window); diff --git a/include/cru/win/gui/Window.h b/include/cru/win/gui/Window.h index fcbe1dbd..b279a434 100644 --- a/include/cru/win/gui/Window.h +++ b/include/cru/win/gui/Window.h @@ -11,7 +11,7 @@ namespace cru::platform::gui::win { class CRU_WIN_GUI_API WinNativeWindow : public WinNativeResource, public virtual INativeWindow { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinNativeWindow") + CRU_DEFINE_CLASS_LOG_TAG(u"WinNativeWindow") public: explicit WinNativeWindow(WinUiApplication* application); diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 706f0ed0..330c7226 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -2,13 +2,14 @@ add_library(cru_base SHARED Base.cpp Exception.cpp Format.cpp - Logger.cpp PropertyTree.cpp String.cpp StringUtil.cpp io/Stream.cpp io/Resource.cpp io/MemoryStream.cpp + log/Logger.cpp + log/StdioLogTarget.cpp platform/Exception.cpp ) target_compile_definitions(cru_base PRIVATE CRU_BASE_EXPORT_API) diff --git a/src/common/Format.cpp b/src/common/Format.cpp index 3362db65..d58c90b7 100644 --- a/src/common/Format.cpp +++ b/src/common/Format.cpp @@ -46,7 +46,7 @@ FormatToken ParsePlaceHolder(String place_holder_string) { } } -std::vector<FormatToken> ParseToFormatTokenList(const String& str) { +std::vector<FormatToken> ParseToFormatTokenList(StringView str) { std::vector<FormatToken> result; auto push_char = [&result](char16_t c) { diff --git a/src/common/Logger.cpp b/src/common/Logger.cpp deleted file mode 100644 index 49261396..00000000 --- a/src/common/Logger.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include "cru/common/Logger.h" - -#include <array> -#include <cstdlib> -#include <ctime> -#include <iostream> -#include <memory> -#include <mutex> -#include <string_view> - -namespace cru::log { -namespace { -Logger *CreateLogger() { - const auto logger = new Logger(); - return logger; -} -} // namespace - -Logger *Logger::GetInstance() { - static std::unique_ptr<Logger> logger{CreateLogger()}; - return logger.get(); -} - -void Logger::AddSource(std::unique_ptr<ILogSource> source) { - sources_.push_back(std::move(source)); -} - -void Logger::RemoveSource(ILogSource *source) { - sources_.remove_if([source](const std::unique_ptr<ILogSource> &s) { - return s.get() == source; - }); -} - -namespace { -String LogLevelToString(LogLevel level) { - switch (level) { - case LogLevel::Debug: - return u"DEBUG"; - case LogLevel::Info: - return u"INFO"; - case LogLevel::Warn: - return u"WARN"; - case LogLevel::Error: - return u"ERROR"; - default: - std::terminate(); - } -} - -String GetLogTime() { - auto time = std::time(nullptr); - auto calendar = std::localtime(&time); - return Format(u"{}:{}:{}", calendar->tm_hour, calendar->tm_min, - calendar->tm_sec); -} -} // namespace - -void Logger::Log(LogLevel level, StringView message) { -#ifndef CRU_DEBUG - if (level == LogLevel::Debug) { - return; - } -#endif - for (const auto &source : sources_) { - source->Write(level, Format(u"[{}] {}: {}\n", GetLogTime(), - LogLevelToString(level), message)); - } -} - -void Logger::Log(LogLevel level, StringView tag, StringView message) { -#ifndef CRU_DEBUG - if (level == LogLevel::Debug) { - return; - } -#endif - for (const auto &source : sources_) { - source->Write(level, Format(u"[{}] {} {}: {}\n", GetLogTime(), - LogLevelToString(level), tag, message)); - } -} - -namespace { -std::mutex stdio_lock; - -void WriteStdio(LogLevel level, StringView s) { - std::string m = s.ToString().ToUtf8(); - - if (level == LogLevel::Error) { - std::cerr << m; - } else { - std::cout << m; - } -} -} // namespace - -StdioLogSource::StdioLogSource(bool use_lock) : use_lock_(use_lock) {} - -StdioLogSource::~StdioLogSource() {} - -void StdioLogSource::Write(LogLevel level, StringView s) { - if (use_lock_) { - std::lock_guard<std::mutex> guard(stdio_lock); - WriteStdio(level, s); - } else { - WriteStdio(level, s); - } -} -} // namespace cru::log diff --git a/src/common/log/Logger.cpp b/src/common/log/Logger.cpp new file mode 100644 index 00000000..bcafde21 --- /dev/null +++ b/src/common/log/Logger.cpp @@ -0,0 +1,86 @@ +#include "cru/common/log/Logger.h" +#include "cru/common/log/StdioLogTarget.h" + +#include <array> +#include <cstdlib> +#include <ctime> + +namespace cru::log { +Logger *Logger::GetInstance() { + static Logger logger; + + logger.AddLogTarget(std::make_unique<StdioLogTarget>()); + + return &logger; +} + +void Logger::AddLogTarget(std::unique_ptr<ILogTarget> target) { + std::lock_guard<std::mutex> lock(target_list_mutex_); + target_list_.push_back(std::move(target)); +} + +void Logger::RemoveLogTarget(ILogTarget *target) { + std::lock_guard<std::mutex> lock(target_list_mutex_); + target_list_.erase( + std::remove_if(target_list_.begin(), target_list_.end(), + [target](const auto &t) { return t.get() == target; }), + target_list_.end()); +} + +namespace { +String LogLevelToString(LogLevel level) { + switch (level) { + case LogLevel::Debug: + return u"DEBUG"; + case LogLevel::Info: + return u"INFO"; + case LogLevel::Warn: + return u"WARN"; + case LogLevel::Error: + return u"ERROR"; + default: + std::terminate(); + } +} + +String GetLogTime() { + auto time = std::time(nullptr); + auto calendar = std::localtime(&time); + return Format(u"{}:{}:{}", calendar->tm_hour, calendar->tm_min, + calendar->tm_sec); +} + +String MakeLogFinalMessage(const LogInfo &log_info) { + if (log_info.tag.empty()) { + return Format(u"[{}] {}: {}", GetLogTime(), + LogLevelToString(log_info.level), log_info.message); + } else { + return Format(u"[{}] {} {}: {}", GetLogTime(), + LogLevelToString(log_info.level), log_info.tag, + log_info.message); + } +} +} // namespace + +Logger::Logger() + : log_thread_([this] { + while (true) { + auto log_info = log_queue_.Pull(); + std::lock_guard<std::mutex> lock_guard{target_list_mutex_}; + for (const auto &target : target_list_) { + target->Write(log_info.level, MakeLogFinalMessage(log_info)); + } + } + }) {} + +Logger::~Logger() {} + +void Logger::Log(LogInfo log_info) { +#ifndef CRU_DEBUG + if (log_info.level == LogLevel::Debug) { + return; + } +#endif + log_queue_.Push(std::move(log_info)); +} +} // namespace cru::log diff --git a/src/common/log/StdioLogTarget.cpp b/src/common/log/StdioLogTarget.cpp new file mode 100644 index 00000000..ad29a3ce --- /dev/null +++ b/src/common/log/StdioLogTarget.cpp @@ -0,0 +1,22 @@ +#include "cru/common/log/StdioLogTarget.h" + +#include <iostream> + +namespace cru::log { +StdioLogTarget::StdioLogTarget() {} + +StdioLogTarget::~StdioLogTarget() {} + +void StdioLogTarget::Write(log::LogLevel level, StringView s) { +#ifdef CRU_PLATFORM_WINDOWS +#else + std::string m = s.ToUtf8(); + + if (level == log::LogLevel::Error) { + std::cerr << m; + } else { + std::cout << m; + } +#endif +} +} // namespace cru::log diff --git a/src/osx/graphics/quartz/Painter.cpp b/src/osx/graphics/quartz/Painter.cpp index d74e456b..a8c3715a 100644 --- a/src/osx/graphics/quartz/Painter.cpp +++ b/src/osx/graphics/quartz/Painter.cpp @@ -1,6 +1,5 @@ #include "cru/osx/graphics/quartz/Painter.h" -#include "cru/common/Logger.h" #include "cru/osx/graphics/quartz/Brush.h" #include "cru/osx/graphics/quartz/Convert.h" #include "cru/osx/graphics/quartz/Geometry.h" @@ -27,10 +26,6 @@ QuartzCGContextPainter::QuartzCGContextPainter( transform_ = Matrix::Scale(1, -1) * Matrix::Translation(0, size.height); CGContextConcatCTM(cg_context_, Convert(transform_)); - - // log::TagDebug(log_tag, - // u"Created with CGContext: {}, Auto Release: {}, Size: {}.", - // cg_context, auto_release, size_); } QuartzCGContextPainter::~QuartzCGContextPainter() { @@ -61,8 +56,6 @@ void QuartzCGContextPainter::Clear(const Color& color) { color.GetFloatGreen(), color.GetFloatBlue(), color.GetFloatAlpha()); CGContextFillRect(cg_context_, Convert(Rect{Point{}, size_})); - - // log::TagDebug(log_tag, u"Clear with color {}, size {}.", color, size_); } void QuartzCGContextPainter::DrawLine(const Point& start, const Point& end, @@ -225,7 +218,6 @@ void QuartzCGContextPainter::DoEndDraw() { if (cg_context_) { CGContextFlush(cg_context_); CGContextSynchronize(cg_context_); - // log::TagDebug(log_tag, u"End draw and flush."); on_end_draw_(this); } diff --git a/src/osx/gui/Clipboard.mm b/src/osx/gui/Clipboard.mm index b37efce2..6e3fb076 100644 --- a/src/osx/gui/Clipboard.mm +++ b/src/osx/gui/Clipboard.mm @@ -1,7 +1,7 @@ #include "cru/osx/gui/Clipboard.h" #include "ClipboardPrivate.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/osx/Convert.h" #include <memory> @@ -27,7 +27,7 @@ OsxClipboardPrivate::~OsxClipboardPrivate() {} String OsxClipboardPrivate::GetText() { auto result = [pasteboard_ readObjectsForClasses:@[ NSString.class ] options:nil]; if (result == nil) { - log::TagWarn(log_tag, u"Failed to get text from clipboard"); + CRU_LOG_WARN(u"Failed to get text from clipboard"); return u""; } else { if (result.count == 0) { diff --git a/src/osx/gui/ClipboardPrivate.h b/src/osx/gui/ClipboardPrivate.h index 93fe5448..63145a64 100644 --- a/src/osx/gui/ClipboardPrivate.h +++ b/src/osx/gui/ClipboardPrivate.h @@ -7,8 +7,7 @@ namespace cru::platform::gui::osx { namespace details { class OsxClipboardPrivate : public Object { - CRU_DEFINE_CLASS_LOG_TAG( - u"cru::platform::gui::osx::details::OsxClipboardPrivate") + CRU_DEFINE_CLASS_LOG_TAG(u"OsxClipboardPrivate") public: explicit OsxClipboardPrivate(NSPasteboard* pasteboard); diff --git a/src/osx/gui/InputMethod.mm b/src/osx/gui/InputMethod.mm index 3a961209..2c19c358 100644 --- a/src/osx/gui/InputMethod.mm +++ b/src/osx/gui/InputMethod.mm @@ -3,7 +3,7 @@ #import <AppKit/AppKit.h> #include "InputMethodPrivate.h" #include "WindowPrivate.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/osx/Convert.h" #include "cru/osx/gui/Window.h" @@ -46,15 +46,9 @@ OsxInputMethodContext::OsxInputMethodContext(OsxWindow* window) OsxInputMethodContext::~OsxInputMethodContext() {} -void OsxInputMethodContext::EnableIME() { - // log::Debug(u"Enable IME."); - p_->Activate(); -} +void OsxInputMethodContext::EnableIME() { p_->Activate(); } -void OsxInputMethodContext::DisableIME() { - // log::Debug(u"Disable IME."); - p_->Deactivate(); -} +void OsxInputMethodContext::DisableIME() { p_->Deactivate(); } bool OsxInputMethodContext::ShouldManuallyDrawCompositionText() { return true; } diff --git a/src/osx/gui/UiApplication.mm b/src/osx/gui/UiApplication.mm index 20ce82d3..43c49c5c 100644 --- a/src/osx/gui/UiApplication.mm +++ b/src/osx/gui/UiApplication.mm @@ -1,7 +1,7 @@ #include "cru/osx/gui/UiApplication.h" #include "ClipboardPrivate.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/common/platform/osx/Convert.h" #include "cru/osx/graphics/quartz/Factory.h" #include "cru/osx/gui/Clipboard.h" @@ -80,9 +80,6 @@ OsxUiApplication::OsxUiApplication() : OsxGuiResource(this), p_(new details::OsxUiApplicationPrivate(this)) { [NSApplication sharedApplication]; - // Add stdio logger. - log::Logger::GetInstance()->AddSource(std::make_unique<log::StdioLogSource>()); - [NSApp setDelegate:p_->app_delegate_]; p_->quartz_graphics_factory_ = std::make_unique<graphics::osx::quartz::QuartzGraphicsFactory>(); p_->cursor_manager_ = std::make_unique<OsxCursorManager>(this); diff --git a/src/osx/gui/Window.mm b/src/osx/gui/Window.mm index 403ae030..8d15ef37 100644 --- a/src/osx/gui/Window.mm +++ b/src/osx/gui/Window.mm @@ -3,8 +3,8 @@ #include "CursorPrivate.h" #include "InputMethodPrivate.h" -#include "cru/common/Logger.h" #include "cru/common/Range.h" +#include "cru/common/log/Logger.h" #include "cru/osx/Convert.h" #include "cru/osx/graphics/quartz/Convert.h" #include "cru/osx/graphics/quartz/Painter.h" @@ -351,7 +351,6 @@ std::unique_ptr<graphics::IPainter> OsxWindow::BeginPaint() { return std::make_unique<cru::platform::graphics::osx::quartz::QuartzCGContextPainter>( GetUiApplication()->GetGraphicsFactory(), cg_context, false, GetClientSize(), [this](graphics::osx::quartz::QuartzCGContextPainter*) { - // log::Debug(u"Finish painting and invalidate view."); [[p_->window_ contentView] setNeedsDisplay:YES]; }); } @@ -470,7 +469,6 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)drawRect:(NSRect)dirtyRect { - // cru::log::TagDebug(u"CruView", u"Begin to draw layer in view."); auto cg_context = [[NSGraphicsContext currentContext] CGContext]; auto layer = _p->GetDrawLayer(); Ensures(layer); @@ -486,32 +484,26 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)mouseMoved:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse move."); _p->OnMouseMove(cru::platform::Point(event.locationInWindow.x, event.locationInWindow.y)); } - (void)mouseDragged:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse move."); _p->OnMouseMove(cru::platform::Point(event.locationInWindow.x, event.locationInWindow.y)); } - (void)rightMouseDragged:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse move."); _p->OnMouseMove(cru::platform::Point(event.locationInWindow.x, event.locationInWindow.y)); } - (void)mouseEntered:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse enter."); _p->OnMouseEnterLeave(cru::platform::gui::MouseEnterLeaveType::Enter); } - (void)mouseExited:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse exit."); _p->OnMouseEnterLeave(cru::platform::gui::MouseEnterLeaveType::Leave); } - (void)mouseDown:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse down."); [[self window] makeKeyWindow]; auto key_modifier = GetKeyModifier(event); @@ -521,8 +513,6 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)mouseUp:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse up."); - auto key_modifier = GetKeyModifier(event); cru::platform::Point p(event.locationInWindow.x, event.locationInWindow.y); @@ -530,8 +520,6 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)rightMouseDown:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved right mouse down."); - auto key_modifier = GetKeyModifier(event); cru::platform::Point p(event.locationInWindow.x, event.locationInWindow.y); @@ -539,8 +527,6 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)rightMouseUp:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved right mouse up."); - auto key_modifier = GetKeyModifier(event); cru::platform::Point p(event.locationInWindow.x, event.locationInWindow.y); @@ -548,8 +534,6 @@ cru::platform::gui::KeyModifier GetKeyModifier(NSEvent* event) { } - (void)scrollWheel:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved mouse wheel."); - auto key_modifier = GetKeyModifier(event); cru::platform::Point p(event.locationInWindow.x, event.locationInWindow.y); @@ -620,10 +604,6 @@ const std::unordered_set<KeyCode> input_context_handle_codes_when_has_text{ KeyCode::Right, KeyCode::Up, KeyCode::Down}; - (void)keyDown:(NSEvent*)event { - if constexpr (key_down_debug) { - cru::log::TagDebug(u"CruView", u"Recieved key down."); - } - auto key_modifier = GetKeyModifier(event); bool handled = false; @@ -655,15 +635,11 @@ const std::unordered_set<KeyCode> input_context_handle_codes_when_has_text{ if (!handled) { _p->OnKeyDown(c, key_modifier); - } else { - if constexpr (key_down_debug) { - cru::log::TagDebug(u"CruView", u"Key down is handled by input context."); - } } } - (void)keyUp:(NSEvent*)event { - // cru::log::TagDebug(u"CruView", u"Recieved key up."); + // cru::CRU_LOG_DEBUG(u"CruView", u"Recieved key up."); auto key_modifier = GetKeyModifier(event); auto c = cru::platform::gui::osx::KeyCodeFromOsxToCru(event.keyCode); @@ -698,7 +674,7 @@ const std::unordered_set<KeyCode> input_context_handle_codes_when_has_text{ auto ss = Convert(s); - // cru::log::TagDebug(u"CruView", + // cru::CRU_LOG_DEBUG(u"CruView", // u"Received setMarkedText string: {}, selected range: ({}, {}), " // u"replacement range: ({}, {}).", // ss, selectedRange.location, selectedRange.length, replacementRange.location, @@ -759,7 +735,7 @@ const std::unordered_set<KeyCode> input_context_handle_codes_when_has_text{ _input_context_p->SetCompositionText(cru::platform::gui::CompositionText()); cru::String ss = Convert(s); - // cru::log::TagDebug(u"CruView", u"Finish composition: {}, replacement range: ({}, {})", ss, + // cru::CRU_LOG_DEBUG(u"CruView", u"Finish composition: {}, replacement range: ({}, {})", ss, // replacementRange.location, replacementRange.length); _input_context_p->RaiseCompositionEvent(); diff --git a/src/ui/controls/TextHostControlService.cpp b/src/ui/controls/TextHostControlService.cpp index 81365a8b..15d9102c 100644 --- a/src/ui/controls/TextHostControlService.cpp +++ b/src/ui/controls/TextHostControlService.cpp @@ -2,7 +2,7 @@ #include "../Helper.h" #include "cru/common/Base.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/common/String.h" #include "cru/common/StringUtil.h" #include "cru/platform/graphics/Font.h" @@ -226,7 +226,7 @@ void TextHostControlService::SetText(String text, bool stop_composition) { void TextHostControlService::InsertText(gsl::index position, StringView text, bool stop_composition) { if (!Utf16IsValidInsertPosition(this->text_, position)) { - log::TagError(log_tag, u"Invalid text insert position."); + CRU_LOG_ERROR(u"Invalid text insert position."); return; } this->text_.insert(this->text_.cbegin() + position, text); @@ -240,7 +240,7 @@ void TextHostControlService::InsertText(gsl::index position, StringView text, void TextHostControlService::DeleteChar(gsl::index position, bool stop_composition) { if (!Utf16IsValidInsertPosition(this->text_, position)) { - log::TagError(log_tag, u"Invalid text delete position."); + CRU_LOG_ERROR(u"Invalid text delete position."); return; } if (position == static_cast<gsl::index>(this->text_.size())) return; @@ -253,7 +253,7 @@ void TextHostControlService::DeleteChar(gsl::index position, gsl::index TextHostControlService::DeleteCharPrevious(gsl::index position, bool stop_composition) { if (!Utf16IsValidInsertPosition(this->text_, position)) { - log::TagError(log_tag, u"Invalid text delete position."); + CRU_LOG_ERROR(u"Invalid text delete position."); return 0; } if (position == 0) return 0; @@ -269,11 +269,11 @@ void TextHostControlService::DeleteText(TextRange range, if (range.count == 0) return; range = range.Normalize(); if (!Utf16IsValidInsertPosition(this->text_, range.GetStart())) { - log::TagError(log_tag, u"Invalid text delete start position."); + CRU_LOG_ERROR(u"Invalid text delete start position."); return; } if (!Utf16IsValidInsertPosition(this->text_, range.GetStart())) { - log::TagError(log_tag, u"Invalid text delete end position."); + CRU_LOG_ERROR(u"Invalid text delete end position."); return; } this->text_.erase(this->text_.cbegin() + range.GetStart(), @@ -465,7 +465,7 @@ void TextHostControlService::UpdateInputMethodPosition() { right_bottom.y += 5; if constexpr (debug_flags::text_service) { - log::TagDebug(log_tag, + CRU_LOG_DEBUG( u"Calculate input method candidate window position: {}.", right_bottom); } diff --git a/src/ui/helper/ClickDetector.cpp b/src/ui/helper/ClickDetector.cpp index a10133e9..8ebdfabc 100644 --- a/src/ui/helper/ClickDetector.cpp +++ b/src/ui/helper/ClickDetector.cpp @@ -1,6 +1,6 @@ #include "cru/ui/helper/ClickDetector.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/DebugFlags.h" #include "cru/ui/controls/Control.h" #include "cru/ui/host/WindowHost.h" @@ -58,7 +58,7 @@ ClickDetector::ClickDetector(controls::Control* control) { this->state_ == ClickState::Hover) { if (!this->control_->CaptureMouse()) { if constexpr (debug_flags::click_detector) { - log::TagDebug(log_tag, + CRU_LOG_DEBUG( u"Failed to capture mouse when begin click."); } return; @@ -136,7 +136,7 @@ void ClickDetector::SetState(ClickState state) { UnreachableCode(); } }; - log::TagDebug(log_tag, u"Click state changed, new state: {}.", + CRU_LOG_DEBUG(u"Click state changed, new state: {}.", to_string(state)); } diff --git a/src/ui/helper/ShortcutHub.cpp b/src/ui/helper/ShortcutHub.cpp index 3df07409..8fbf0b8d 100644 --- a/src/ui/helper/ShortcutHub.cpp +++ b/src/ui/helper/ShortcutHub.cpp @@ -1,6 +1,6 @@ #include "cru/ui/helper/ShortcutHub.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/DebugFlags.h" #include "cru/ui/controls/Control.h" @@ -64,7 +64,7 @@ const std::vector<ShortcutInfo>& ShortcutHub::GetShortcutByKeyBind( void ShortcutHub::Install(controls::Control* control) { if (!event_guard_.IsEmpty()) { - log::Error(u"Shortcut hub is already installed. Failed to install."); + CRU_LOG_ERROR(u"Shortcut hub is already installed. Failed to install."); return; } @@ -74,7 +74,7 @@ void ShortcutHub::Install(controls::Control* control) { void ShortcutHub::Uninstall() { if (event_guard_.IsEmpty()) { - log::Warn(u"Shortcut hub is not installed. Failed to uninstall."); + CRU_LOG_WARN(u"Shortcut hub is not installed. Failed to uninstall."); return; } @@ -89,17 +89,17 @@ void ShortcutHub::OnKeyDown(events::KeyEventArgs& event) { if constexpr (debug_flags::shortcut) { if (shortcut_list.empty()) { - log::Debug(u"No shortcut for key bind {}.", key_bind.ToString()); + CRU_LOG_DEBUG(u"No shortcut for key bind {}.", key_bind.ToString()); } - log::Debug(u"Begin to handle shortcut for key bind {}.", - key_bind.ToString()); + CRU_LOG_DEBUG(u"Begin to handle shortcut for key bind {}.", + key_bind.ToString()); } for (const auto& shortcut : shortcut_list) { auto is_handled = shortcut.handler(); if (is_handled) { if constexpr (debug_flags::shortcut) { - log::Debug(u"Handle {} handled it.", shortcut.name); + CRU_LOG_DEBUG(u"Handle {} handled it.", shortcut.name); } handled = true; @@ -108,22 +108,23 @@ void ShortcutHub::OnKeyDown(events::KeyEventArgs& event) { break; } else { if constexpr (debug_flags::shortcut) { - log::Debug(u"Handle {} didn't handle it.", shortcut.name); + CRU_LOG_DEBUG(u"Handle {} didn't handle it.", shortcut.name); } } } if constexpr (debug_flags::shortcut) { if (!shortcut_list.empty()) { - log::Debug(u"End handling shortcut for key bind {}.", - key_bind.ToString()); + CRU_LOG_DEBUG(u"End handling shortcut for key bind {}.", + key_bind.ToString()); } } if (!handled) { if constexpr (debug_flags::shortcut) { - log::Debug(u"Raise fallback event for unhandled shortcut of key bind {}.", - key_bind.ToString()); + CRU_LOG_DEBUG( + u"Raise fallback event for unhandled shortcut of key bind {}.", + key_bind.ToString()); } fallback_event_.Raise(event); } diff --git a/src/ui/host/RoutedEventDispatch.h b/src/ui/host/RoutedEventDispatch.h index 2ab51645..3c2a98d8 100644 --- a/src/ui/host/RoutedEventDispatch.h +++ b/src/ui/host/RoutedEventDispatch.h @@ -1,5 +1,5 @@ #pragma once -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/DebugFlags.h" #include "cru/ui/controls/Control.h" @@ -21,18 +21,19 @@ namespace cru::ui { // as the rest arguments. template <typename EventArgs, typename... Args> void DispatchEvent( - const std::u16string_view& event_name, - controls::Control* const original_sender, + const String& event_name, controls::Control* const original_sender, events::RoutedEvent<EventArgs>* (controls::Control::*event_ptr)(), controls::Control* const last_receiver, Args&&... args) { + constexpr auto kLogTag = u"DispatchEvent"; + if (original_sender == nullptr) return; CRU_UNUSED(event_name) if (original_sender == last_receiver) { if constexpr (debug_flags::routed_event) - log::Debug( - "Routed event {} no need to dispatch (original_sender == " + CRU_LOG_DEBUG( + u"Routed event {} no need to dispatch (original_sender == " "last_receiver). Original sender is {}.", event_name, original_sender->GetControlType()); return; @@ -49,7 +50,7 @@ void DispatchEvent( } if constexpr (debug_flags::routed_event) { - std::u16string log = u"Dispatch routed event "; + String log = u"Dispatch routed event "; log += event_name; log += u". Path (parent first): "; auto i = receive_list.crbegin(); @@ -59,7 +60,7 @@ void DispatchEvent( log += u" -> "; } log += (*i)->GetControlType(); - log::Debug(log); + CRU_LOG_DEBUG(log); } auto handled = false; @@ -75,7 +76,7 @@ void DispatchEvent( if (event_args.IsHandled()) { handled = true; if constexpr (debug_flags::routed_event) - log::Debug( + CRU_LOG_DEBUG( u"Routed event is short-circuit in TUNNEL at {}-st control (count " u"from parent).", count); @@ -92,7 +93,7 @@ void DispatchEvent( ->Raise(event_args); if (event_args.IsHandled()) { if constexpr (debug_flags::routed_event) - log::Debug( + CRU_LOG_DEBUG( u"Routed event is short-circuit in BUBBLE at {}-st control " u"(count from parent).", count); @@ -109,6 +110,6 @@ void DispatchEvent( } if constexpr (debug_flags::routed_event) - log::Debug(u"Routed event dispatch finished."); + CRU_LOG_DEBUG(u"Routed event dispatch finished."); } } // namespace cru::ui diff --git a/src/ui/host/WindowHost.cpp b/src/ui/host/WindowHost.cpp index 91b5f438..42d0945f 100644 --- a/src/ui/host/WindowHost.cpp +++ b/src/ui/host/WindowHost.cpp @@ -2,7 +2,7 @@ #include "RoutedEventDispatch.h" #include "cru/common/Base.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/graphics/Painter.h" #include "cru/platform/gui/InputMethod.h" #include "cru/platform/gui/UiApplication.h" @@ -191,7 +191,7 @@ void WindowHost::RelayoutWithSize(const Size& available_size, after_layout_event_.Raise(AfterLayoutEventArgs{}); after_layout_stable_action_.clear(); if constexpr (debug_flags::layout) - log::TagDebug(log_tag, u"A relayout is finished."); + CRU_LOG_DEBUG(u"A relayout is finished."); } void WindowHost::Repaint() { diff --git a/src/ui/mapper/BorderStyleMapper.cpp b/src/ui/mapper/BorderStyleMapper.cpp index 8daa9d1b..3dea0776 100644 --- a/src/ui/mapper/BorderStyleMapper.cpp +++ b/src/ui/mapper/BorderStyleMapper.cpp @@ -1,6 +1,6 @@ #include "cru/ui/mapper/BorderStyleMapper.h" #include "../Helper.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/graphics/Brush.h" #include "cru/platform/graphics/Factory.h" #include "cru/ui/mapper/MapperRegistry.h" @@ -21,7 +21,6 @@ ApplyBorderStyleInfo BorderStyleMapper::DoMapFromXml( for (auto child : node->GetChildren()) { if (child->GetType() == XmlNode::Type::Text) { - log::Debug(u"Ignore text node."); } else { auto c = child->AsElement(); auto thickness_mapper = @@ -43,7 +42,6 @@ ApplyBorderStyleInfo BorderStyleMapper::DoMapFromXml( } else if (name->CaseInsensitiveCompare(u"background") == 0) { result.background_brush = std::move(brush); } else { - log::Debug(u"Unknown brush name: {}", *name); } } else { result.border_brush = std::move(brush); diff --git a/src/ui/render/BorderRenderObject.cpp b/src/ui/render/BorderRenderObject.cpp index 30493a49..cbea4b81 100644 --- a/src/ui/render/BorderRenderObject.cpp +++ b/src/ui/render/BorderRenderObject.cpp @@ -1,7 +1,7 @@ #include "cru/ui/render/BorderRenderObject.h" #include "../Helper.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/graphics/Factory.h" #include "cru/platform/graphics/Geometry.h" #include "cru/platform/graphics/Painter.h" @@ -80,8 +80,8 @@ RenderObject* BorderRenderObject::HitTest(const Point& point) { void BorderRenderObject::Draw(platform::graphics::IPainter* painter) { if constexpr (debug_flags::draw) { - log::TagDebug( - log_tag, u"BorderRenderObject draw, background: {}, foreground: {}.", + CRU_LOG_DEBUG( + u"BorderRenderObject draw, background: {}, foreground: {}.", background_brush_ == nullptr ? u"NONE" : background_brush_->GetDebugString(), foreground_brush_ == nullptr ? u"NONE" @@ -94,7 +94,7 @@ void BorderRenderObject::Draw(platform::graphics::IPainter* painter) { if (is_border_enabled_) { if (border_brush_ == nullptr) { - log::TagWarn(log_tag, u"Border is enabled but border brush is null."); + CRU_LOG_WARN(u"Border is enabled but border brush is null."); } else { painter->FillGeometry(geometry_.get(), border_brush_.get()); } diff --git a/src/ui/render/FlexLayoutRenderObject.cpp b/src/ui/render/FlexLayoutRenderObject.cpp index 0699768a..988e7590 100644 --- a/src/ui/render/FlexLayoutRenderObject.cpp +++ b/src/ui/render/FlexLayoutRenderObject.cpp @@ -1,6 +1,6 @@ #include "cru/ui/render/FlexLayoutRenderObject.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/render/LayoutHelper.h" #include <algorithm> @@ -90,7 +90,7 @@ Size FlexLayoutMeasureContentImpl( const MeasureRequirement& requirement, const MeasureSize& preferred_size, const std::vector<RenderObject*>& children, const std::vector<FlexChildLayoutData>& layout_data, - Alignment item_cross_align, StringView log_tag) { + Alignment item_cross_align, String kLogTag) { Expects(children.size() == layout_data.size()); direction_tag_t direction_tag; @@ -300,8 +300,7 @@ Size FlexLayoutMeasureContentImpl( if (max_main_length.IsSpecified() && total_length > max_main_length.GetLengthOrUndefined()) { - log::TagWarn( - log_tag, + CRU_LOG_WARN( u"(Measure) Children's main axis length exceeds required max length."); total_length = max_main_length.GetLengthOrUndefined(); } else if (min_main_length.IsSpecified() && @@ -345,11 +344,11 @@ Size FlexLayoutRenderObject::OnMeasureContent( if (horizontal) { return FlexLayoutMeasureContentImpl<tag_horizontal_t>( requirement, preferred_size, children, layout_data_list, - item_cross_align_, log_tag); + item_cross_align_, kLogTag); } else { return FlexLayoutMeasureContentImpl<tag_vertical_t>( requirement, preferred_size, children, layout_data_list, - item_cross_align_, log_tag); + item_cross_align_, kLogTag); } } diff --git a/src/ui/render/LayoutHelper.cpp b/src/ui/render/LayoutHelper.cpp index 7a82bb2d..a9121321 100644 --- a/src/ui/render/LayoutHelper.cpp +++ b/src/ui/render/LayoutHelper.cpp @@ -1,6 +1,6 @@ #include "cru/ui/render/LayoutHelper.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" namespace cru::ui::render { float CalculateAnchorByAlignment(Alignment alignment, float start_point, diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index 6c09ce99..b6de5782 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -1,6 +1,6 @@ #include "cru/ui/render/RenderObject.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/DebugFlags.h" #include "cru/ui/controls/Control.h" #include "cru/ui/host/WindowHost.h" @@ -80,16 +80,16 @@ void RenderObject::Measure(const MeasureRequirement& requirement, preferred_size.OverrideBy(preferred_size_); if constexpr (cru::ui::debug_flags::layout) { - log::Debug(u"{} Measure begins :\nrequirement: {}\npreferred size: {}", - this->GetDebugPathInTree(), requirement.ToDebugString(), - preferred_size.ToDebugString()); + CRU_LOG_DEBUG(u"{} Measure begins :\nrequirement: {}\npreferred size: {}", + this->GetDebugPathInTree(), requirement.ToDebugString(), + preferred_size.ToDebugString()); } desired_size_ = OnMeasureCore(merged_requirement, merged_preferred_size); if constexpr (cru::ui::debug_flags::layout) { - log::Debug(u"{} Measure ends :\nresult size: {}", - this->GetDebugPathInTree(), desired_size_); + CRU_LOG_DEBUG(u"{} Measure ends :\nresult size: {}", + this->GetDebugPathInTree(), desired_size_); } Ensures(desired_size_.width >= 0); @@ -98,8 +98,8 @@ void RenderObject::Measure(const MeasureRequirement& requirement, void RenderObject::Layout(const Point& offset) { if constexpr (cru::ui::debug_flags::layout) { - log::Debug(u"{} Layout :\noffset: {} size: {}", this->GetDebugPathInTree(), - offset, desired_size_); + CRU_LOG_DEBUG(u"{} Layout :\noffset: {} size: {}", + this->GetDebugPathInTree(), offset, desired_size_); } offset_ = offset; size_ = desired_size_; diff --git a/src/ui/render/StackLayoutRenderObject.cpp b/src/ui/render/StackLayoutRenderObject.cpp index fda9a420..9ca9bf02 100644 --- a/src/ui/render/StackLayoutRenderObject.cpp +++ b/src/ui/render/StackLayoutRenderObject.cpp @@ -1,6 +1,6 @@ #include "cru/ui/render/StackLayoutRenderObject.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/ui/render/LayoutHelper.h" #include "cru/ui/render/MeasureRequirement.h" diff --git a/src/ui/render/TextRenderObject.cpp b/src/ui/render/TextRenderObject.cpp index 82f314bd..0b9009c5 100644 --- a/src/ui/render/TextRenderObject.cpp +++ b/src/ui/render/TextRenderObject.cpp @@ -1,7 +1,7 @@ #include "cru/ui/render/TextRenderObject.h" #include "../Helper.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/graphics/Factory.h" #include "cru/platform/graphics/Painter.h" #include "cru/platform/graphics/TextLayout.h" @@ -176,12 +176,11 @@ RenderObject* TextRenderObject::HitTest(const Point& point) { void TextRenderObject::Draw(platform::graphics::IPainter* painter) { if constexpr (debug_flags::draw) { - log::TagDebug(log_tag, - u"Begin to paint, total_offset: {}, size: {}, text_layout: " - u"{}, brush: {}.", - this->GetTotalOffset(), this->GetDesiredSize(), - this->text_layout_->GetDebugString(), - this->brush_->GetDebugString()); + CRU_LOG_DEBUG( + u"Begin to paint, total_offset: {}, size: {}, text_layout: " + u"{}, brush: {}.", + this->GetTotalOffset(), this->GetDesiredSize(), + this->text_layout_->GetDebugString(), this->brush_->GetDebugString()); } if (this->selection_range_.has_value()) { diff --git a/src/win/graphics/direct/Factory.cpp b/src/win/graphics/direct/Factory.cpp index b948c040..e8b3f107 100644 --- a/src/win/graphics/direct/Factory.cpp +++ b/src/win/graphics/direct/Factory.cpp @@ -1,6 +1,6 @@ #include "cru/win/graphics/direct/Factory.h" -#include "cru/common/Logger.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" diff --git a/src/win/graphics/direct/TextLayout.cpp b/src/win/graphics/direct/TextLayout.cpp index 14e2d3aa..ffef5e0c 100644 --- a/src/win/graphics/direct/TextLayout.cpp +++ b/src/win/graphics/direct/TextLayout.cpp @@ -1,7 +1,7 @@ #include "cru/win/graphics/direct/TextLayout.h" #include <dwrite.h> -#include "cru/common/Logger.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" diff --git a/src/win/gui/Clipboard.cpp b/src/win/gui/Clipboard.cpp index 6bb5d1c5..7ecc9dea 100644 --- a/src/win/gui/Clipboard.cpp +++ b/src/win/gui/Clipboard.cpp @@ -1,6 +1,6 @@ #include "cru/win/gui/Clipboard.h" #include <winuser.h> -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/win/gui/GodWindow.h" #include "cru/win/gui/UiApplication.h" diff --git a/src/win/gui/Cursor.cpp b/src/win/gui/Cursor.cpp index 1d421b59..d85ba565 100644 --- a/src/win/gui/Cursor.cpp +++ b/src/win/gui/Cursor.cpp @@ -1,6 +1,6 @@ #include "cru/win/gui/Cursor.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/win/gui/Exception.h" #include <stdexcept> @@ -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, u"Failed to destroy a cursor. Last error code: {}", + CRU_LOG_WARN(u"Failed to destroy a cursor. Last error code: {}", ::GetLastError()); } } diff --git a/src/win/gui/GodWindow.cpp b/src/win/gui/GodWindow.cpp index 0c385bea..4416870f 100644 --- a/src/win/gui/GodWindow.cpp +++ b/src/win/gui/GodWindow.cpp @@ -1,6 +1,6 @@ #include "cru/win/gui/GodWindow.h" -#include "cru/common/Logger.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" @@ -43,7 +43,7 @@ GodWindow::GodWindow(WinUiApplication* application) { GodWindow::~GodWindow() { if (!::DestroyWindow(hwnd_)) { // Although this could be "safely" ignore. - log::TagWarn(log_tag, u"Failed to destroy god window."); + CRU_LOG_WARN(u"Failed to destroy god window."); } } diff --git a/src/win/gui/InputMethod.cpp b/src/win/gui/InputMethod.cpp index fedb72fe..8a54577b 100644 --- a/src/win/gui/InputMethod.cpp +++ b/src/win/gui/InputMethod.cpp @@ -1,6 +1,6 @@ #include "cru/win/gui/InputMethod.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/common/StringUtil.h" #include "cru/platform/Check.h" #include "cru/platform/gui/DebugFlags.h" @@ -35,7 +35,7 @@ AutoHIMC& AutoHIMC::operator=(AutoHIMC&& other) { AutoHIMC::~AutoHIMC() { if (handle_) { if (!::ImmReleaseContext(hwnd_, handle_)) - log::TagWarn(log_tag, u"Failed to release HIMC."); + CRU_LOG_WARN(u"Failed to release HIMC."); } } @@ -157,7 +157,7 @@ WinInputMethodContext::~WinInputMethodContext() {} void WinInputMethodContext::EnableIME() { const auto hwnd = native_window_->GetWindowHandle(); if (::ImmAssociateContextEx(hwnd, nullptr, IACE_DEFAULT) == FALSE) { - log::TagWarn(log_tag, u"Failed to enable ime."); + CRU_LOG_WARN(u"Failed to enable ime."); } } @@ -168,21 +168,21 @@ void WinInputMethodContext::DisableIME() { ::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0); if (::ImmAssociateContextEx(hwnd, nullptr, 0) == FALSE) { - log::TagWarn(log_tag, u"Failed to disable ime."); + CRU_LOG_WARN(u"Failed to disable ime."); } } void WinInputMethodContext::CompleteComposition() { auto himc = GetHIMC(); if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) { - log::TagWarn(log_tag, u"Failed to complete composition."); + CRU_LOG_WARN(u"Failed to complete composition."); } } void WinInputMethodContext::CancelComposition() { auto himc = GetHIMC(); if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0)) { - log::TagWarn(log_tag, u"Failed to complete composition."); + CRU_LOG_WARN(u"Failed to complete composition."); } } @@ -201,7 +201,7 @@ void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) { form.ptCurrentPos = native_window_->DipToPixel(point); if (!::ImmSetCandidateWindow(himc.Get(), &form)) - log::TagDebug(log_tag, + CRU_LOG_DEBUG( u"Failed to set input method candidate window position."); } @@ -229,7 +229,7 @@ void WinInputMethodContext::OnWindowNativeMessage( // 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, + CRU_LOG_WARN( u"A WM_CHAR message for character from supplementary " u"planes is ignored."); } else { @@ -247,7 +247,7 @@ void WinInputMethodContext::OnWindowNativeMessage( composition_event_.Raise(nullptr); auto composition_text = GetCompositionText(); if constexpr (DebugFlags::input_method) { - log::TagDebug(log_tag, u"WM_IME_COMPOSITION composition text:\n{}", + CRU_LOG_DEBUG(u"WM_IME_COMPOSITION composition text:\n{}", composition_text); } if (message.l_param & GCS_RESULTSTR) { @@ -258,14 +258,14 @@ void WinInputMethodContext::OnWindowNativeMessage( } case WM_IME_STARTCOMPOSITION: { if constexpr (DebugFlags::input_method) { - log::TagDebug(log_tag, u"WM_IME_STARTCOMPOSITION received."); + CRU_LOG_DEBUG(u"WM_IME_STARTCOMPOSITION received."); } composition_start_event_.Raise(nullptr); break; } case WM_IME_ENDCOMPOSITION: { if constexpr (DebugFlags::input_method) { - log::TagDebug(log_tag, u"WM_IME_ENDCOMPOSITION received."); + CRU_LOG_DEBUG(u"WM_IME_ENDCOMPOSITION received."); } composition_end_event_.Raise(nullptr); break; diff --git a/src/win/gui/UiApplication.cpp b/src/win/gui/UiApplication.cpp index 59076a9c..8c2dfae7 100644 --- a/src/win/gui/UiApplication.cpp +++ b/src/win/gui/UiApplication.cpp @@ -2,7 +2,7 @@ #include "TimerManager.h" #include "WindowManager.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/Check.h" #include "cru/win/DebugLogger.h" #include "cru/win/StdOutLogger.h" diff --git a/src/win/gui/Window.cpp b/src/win/gui/Window.cpp index ada3d59f..9c86441e 100644 --- a/src/win/gui/Window.cpp +++ b/src/win/gui/Window.cpp @@ -1,7 +1,7 @@ #include "cru/win/gui/Window.h" #include "WindowManager.h" -#include "cru/common/Logger.h" +#include "cru/common/log/Logger.h" #include "cru/platform/Check.h" #include "cru/platform/graphics/NullPainter.h" #include "cru/platform/gui/Base.h" @@ -207,7 +207,7 @@ bool WinNativeWindow::ReleaseMouse() { void WinNativeWindow::RequestRepaint() { if constexpr (DebugFlags::paint) { - log::TagDebug(log_tag, u"A repaint is requested."); + CRU_LOG_DEBUG(u"A repaint is requested."); } if (!::InvalidateRect(hwnd_, nullptr, FALSE)) throw Win32Error(::GetLastError(), u"Failed to invalidate window."); @@ -234,7 +234,7 @@ void WinNativeWindow::SetCursor(std::shared_ptr<ICursor> cursor) { if (!::SetClassLongPtrW(hwnd_, GCLP_HCURSOR, reinterpret_cast<LONG_PTR>(cursor_->GetHandle()))) { - log::TagWarn(log_tag, + CRU_LOG_WARN( u"Failed to set cursor because failed to set class long. Last " u"error code: {}.", ::GetLastError()); @@ -244,8 +244,8 @@ void WinNativeWindow::SetCursor(std::shared_ptr<ICursor> cursor) { if (GetVisibility() != WindowVisibilityType::Show) return; auto lg = [](StringView reason) { - log::TagWarn( - log_tag, + 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()); @@ -507,7 +507,7 @@ void WinNativeWindow::OnPaintInternal() { paint_event_.Raise(nullptr); ValidateRect(hwnd_, nullptr); if constexpr (DebugFlags::paint) { - log::TagDebug(log_tag, u"A repaint is finished."); + CRU_LOG_DEBUG(u"A repaint is finished."); } } |