From c84b89b4826b64b05a176eb15725ba526495c6a1 Mon Sep 17 00:00:00 2001 From: David Capello Date: Sat, 14 Dec 2024 00:15:21 -0300 Subject: [PATCH] clang-format all files --- base/24bits.h | 26 +- base/base.h | 18 +- base/base64.cpp | 23 +- base/base64.h | 21 +- base/base64_tests.cpp | 12 +- base/cfile.cpp | 24 +- base/cfile.h | 20 +- base/chrono.cpp | 78 +-- base/chrono.h | 54 +- base/chrono_unix.h | 55 +- base/chrono_win32.h | 62 +- base/concurrent_queue.h | 124 ++-- base/convert_to.cpp | 61 +- base/convert_to.h | 56 +- base/count_bits.h | 19 +- base/count_bits_tests.cpp | 2 +- base/debug.cpp | 44 +- base/debug.h | 63 +- base/disable_copying.h | 4 +- base/dll.cpp | 2 +- base/dll.h | 3 +- base/dll_win32.h | 8 +- base/enum_flags.h | 67 ++- base/enum_flags_tests.cpp | 14 +- base/errno_string.cpp | 86 ++- base/exception.cpp | 2 +- base/exception.h | 26 +- base/file_content.cpp | 8 +- base/file_content.h | 40 +- base/file_content_tests.cpp | 4 +- base/file_handle.cpp | 33 +- base/file_handle.h | 21 +- base/file_handle_tests.cpp | 52 +- base/fs.cpp | 67 +-- base/fs.h | 171 +++--- base/fs_osx.mm | 6 +- base/fs_tests.cpp | 269 +++++---- base/fs_unix.h | 45 +- base/fs_win32.h | 60 +- base/gcd.h | 35 +- base/hex.h | 25 +- base/launcher.cpp | 60 +- base/launcher.h | 6 +- base/log.cpp | 6 +- base/log.h | 29 +- base/mask_shift.h | 21 +- base/mem_utils.cpp | 10 +- base/mem_utils.h | 2 +- base/memory.cpp | 73 +-- base/memory.h | 30 +- base/memory_dump.cpp | 5 +- base/memory_dump_none.h | 12 +- base/memory_dump_win32.h | 45 +- base/paths.h | 2 +- base/pi.h | 19 +- base/pi_tests.cpp | 14 +- base/platform.cpp | 31 +- base/platform.h | 34 +- base/platform_osx.mm | 2 +- base/platform_unix.cpp | 13 +- base/platform_win.cpp | 18 +- base/process.cpp | 15 +- base/process.h | 16 +- base/program_options.cpp | 82 ++- base/program_options.h | 188 +++--- base/program_options_tests.cpp | 11 +- base/ref.h | 334 ++++++----- base/ref_tests.cpp | 2 +- base/remove_from_container.h | 6 +- base/replace_string.cpp | 11 +- base/replace_string.h | 7 +- base/replace_string_tests.cpp | 3 +- base/rw_lock.cpp | 27 +- base/rw_lock.h | 149 +++-- base/rw_lock_tests.cpp | 6 +- base/scoped_value.h | 55 +- base/serialization.cpp | 53 +- base/serialization.h | 74 ++- base/sha1.cpp | 8 +- base/sha1.h | 42 +- base/sha1_rfc3174.c | 391 ++++++------ base/sha1_rfc3174.h | 43 +- base/split_string.cpp | 35 +- base/split_string.h | 6 +- base/string.cpp | 55 +- base/string.h | 25 +- base/string_tests.cpp | 56 +- base/system_console.cpp | 34 +- base/system_console.h | 3 +- base/task.cpp | 10 +- base/task.h | 127 ++-- base/task_tests.cpp | 12 +- base/thread.cpp | 26 +- base/thread.h | 6 +- base/thread_pool.cpp | 24 +- base/thread_pool.h | 42 +- base/thread_pool_tests.cpp | 4 +- base/thread_tests.cpp | 3 +- base/time.cpp | 34 +- base/time.h | 100 ++-- base/time_tests.cpp | 15 +- base/tok.h | 50 +- base/tok_tests.cpp | 6 +- base/trim_string.h | 14 +- base/utf8_decode.h | 152 +++-- base/uuid.h | 28 +- base/uuid_osx.mm | 2 +- base/uuid_tests.cpp | 8 +- base/uuid_unix.cpp | 9 +- base/uuid_win.cpp | 10 +- base/vector2d.h | 134 +++-- base/version.cpp | 36 +- base/version.h | 48 +- base/version_tests.cpp | 11 +- base/win/comptr.h | 114 ++-- base/win/registry.cpp | 438 +++++++------- base/win/registry.h | 134 ++--- base/win/registry_tests.cpp | 6 +- base/win/ver_query_values.cpp | 54 +- base/win/win32_exception.cpp | 19 +- base/win/win32_exception.h | 18 +- examples/allevents.cpp | 114 ++-- examples/base64.cpp | 2 +- examples/complextextlayout.cpp | 45 +- examples/custom_window.cpp | 128 ++-- examples/drag_and_drop.cpp | 42 +- examples/floating_window.cpp | 92 ++- examples/hello_laf.cpp | 37 +- examples/listfonts.cpp | 40 +- examples/listscreens.cpp | 13 +- examples/multiple_windows.cpp | 55 +- examples/panviewport.cpp | 72 +-- examples/shader.cpp | 37 +- examples/show_platform.cpp | 29 +- ft/algorithm.h | 239 ++++---- ft/face.h | 326 +++++----- ft/hb_face.h | 33 +- ft/hb_shaper.h | 177 +++--- ft/lib.cpp | 3 +- ft/lib.h | 20 +- ft/stream.cpp | 4 +- gfx/border.h | 126 ++-- gfx/border_io.h | 54 +- gfx/clip.h | 310 +++++----- gfx/clip_tests.cpp | 13 +- gfx/color.h | 71 ++- gfx/color_space.cpp | 58 +- gfx/color_space.h | 196 +++--- gfx/fwd.h | 15 +- gfx/hsl.cpp | 15 +- gfx/hsl.h | 33 +- gfx/hsl_tests.cpp | 42 +- gfx/hsv.cpp | 13 +- gfx/hsv.h | 36 +- gfx/hsv_tests.cpp | 41 +- gfx/matrix_none.h | 93 +-- gfx/matrix_skia.h | 227 +++---- gfx/packing_rects.cpp | 34 +- gfx/packing_rects.h | 68 +-- gfx/packing_rects_tests.cpp | 10 +- gfx/path_none.h | 44 +- gfx/path_skia.h | 195 +++--- gfx/point.h | 80 ++- gfx/point_io.h | 35 +- gfx/rect.h | 280 ++++----- gfx/rect_io.h | 41 +- gfx/rect_tests.cpp | 131 ++-- gfx/region.h | 2 +- gfx/region_pixman.cpp | 18 +- gfx/region_pixman.h | 215 ++++--- gfx/region_skia.cpp | 14 +- gfx/region_skia.h | 231 +++---- gfx/region_tests.cpp | 31 +- gfx/region_win.cpp | 17 +- gfx/region_win.h | 212 ++++--- gfx/rgb.cpp | 26 +- gfx/rgb.h | 55 +- gfx/rgb_tests.cpp | 38 +- gfx/size.h | 96 ++- gfx/size_io.h | 35 +- os/app_main_tests.cpp | 2 +- os/app_mode.h | 2 +- os/capabilities.h | 56 +- os/color_space.h | 36 +- os/common/event_queue.cpp | 5 +- os/common/file_dialog.h | 19 +- os/common/freetype_font.cpp | 12 +- os/common/freetype_font.h | 54 +- os/common/generic_surface.h | 37 +- os/common/main.cpp | 16 +- os/common/sprite_sheet_font.h | 55 +- os/common/system.cpp | 88 +-- os/common/system.h | 28 +- os/cursor.h | 14 +- os/dnd.cpp | 12 +- os/dnd.h | 201 +++---- os/draw_text.cpp | 77 ++- os/draw_text.h | 111 ++-- os/error.h | 2 +- os/event.h | 264 ++++---- os/event_queue.h | 81 +-- os/font.h | 64 +- os/font_manager.h | 19 +- os/font_style.h | 140 +++-- os/font_style_set.h | 25 +- os/gl/gl_context.h | 8 +- os/gl/gl_context_glx.h | 39 +- os/gl/gl_context_nsgl.h | 4 +- os/gl/gl_context_nsgl.mm | 9 +- os/gl/gl_context_wgl.h | 69 ++- os/keys.h | 290 ++++----- os/logger.h | 10 +- os/menus.h | 163 +++-- os/native_cursor.h | 44 +- os/native_dialogs.h | 66 +- os/none/os.cpp | 56 +- os/none/paint.h | 54 +- os/osx/app.h | 30 +- os/osx/app.mm | 26 +- os/osx/app_delegate.h | 4 +- os/osx/app_delegate.mm | 14 +- os/osx/color_space.h | 2 +- os/osx/color_space.mm | 12 +- os/osx/dnd.h | 36 +- os/osx/dnd.mm | 17 +- os/osx/event_queue.mm | 10 +- os/osx/generate_drop_files.h | 4 +- os/osx/keys.h | 10 +- os/osx/keys.mm | 59 +- os/osx/logger.h | 8 +- os/osx/menus.h | 14 +- os/osx/menus.mm | 63 +- os/osx/native_dialogs.h | 10 +- os/osx/native_dialogs.mm | 74 +-- os/osx/screen.h | 23 +- os/osx/system.h | 34 +- os/osx/system.mm | 68 +-- os/osx/view.h | 4 +- os/osx/view.mm | 132 ++-- os/osx/window.h | 18 +- os/osx/window.mm | 158 ++--- os/osx/window_delegate.h | 10 +- os/paint.h | 108 ++-- os/pointer_type.h | 20 +- os/ref.h | 24 +- os/sampling.h | 42 +- os/screen.h | 40 +- os/shortcut.h | 34 +- os/skia/os.cpp | 5 +- os/skia/paint.h | 87 ++- os/skia/skia_color_space.cpp | 69 ++- os/skia/skia_draw_text.cpp | 35 +- os/skia/skia_draw_text_with_shaper.cpp | 27 +- os/skia/skia_font_manager.h | 46 +- os/skia/skia_gl.cpp | 36 +- os/skia/skia_gl.h | 6 +- os/skia/skia_helpers.h | 37 +- os/skia/skia_surface.cpp | 400 ++++++------- os/skia/skia_surface.h | 75 ++- os/skia/skia_system.h | 77 ++- os/skia/skia_window.cpp | 4 +- os/skia/skia_window.h | 18 +- os/skia/skia_window_base.h | 72 +-- os/skia/skia_window_osx.h | 2 +- os/skia/skia_window_osx.mm | 74 +-- os/skia/skia_window_win.cpp | 49 +- os/skia/skia_window_x11.cpp | 39 +- os/skia/skia_window_x11.h | 2 +- os/surface.h | 254 ++++---- os/surface_format.h | 46 +- os/surface_list.h | 2 +- os/system.cpp | 4 +- os/system.h | 409 +++++++------ os/tablet_options.h | 66 +- os/typeface.h | 19 +- os/win/color_space.cpp | 16 +- os/win/dnd.cpp | 42 +- os/win/dnd.h | 80 ++- os/win/event_queue.cpp | 11 +- os/win/keys.cpp | 408 +++++++------ os/win/keys.h | 82 ++- os/win/native_dialogs.cpp | 105 ++-- os/win/native_dialogs.h | 10 +- os/win/screen.h | 16 +- os/win/system.cpp | 77 ++- os/win/system.h | 7 +- os/win/winapi.cpp | 5 +- os/win/winapi.h | 113 ++-- os/win/window.cpp | 794 +++++++++++-------------- os/win/window.h | 440 +++++++------- os/win/window_dde.cpp | 51 +- os/win/wintab.cpp | 137 +++-- os/win/wintab.h | 109 ++-- os/window.cpp | 2 +- os/window.h | 383 ++++++------ os/window_spec.h | 129 ++-- os/x11/cursor.h | 9 +- os/x11/event_queue.cpp | 79 ++- os/x11/keys.cpp | 620 ++++++++++--------- os/x11/keys.h | 14 +- os/x11/mouse.h | 44 +- os/x11/native_dialogs.cpp | 51 +- os/x11/native_dialogs.h | 10 +- os/x11/screen.h | 29 +- os/x11/system.cpp | 116 ++-- os/x11/system.h | 46 +- os/x11/window.cpp | 514 ++++++++-------- os/x11/window.h | 16 +- os/x11/x11.cpp | 2 +- os/x11/x11.h | 3 +- os/x11/xinput.cpp | 53 +- os/x11/xinput.h | 5 +- 312 files changed, 9879 insertions(+), 10481 deletions(-) diff --git a/base/24bits.h b/base/24bits.h index 5b76fb6f9..284d1d4b7 100644 --- a/base/24bits.h +++ b/base/24bits.h @@ -15,21 +15,23 @@ namespace base { #ifdef LAF_LITTLE_ENDIAN - template - inline void write24bits(PTR* ptr, VALUE value) { - ((uint8_t*)ptr)[0] = value; - ((uint8_t*)ptr)[1] = value >> 8; - ((uint8_t*)ptr)[2] = value >> 16; - } +template +inline void write24bits(PTR* ptr, VALUE value) +{ + ((uint8_t*)ptr)[0] = value; + ((uint8_t*)ptr)[1] = value >> 8; + ((uint8_t*)ptr)[2] = value >> 16; +} #elif defined(LAF_BIG_ENDIAN) - template - inline void write24bits(PTR* ptr, VALUE value) { - ((uint8_t*)ptr)[0] = value >> 16; - ((uint8_t*)ptr)[1] = value >> 8; - ((uint8_t*)ptr)[2] = value; - } +template +inline void write24bits(PTR* ptr, VALUE value) +{ + ((uint8_t*)ptr)[0] = value >> 16; + ((uint8_t*)ptr)[1] = value >> 8; + ((uint8_t*)ptr)[2] = value; +} #endif diff --git a/base/base.h b/base/base.h index fa2f94fad..d27aa9fcb 100644 --- a/base/base.h +++ b/base/base.h @@ -36,23 +36,21 @@ #undef ABS #undef SGN -#define ABS(x) (((x) >= 0) ? (x) : (-(x))) -#define SGN(x) (((x) >= 0) ? 1 : -1) - - +#define ABS(x) (((x) >= 0) ? (x) : (-(x))) +#define SGN(x) (((x) >= 0) ? 1 : -1) ////////////////////////////////////////////////////////////////////// // Overloaded new/delete operators to detect memory-leaks #if defined __cplusplus && defined LAF_MEMLEAK -#include + #include -#ifdef _NOEXCEPT - #define LAF_NOEXCEPT _NOEXCEPT -#else - #define LAF_NOEXCEPT -#endif + #ifdef _NOEXCEPT + #define LAF_NOEXCEPT _NOEXCEPT + #else + #define LAF_NOEXCEPT + #endif void* operator new(std::size_t size); void* operator new[](std::size_t size); diff --git a/base/base64.cpp b/base/base64.cpp index 271557346..7400196c6 100644 --- a/base/base64.cpp +++ b/base/base64.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/base64.h" @@ -56,7 +56,7 @@ static inline int base64Inv(int asciiChar) void encode_base64(const char* input, size_t n, std::string& output) { - const size_t size = 4*int(std::ceil(n/3.0)); // Estimate encoded string size + const size_t size = 4 * int(std::ceil(n / 3.0)); // Estimate encoded string size output.resize(size); auto outIt = output.begin(); @@ -64,7 +64,7 @@ void encode_base64(const char* input, size_t n, std::string& output) uint8_t next = 0; size_t i = 0; size_t j = 0; - for (; i> 4)); + for (; i + 3 < n; i += 4, input += 4) { + *outIt = (((base64Inv(input[0])) << 2) | ((base64Inv(input[1]) & 0b110000) >> 4)); ++outIt; if (input[2] == '=') { @@ -117,8 +116,7 @@ void decode_base64(const char* input, size_t n, buffer& output) break; } - *outIt = (((base64Inv(input[1]) & 0b001111) << 4) | - ((base64Inv(input[2]) & 0b111100) >> 2)); + *outIt = (((base64Inv(input[1]) & 0b001111) << 4) | ((base64Inv(input[2]) & 0b111100) >> 2)); ++outIt; if (input[3] == '=') { @@ -126,8 +124,7 @@ void decode_base64(const char* input, size_t n, buffer& output) break; } - *outIt = (((base64Inv(input[2]) & 0b000011) << 6) | - ((base64Inv(input[3]) ))); + *outIt = (((base64Inv(input[2]) & 0b000011) << 6) | ((base64Inv(input[3])))); ++outIt; } diff --git a/base/base64.h b/base/base64.h index 04dba40b2..6ffd686dc 100644 --- a/base/base64.h +++ b/base/base64.h @@ -18,38 +18,44 @@ namespace base { void encode_base64(const char* input, size_t n, std::string& output); void decode_base64(const char* input, size_t n, buffer& output); -inline void encode_base64(const buffer& input, std::string& output) { +inline void encode_base64(const buffer& input, std::string& output) +{ if (!input.empty()) encode_base64((const char*)&input[0], input.size(), output); } -inline std::string encode_base64(const buffer& input) { +inline std::string encode_base64(const buffer& input) +{ std::string output; if (!input.empty()) encode_base64((const char*)&input[0], input.size(), output); return output; } -inline std::string encode_base64(const std::string& input) { +inline std::string encode_base64(const std::string& input) +{ std::string output; if (!input.empty()) encode_base64((const char*)input.c_str(), input.size(), output); return output; } -inline void decode_base64(const std::string& input, buffer& output) { +inline void decode_base64(const std::string& input, buffer& output) +{ if (!input.empty()) decode_base64(input.c_str(), input.size(), output); } -inline buffer decode_base64(const std::string& input) { +inline buffer decode_base64(const std::string& input) +{ buffer output; if (!input.empty()) decode_base64(input.c_str(), input.size(), output); return output; } -inline std::string decode_base64s(const std::string& input) { +inline std::string decode_base64s(const std::string& input) +{ if (input.empty()) return std::string(); buffer tmp; @@ -57,7 +63,8 @@ inline std::string decode_base64s(const std::string& input) { return std::string((const char*)&tmp[0], tmp.size()); } -inline buffer decode_base64(const buffer& input) { +inline buffer decode_base64(const buffer& input) +{ buffer output; if (!input.empty()) decode_base64((const char*)&input[0], input.size(), output); diff --git a/base/base64_tests.cpp b/base/base64_tests.cpp index 6eb91899d..f39b8874e 100644 --- a/base/base64_tests.cpp +++ b/base/base64_tests.cpp @@ -15,9 +15,9 @@ using namespace base; TEST(Base64, Encode) { EXPECT_EQ("", encode_base64(buffer())); - EXPECT_EQ("Cg==", encode_base64(buffer{'\n'})); - EXPECT_EQ("YQ==", encode_base64(buffer{'a'})); - EXPECT_EQ("YWJjZGU=", encode_base64(buffer{'a', 'b', 'c', 'd', 'e'})); + EXPECT_EQ("Cg==", encode_base64(buffer{ '\n' })); + EXPECT_EQ("YQ==", encode_base64(buffer{ 'a' })); + EXPECT_EQ("YWJjZGU=", encode_base64(buffer{ 'a', 'b', 'c', 'd', 'e' })); EXPECT_EQ("YWJjZGU=", encode_base64("abcde")); EXPECT_EQ("YWJj", encode_base64("abc")); EXPECT_EQ("5pel5pys6Kqe", encode_base64("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E")); // "日本語" @@ -26,9 +26,9 @@ TEST(Base64, Encode) TEST(Base64, Decode) { EXPECT_EQ(buffer(), decode_base64("")); - EXPECT_EQ(buffer{'\n'}, decode_base64("Cg==")); - EXPECT_EQ(buffer{'a'}, decode_base64("YQ==")); - EXPECT_EQ(buffer({'a', 'b', 'c', 'd', 'e'}), decode_base64("YWJjZGU=")); + EXPECT_EQ(buffer{ '\n' }, decode_base64("Cg==")); + EXPECT_EQ(buffer{ 'a' }, decode_base64("YQ==")); + EXPECT_EQ(buffer({ 'a', 'b', 'c', 'd', 'e' }), decode_base64("YWJjZGU=")); EXPECT_EQ("abcde", decode_base64s("YWJjZGU=")); EXPECT_EQ("abc", decode_base64s("YWJj")); EXPECT_EQ("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E", decode_base64s("5pel5pys6Kqe")); // "日本語" diff --git a/base/cfile.cpp b/base/cfile.cpp index 93102264a..ce5f8f096 100644 --- a/base/cfile.cpp +++ b/base/cfile.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -84,14 +84,9 @@ long long fgetq(FILE* file) return EOF; // Little endian. - return (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + return (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); } // Reads a 32-bit single-precision floating point number using @@ -148,14 +143,9 @@ double fgetd(FILE* file) return EOF; // Little endian. - long long v = (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + long long v = (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); return *reinterpret_cast(&v); } diff --git a/base/cfile.h b/base/cfile.h index 45d0fcb5e..aeaaa7d33 100644 --- a/base/cfile.h +++ b/base/cfile.h @@ -12,16 +12,16 @@ namespace base { - int fgetw(FILE* file); - long fgetl(FILE* file); - long long fgetq(FILE* file); - float fgetf(FILE* file); - double fgetd(FILE* file); - int fputw(int w, FILE* file); - int fputl(long l, FILE* file); - int fputq(long long l, FILE* file); - int fputf(float l, FILE* file); - int fputd(double l, FILE* file); +int fgetw(FILE* file); +long fgetl(FILE* file); +long long fgetq(FILE* file); +float fgetf(FILE* file); +double fgetd(FILE* file); +int fputw(int w, FILE* file); +int fputl(long l, FILE* file); +int fputq(long long l, FILE* file); +int fputf(float l, FILE* file); +int fputd(double l, FILE* file); } // namespace base diff --git a/base/chrono.cpp b/base/chrono.cpp index bf3a40279..2091ffd28 100644 --- a/base/chrono.cpp +++ b/base/chrono.cpp @@ -1,37 +1,41 @@ -// LAF Base Library -// Copyright (c) 2021 Igara Studio S.A. -// Copyright (c) 2001-2016 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "base/chrono.h" - -#if LAF_WINDOWS - #include "base/chrono_win32.h" -#else - #include "base/chrono_unix.h" -#endif - -namespace base { - - Chrono::Chrono() : m_impl(new ChronoImpl) { - } - - Chrono::~Chrono() { - delete m_impl; - } - - void Chrono::reset() { - m_impl->reset(); - } - - double Chrono::elapsed() const { - return m_impl->elapsed(); - } - -} // namespace base +// LAF Base Library +// Copyright (c) 2021 Igara Studio S.A. +// Copyright (c) 2001-2016 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#ifdef HAVE_CONFIG_H + #include "config.h" +#endif + +#include "base/chrono.h" + +#if LAF_WINDOWS + #include "base/chrono_win32.h" +#else + #include "base/chrono_unix.h" +#endif + +namespace base { + +Chrono::Chrono() : m_impl(new ChronoImpl) +{ +} + +Chrono::~Chrono() +{ + delete m_impl; +} + +void Chrono::reset() +{ + m_impl->reset(); +} + +double Chrono::elapsed() const +{ + return m_impl->elapsed(); +} + +} // namespace base diff --git a/base/chrono.h b/base/chrono.h index 4ff976ace..37726ea66 100644 --- a/base/chrono.h +++ b/base/chrono.h @@ -1,27 +1,27 @@ -// LAF Base Library -// Copyright (c) 2001-2016 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#ifndef BASE_CHRONO_H_INCLUDED -#define BASE_CHRONO_H_INCLUDED -#pragma once - -namespace base { - - class Chrono { - public: - Chrono(); - ~Chrono(); - void reset(); - double elapsed() const; - - private: - class ChronoImpl; - ChronoImpl* m_impl; - }; - -} // namespace base - -#endif // BASE_CHRONO_H_INCLUDED +// LAF Base Library +// Copyright (c) 2001-2016 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#ifndef BASE_CHRONO_H_INCLUDED +#define BASE_CHRONO_H_INCLUDED +#pragma once + +namespace base { + +class Chrono { +public: + Chrono(); + ~Chrono(); + void reset(); + double elapsed() const; + +private: + class ChronoImpl; + ChronoImpl* m_impl; +}; + +} // namespace base + +#endif // BASE_CHRONO_H_INCLUDED diff --git a/base/chrono_unix.h b/base/chrono_unix.h index 54b8f0d4b..f8ea9655d 100644 --- a/base/chrono_unix.h +++ b/base/chrono_unix.h @@ -1,29 +1,26 @@ -// LAF Base Library -// Copyright (c) 2001-2016 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#include -#include - -class base::Chrono::ChronoImpl { -public: - ChronoImpl() { - reset(); - } - - void reset() { - gettimeofday(&m_point, NULL); - } - - double elapsed() const { - struct timeval now; - gettimeofday(&now, NULL); - return (double)(now.tv_sec + (double)now.tv_usec/1000000) - - (double)(m_point.tv_sec + (double)m_point.tv_usec/1000000); - } - -private: - struct timeval m_point; -}; +// LAF Base Library +// Copyright (c) 2001-2016 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#include +#include + +class base::Chrono::ChronoImpl { +public: + ChronoImpl() { reset(); } + + void reset() { gettimeofday(&m_point, NULL); } + + double elapsed() const + { + struct timeval now; + gettimeofday(&now, NULL); + return (double)(now.tv_sec + (double)now.tv_usec / 1000000) - + (double)(m_point.tv_sec + (double)m_point.tv_usec / 1000000); + } + +private: + struct timeval m_point; +}; diff --git a/base/chrono_win32.h b/base/chrono_win32.h index 9abbe24dd..0ec3b9451 100644 --- a/base/chrono_win32.h +++ b/base/chrono_win32.h @@ -1,31 +1,31 @@ -// LAF Base Library -// Copyright (c) 2001-2016 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#define WIN32_LEAN_AND_MEAN -#include - -class base::Chrono::ChronoImpl { -public: - ChronoImpl() { - QueryPerformanceFrequency(&m_freq); - reset(); - } - - void reset() { - QueryPerformanceCounter(&m_point); - } - - double elapsed() const { - LARGE_INTEGER now; - QueryPerformanceCounter(&now); - return static_cast(now.QuadPart - m_point.QuadPart) - / static_cast(m_freq.QuadPart); - } - -private: - LARGE_INTEGER m_point; - LARGE_INTEGER m_freq; -}; +// LAF Base Library +// Copyright (c) 2001-2016 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#define WIN32_LEAN_AND_MEAN +#include + +class base::Chrono::ChronoImpl { +public: + ChronoImpl() + { + QueryPerformanceFrequency(&m_freq); + reset(); + } + + void reset() { QueryPerformanceCounter(&m_point); } + + double elapsed() const + { + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + return static_cast(now.QuadPart - m_point.QuadPart) / + static_cast(m_freq.QuadPart); + } + +private: + LARGE_INTEGER m_point; + LARGE_INTEGER m_freq; +}; diff --git a/base/concurrent_queue.h b/base/concurrent_queue.h index f688504b8..52f04a827 100644 --- a/base/concurrent_queue.h +++ b/base/concurrent_queue.h @@ -15,71 +15,77 @@ namespace base { - template - class concurrent_queue { - public: - concurrent_queue() { } - concurrent_queue(const concurrent_queue&) = delete; - concurrent_queue& operator=(const concurrent_queue&) = delete; - ~concurrent_queue() { } - - bool empty() const { - bool result; - { - const std::lock_guard lock(m_mutex); - result = m_queue.empty(); - } - return result; - } - - void clear() { +template +class concurrent_queue { +public: + concurrent_queue() {} + concurrent_queue(const concurrent_queue&) = delete; + concurrent_queue& operator=(const concurrent_queue&) = delete; + ~concurrent_queue() {} + + bool empty() const + { + bool result; + { const std::lock_guard lock(m_mutex); - m_queue.clear(); - } - - size_t size() const { - size_t result; - { - const std::lock_guard lock(m_mutex); - result = m_queue.size(); - } - return result; + result = m_queue.empty(); } - - void push(const T& value) { + return result; + } + + void clear() + { + const std::lock_guard lock(m_mutex); + m_queue.clear(); + } + + size_t size() const + { + size_t result; + { const std::lock_guard lock(m_mutex); - m_queue.push_back(value); - } - - bool try_pop(T& value) { - if (!m_mutex.try_lock()) - return false; - - const std::lock_guard unlock(m_mutex, std::adopt_lock); - if (m_queue.empty()) - return false; - - value = m_queue.front(); - m_queue.pop_front(); - return true; + result = m_queue.size(); } - - template - void prioritize(UnaryPredicate p) { - const std::lock_guard lock(m_mutex); - - auto it = std::find_if(m_queue.begin(), m_queue.end(), p); - if (it != m_queue.end()) { - T value(std::move(*it)); - m_queue.erase(it); - m_queue.push_front(std::move(value)); - } + return result; + } + + void push(const T& value) + { + const std::lock_guard lock(m_mutex); + m_queue.push_back(value); + } + + bool try_pop(T& value) + { + if (!m_mutex.try_lock()) + return false; + + const std::lock_guard unlock(m_mutex, std::adopt_lock); + if (m_queue.empty()) + return false; + + value = m_queue.front(); + m_queue.pop_front(); + return true; + } + + template + void prioritize(UnaryPredicate p) + { + const std::lock_guard lock(m_mutex); + + auto it = std::find_if(m_queue.begin(), m_queue.end(), p); + if (it != m_queue.end()) { + T value(std::move(*it)); + m_queue.erase(it); + m_queue.push_front(std::move(value)); } + } - private: - std::deque m_queue; - mutable std::mutex m_mutex; - }; +private: + std::deque m_queue; + mutable std::mutex m_mutex; +}; } // namespace base diff --git a/base/convert_to.cpp b/base/convert_to.cpp index 4ad5fc866..8f1fbf99d 100644 --- a/base/convert_to.cpp +++ b/base/convert_to.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/convert_to.h" @@ -19,63 +19,71 @@ namespace base { -template<> int convert_to(const std::string& from) +template<> +int convert_to(const std::string& from) { return std::strtol(from.c_str(), NULL, 10); } -template<> std::string convert_to(const int& from) +template<> +std::string convert_to(const int& from) { char buf[32]; std::snprintf(buf, sizeof(buf), "%d", from); return buf; } -template<> uint32_t convert_to(const std::string& from) +template<> +uint32_t convert_to(const std::string& from) { return std::strtoul(from.c_str(), NULL, 10); } -template<> std::string convert_to(const uint32_t& from) +template<> +std::string convert_to(const uint32_t& from) { char buf[32]; std::snprintf(buf, sizeof(buf), "%u", from); return buf; } -template<> double convert_to(const std::string& from) +template<> +double convert_to(const std::string& from) { return std::strtod(from.c_str(), NULL); } -template<> std::string convert_to(const double& from) +template<> +std::string convert_to(const double& from) { char buf[32]; std::snprintf(buf, sizeof(buf), "%g", from); return buf; } -template<> Sha1 convert_to(const std::string& from) +template<> +Sha1 convert_to(const std::string& from) { std::vector digest(Sha1::HashSize); - for (size_t i=0; i= from.size()) + for (size_t i = 0; i < Sha1::HashSize; ++i) { + if (i * 2 + 1 >= from.size()) break; - digest[i] = convert_to(from.substr(i*2, 2)); + digest[i] = convert_to(from.substr(i * 2, 2)); } return Sha1(digest); } -template<> std::string convert_to(const Sha1& from) +template<> +std::string convert_to(const Sha1& from) { char buf[3]; std::string res; - res.reserve(2*Sha1::HashSize); + res.reserve(2 * Sha1::HashSize); - for(int c=0; c std::string convert_to(const Sha1& from) return res; } -template<> Uuid convert_to(const std::string& from) +template<> +Uuid convert_to(const std::string& from) { Uuid uuid; int i = 0; - for (int j=0; j Uuid convert_to(const std::string& from) return uuid; } -template<> std::string convert_to(const Uuid& from) +template<> +std::string convert_to(const Uuid& from) { int i = 0; - char buf[Uuid::HashSize+1]; - for (; i<4; ++i) snprintf(buf+2*i, 3, "%02x", int(from[i])); - for (; i<6; ++i) snprintf(buf+2*i+1, 3, "%02x", int(from[i])); - for (; i<8; ++i) snprintf(buf+2*i+2, 3, "%02x", int(from[i])); - for (; i<10; ++i) snprintf(buf+2*i+3, 3, "%02x", int(from[i])); - for (; i<16; ++i) snprintf(buf+2*i+4, 3, "%02x", int(from[i])); + char buf[Uuid::HashSize + 1]; + for (; i < 4; ++i) + snprintf(buf + 2 * i, 3, "%02x", int(from[i])); + for (; i < 6; ++i) + snprintf(buf + 2 * i + 1, 3, "%02x", int(from[i])); + for (; i < 8; ++i) + snprintf(buf + 2 * i + 2, 3, "%02x", int(from[i])); + for (; i < 10; ++i) + snprintf(buf + 2 * i + 3, 3, "%02x", int(from[i])); + for (; i < 16; ++i) + snprintf(buf + 2 * i + 4, 3, "%02x", int(from[i])); buf[8] = buf[13] = buf[18] = buf[23] = '-'; return std::string(buf); } diff --git a/base/convert_to.h b/base/convert_to.h index 34ffe6952..cf6c8b388 100644 --- a/base/convert_to.h +++ b/base/convert_to.h @@ -15,33 +15,45 @@ namespace base { - class Sha1; - class Uuid; - - // Undefined convertion - template - To convert_to(const From&) { - // We've to use the sizeof(To) trick to use static_assert(false) - // and make the compiler fail in non-specialized cases, see P2593R0: - // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2593r0.html - static_assert(false && sizeof(To), "Invalid conversion"); // NOLINT readability-simplify-boolean-expr - } +class Sha1; +class Uuid; + +// Undefined convertion +template +To convert_to(const From&) +{ + // We've to use the sizeof(To) trick to use static_assert(false) + // and make the compiler fail in non-specialized cases, see P2593R0: + // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2593r0.html + static_assert(false && sizeof(To), "Invalid conversion"); // NOLINT + // readability-simplify-boolean-expr +} - template<> int convert_to(const std::string& from); - template<> std::string convert_to(const int& from); +template<> +int convert_to(const std::string& from); +template<> +std::string convert_to(const int& from); - template<> uint32_t convert_to(const std::string& from); - template<> std::string convert_to(const uint32_t& from); +template<> +uint32_t convert_to(const std::string& from); +template<> +std::string convert_to(const uint32_t& from); - template<> double convert_to(const std::string& from); - template<> std::string convert_to(const double& from); +template<> +double convert_to(const std::string& from); +template<> +std::string convert_to(const double& from); - template<> Sha1 convert_to(const std::string& from); - template<> std::string convert_to(const Sha1& from); +template<> +Sha1 convert_to(const std::string& from); +template<> +std::string convert_to(const Sha1& from); - template<> Uuid convert_to(const std::string& from); - template<> std::string convert_to(const Uuid& from); +template<> +Uuid convert_to(const std::string& from); +template<> +std::string convert_to(const Uuid& from); -} +} // namespace base #endif diff --git a/base/count_bits.h b/base/count_bits.h index 42f7b6e8b..cfd75fd66 100644 --- a/base/count_bits.h +++ b/base/count_bits.h @@ -13,16 +13,17 @@ namespace base { - template - constexpr inline size_t count_bits(const T v) { - size_t n = 0; - for (size_t b=0; b +constexpr inline size_t count_bits(const T v) +{ + size_t n = 0; + for (size_t b = 0; b < sizeof(T) * 8; ++b) { + if (v & (T(1) << b)) + ++n; } - + return n; } +} // namespace base + #endif diff --git a/base/count_bits_tests.cpp b/base/count_bits_tests.cpp index 73ab58f0e..6dbc8f8bd 100644 --- a/base/count_bits_tests.cpp +++ b/base/count_bits_tests.cpp @@ -6,8 +6,8 @@ #include -#include "base/ints.h" #include "base/count_bits.h" +#include "base/ints.h" using namespace base; diff --git a/base/debug.cpp b/base/debug.cpp index 6ce474472..9b8b77058 100644 --- a/base/debug.cpp +++ b/base/debug.cpp @@ -6,42 +6,42 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #ifdef _DEBUG -#include "base/debug.h" + #include "base/debug.h" -#include "base/convert_to.h" -#include "base/string.h" + #include "base/convert_to.h" + #include "base/string.h" -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include -#if LAF_WINDOWS - #include -#endif + #if LAF_WINDOWS + #include + #endif int base_assert(const char* condition, const char* file, int lineNum) { -#if LAF_WINDOWS + #if LAF_WINDOWS std::vector buf(MAX_PATH); GetModuleFileNameW(NULL, &buf[0], MAX_PATH); int ret = _CrtDbgReportW(_CRT_ASSERT, - base::from_utf8(file).c_str(), - lineNum, - &buf[0], - base::from_utf8(condition).c_str()); + base::from_utf8(file).c_str(), + lineNum, + &buf[0], + base::from_utf8(condition).c_str()); - return (ret == 1 ? 1: 0); + return (ret == 1 ? 1 : 0); -#else + #else std::string text = file; text += ":"; @@ -52,7 +52,7 @@ int base_assert(const char* condition, const char* file, int lineNum) std::abort(); return 1; -#endif + #endif } void base_trace(const char* msg, ...) @@ -63,9 +63,9 @@ void base_trace(const char* msg, ...) vsnprintf(buf, sizeof(buf), msg, ap); va_end(ap); -#if LAF_WINDOWS + #if LAF_WINDOWS _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, buf); -#endif + #endif std::cerr << buf << std::flush; } diff --git a/base/debug.h b/base/debug.h index 60175d49b..207a54971 100644 --- a/base/debug.h +++ b/base/debug.h @@ -18,30 +18,34 @@ void base_trace(const char* msg, ...); #include #include - template - void base_args_to_string_step(std::stringstream& s, Arg&& arg) { - s << std::forward(arg); - } +template +void base_args_to_string_step(std::stringstream& s, Arg&& arg) +{ + s << std::forward(arg); +} - template - void base_args_to_string_step(std::stringstream& s, Arg&& arg, Args&&... args) { - s << std::forward(arg) << ' '; - base_args_to_string_step(s, std::forward(args)...); - } +template +void base_args_to_string_step(std::stringstream& s, Arg&& arg, Args&&... args) +{ + s << std::forward(arg) << ' '; + base_args_to_string_step(s, std::forward(args)...); +} - template - std::string base_args_to_string(Args&&... args) { - std::stringstream s; - base_args_to_string_step(s, std::forward(args)...); - return s.str(); - } +template +std::string base_args_to_string(Args&&... args) +{ + std::stringstream s; + base_args_to_string_step(s, std::forward(args)...); + return s.str(); +} - template - void base_trace_args(Args&&... args) { - std::string s = base_args_to_string(std::forward(args)...); - s.push_back('\n'); - base_trace(s.c_str()); - } +template +void base_trace_args(Args&&... args) +{ + std::string s = base_args_to_string(std::forward(args)...); + s.push_back('\n'); + base_trace(s.c_str()); +} #endif #undef ASSERT @@ -57,15 +61,16 @@ void base_trace(const char* msg, ...); #define base_break() raise(SIGTRAP) #endif - #define ASSERT(condition) { \ - if (!(condition)) { \ - if (base_assert(#condition, __FILE__, __LINE__)) { \ - base_break(); \ - } \ - } \ - } + #define ASSERT(condition) \ + { \ + if (!(condition)) { \ + if (base_assert(#condition, __FILE__, __LINE__)) { \ + base_break(); \ + } \ + } \ + } - #define TRACE base_trace + #define TRACE base_trace #define TRACEARGS base_trace_args #else #define ASSERT(condition) diff --git a/base/disable_copying.h b/base/disable_copying.h index 30c2e0b1a..4169d8235 100644 --- a/base/disable_copying.h +++ b/base/disable_copying.h @@ -9,8 +9,8 @@ #define BASE_DISABLE_COPYING_H_INCLUDED #pragma once -#define DISABLE_COPYING(ClassName) \ - ClassName(const ClassName&) = delete; \ +#define DISABLE_COPYING(ClassName) \ + ClassName(const ClassName&) = delete; \ ClassName& operator=(const ClassName&) = delete; #endif diff --git a/base/dll.cpp b/base/dll.cpp index 9feb6b1fc..2d5861868 100644 --- a/base/dll.cpp +++ b/base/dll.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/dll.h" diff --git a/base/dll.h b/base/dll.h index b5c7502fa..d0727c058 100644 --- a/base/dll.h +++ b/base/dll.h @@ -21,7 +21,8 @@ void unload_dll(dll lib); dll_proc get_dll_proc_base(dll lib, const char* procName); template -inline T get_dll_proc(dll lib, const char* procName) { +inline T get_dll_proc(dll lib, const char* procName) +{ return reinterpret_cast(get_dll_proc_base(lib, procName)); } diff --git a/base/dll_win32.h b/base/dll_win32.h index 0051a8997..5a8fd4872 100644 --- a/base/dll_win32.h +++ b/base/dll_win32.h @@ -26,8 +26,7 @@ void unload_dll(dll lib) dll_proc get_dll_proc_base(dll lib, const char* procName) { - return reinterpret_cast( - GetProcAddress((HMODULE)lib, procName)); + return reinterpret_cast(GetProcAddress((HMODULE)lib, procName)); } static bool get_dll_filename_wchar(dll lib, std::vector& buf) @@ -46,9 +45,8 @@ static bool get_dll_filename_wchar(dll lib, std::vector& buf) std::string get_dll_filename(dll lib) { std::vector buf(MAX_PATH); - if (get_dll_filename_wchar(lib, buf) && - buf.size() > 1) { // One char for the null char - return to_utf8(&buf[0], buf.size()-1); + if (get_dll_filename_wchar(lib, buf) && buf.size() > 1) { // One char for the null char + return to_utf8(&buf[0], buf.size() - 1); } return std::string(); } diff --git a/base/enum_flags.h b/base/enum_flags.h index 388e9e1a7..08a73cae3 100644 --- a/base/enum_flags.h +++ b/base/enum_flags.h @@ -30,38 +30,41 @@ // // https://github.com/grisumbras/enum-flags // -#define LAF_ENUM_FLAGS(T) \ - constexpr inline T operator|(const T a, const T b) { \ - using U = std::underlying_type_t; \ - return static_cast(static_cast(a) | \ - static_cast(b)); \ - } \ - \ - constexpr inline T operator&(const T a, const T b) { \ - using U = std::underlying_type_t; \ - return static_cast(static_cast(a) & \ - static_cast(b)); \ - } \ - \ - constexpr inline T operator^(const T a, const T b) { \ - using U = std::underlying_type_t; \ - return static_cast(static_cast(a) ^ \ - static_cast(b)); \ - } \ - \ - constexpr inline T& operator|=(T& a, const T b) { \ - a = a | b; \ - return a; \ - } \ - \ - constexpr inline T& operator&=(T& a, const T b) { \ - a = a & b; \ - return a; \ - } \ - \ - constexpr inline T& operator^=(T& a, const T b) { \ - a = a ^ b; \ - return a; \ +#define LAF_ENUM_FLAGS(T) \ + constexpr inline T operator|(const T a, const T b) \ + { \ + using U = std::underlying_type_t; \ + return static_cast(static_cast(a) | static_cast(b)); \ + } \ + \ + constexpr inline T operator&(const T a, const T b) \ + { \ + using U = std::underlying_type_t; \ + return static_cast(static_cast(a) & static_cast(b)); \ + } \ + \ + constexpr inline T operator^(const T a, const T b) \ + { \ + using U = std::underlying_type_t; \ + return static_cast(static_cast(a) ^ static_cast(b)); \ + } \ + \ + constexpr inline T& operator|=(T& a, const T b) \ + { \ + a = a | b; \ + return a; \ + } \ + \ + constexpr inline T& operator&=(T& a, const T b) \ + { \ + a = a & b; \ + return a; \ + } \ + \ + constexpr inline T& operator^=(T& a, const T b) \ + { \ + a = a ^ b; \ + return a; \ } #endif diff --git a/base/enum_flags_tests.cpp b/base/enum_flags_tests.cpp index 27547dbe2..081205173 100644 --- a/base/enum_flags_tests.cpp +++ b/base/enum_flags_tests.cpp @@ -10,19 +10,21 @@ #include "base/ints.h" -enum class U8 : uint8_t { A=1, B=2, C=4 }; -enum class U32 : uint32_t { A=1, B=256 }; +enum class U8 : uint8_t { A = 1, B = 2, C = 4 }; +enum class U32 : uint32_t { A = 1, B = 256 }; LAF_ENUM_FLAGS(U8); LAF_ENUM_FLAGS(U32); TEST(EnumFlags, Uint8) { - U8 a = { }; + U8 a = {}; EXPECT_EQ(U8(0), a); - a |= U8::A; EXPECT_EQ(U8::A, a); - a |= U8::B; EXPECT_EQ(U8::A | U8::B, a); + a |= U8::A; + EXPECT_EQ(U8::A, a); + a |= U8::B; + EXPECT_EQ(U8::A | U8::B, a); EXPECT_EQ(U8::B, a & U8::B); EXPECT_EQ(U8(0), a & U8::C); @@ -43,7 +45,7 @@ TEST(EnumFlags, Conversion) EXPECT_EQ(uint32_t(U8::A), uint32_t(U32::A)); U8 b = U8(a); - EXPECT_EQ(U8::A, b); // U32::B is lost in uint8_t + EXPECT_EQ(U8::A, b); // U32::B is lost in uint8_t } int main(int argc, char** argv) diff --git a/base/errno_string.cpp b/base/errno_string.cpp index aeaa38d17..216dc75ca 100644 --- a/base/errno_string.cpp +++ b/base/errno_string.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -15,55 +15,53 @@ namespace base { // Like 'strerror' but thread-safe. std::string get_errno_string(int errnum) { - static const char *errors[] = { - "No error", /* errno = 0 */ - "Operation not permitted", /* errno = 1 (EPERM) */ - "No such file or directory", /* errno = 2 (ENOFILE) */ - "No such process", /* errno = 3 (ESRCH) */ - "Interrupted function call", /* errno = 4 (EINTR) */ - "Input/output error", /* errno = 5 (EIO) */ - "No such device or address", /* errno = 6 (ENXIO) */ - "Arg list too long", /* errno = 7 (E2BIG) */ - "Exec format error", /* errno = 8 (ENOEXEC) */ - "Bad file descriptor", /* errno = 9 (EBADF) */ - "No child processes", /* errno = 10 (ECHILD) */ - "Resource temporarily unavailable", /* errno = 11 (EAGAIN) */ - "Not enough space", /* errno = 12 (ENOMEM) */ - "Permission denied", /* errno = 13 (EACCES) */ - "Bad address", /* errno = 14 (EFAULT) */ + static const char* errors[] = { + "No error", /* errno = 0 */ + "Operation not permitted", /* errno = 1 (EPERM) */ + "No such file or directory", /* errno = 2 (ENOFILE) */ + "No such process", /* errno = 3 (ESRCH) */ + "Interrupted function call", /* errno = 4 (EINTR) */ + "Input/output error", /* errno = 5 (EIO) */ + "No such device or address", /* errno = 6 (ENXIO) */ + "Arg list too long", /* errno = 7 (E2BIG) */ + "Exec format error", /* errno = 8 (ENOEXEC) */ + "Bad file descriptor", /* errno = 9 (EBADF) */ + "No child processes", /* errno = 10 (ECHILD) */ + "Resource temporarily unavailable", /* errno = 11 (EAGAIN) */ + "Not enough space", /* errno = 12 (ENOMEM) */ + "Permission denied", /* errno = 13 (EACCES) */ + "Bad address", /* errno = 14 (EFAULT) */ NULL, - "Resource device", /* errno = 16 (EBUSY) */ - "File exists", /* errno = 17 (EEXIST) */ - "Improper link", /* errno = 18 (EXDEV) */ - "No such device", /* errno = 19 (ENODEV) */ - "Not a directory", /* errno = 20 (ENOTDIR) */ - "Is a directory", /* errno = 21 (EISDIR) */ - "Invalid argument", /* errno = 22 (EINVAL) */ - "Too many open files in system", /* errno = 23 (ENFILE) */ - "Too many open files", /* errno = 24 (EMFILE) */ - "Inappropriate I/O control operation", /* errno = 25 (ENOTTY) */ + "Resource device", /* errno = 16 (EBUSY) */ + "File exists", /* errno = 17 (EEXIST) */ + "Improper link", /* errno = 18 (EXDEV) */ + "No such device", /* errno = 19 (ENODEV) */ + "Not a directory", /* errno = 20 (ENOTDIR) */ + "Is a directory", /* errno = 21 (EISDIR) */ + "Invalid argument", /* errno = 22 (EINVAL) */ + "Too many open files in system", /* errno = 23 (ENFILE) */ + "Too many open files", /* errno = 24 (EMFILE) */ + "Inappropriate I/O control operation", /* errno = 25 (ENOTTY) */ NULL, - "File too large", /* errno = 27 (EFBIG) */ - "No space left on device", /* errno = 28 (ENOSPC) */ - "Invalid seek", /* errno = 29 (ESPIPE) */ - "Read-only file system", /* errno = 30 (EROFS) */ - "Too many links", /* errno = 31 (EMLINK) */ - "Broken pipe", /* errno = 32 (EPIPE) */ - "Domain error", /* errno = 33 (EDOM) */ - "Result too large", /* errno = 34 (ERANGE) */ + "File too large", /* errno = 27 (EFBIG) */ + "No space left on device", /* errno = 28 (ENOSPC) */ + "Invalid seek", /* errno = 29 (ESPIPE) */ + "Read-only file system", /* errno = 30 (EROFS) */ + "Too many links", /* errno = 31 (EMLINK) */ + "Broken pipe", /* errno = 32 (EPIPE) */ + "Domain error", /* errno = 33 (EDOM) */ + "Result too large", /* errno = 34 (ERANGE) */ NULL, - "Resource deadlock avoided", /* errno = 36 (EDEADLOCK) */ + "Resource deadlock avoided", /* errno = 36 (EDEADLOCK) */ NULL, - "Filename too long", /* errno = 38 (ENAMETOOLONG) */ - "No locks available", /* errno = 39 (ENOLCK) */ - "Function not implemented", /* errno = 40 (ENOSYS) */ - "Directory not empty", /* errno = 41 (ENOTEMPTY) */ - "Illegal byte sequence", /* errno = 42 (EILSEQ) */ + "Filename too long", /* errno = 38 (ENAMETOOLONG) */ + "No locks available", /* errno = 39 (ENOLCK) */ + "Function not implemented", /* errno = 40 (ENOSYS) */ + "Directory not empty", /* errno = 41 (ENOTEMPTY) */ + "Illegal byte sequence", /* errno = 42 (EILSEQ) */ }; - if (errnum >= 0 - && errnum < (int)(sizeof(errors)/sizeof(char *)) - && errors[errnum] != NULL) { + if (errnum >= 0 && errnum < (int)(sizeof(errors) / sizeof(char*)) && errors[errnum] != NULL) { return errors[errnum]; } return "Unknown error"; diff --git a/base/exception.cpp b/base/exception.cpp index 3e99cd75f..baa5ebfae 100644 --- a/base/exception.cpp +++ b/base/exception.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/exception.h" diff --git a/base/exception.h b/base/exception.h index 971be3f9e..2b72b4390 100644 --- a/base/exception.h +++ b/base/exception.h @@ -14,22 +14,22 @@ namespace base { - class Exception : public std::exception { - public: - Exception() throw(); - Exception(const char* format, ...) throw(); - Exception(const std::string& msg) throw(); - virtual ~Exception() throw(); +class Exception : public std::exception { +public: + Exception() throw(); + Exception(const char* format, ...) throw(); + Exception(const std::string& msg) throw(); + virtual ~Exception() throw(); - const char* what() const throw() override; + const char* what() const throw() override; - protected: - void setMessage(const char* msg) throw(); +protected: + void setMessage(const char* msg) throw(); - private: - std::string m_msg; - }; +private: + std::string m_msg; +}; -} +} // namespace base #endif diff --git a/base/file_content.cpp b/base/file_content.cpp index 9692ad7ac..cc59b8464 100644 --- a/base/file_content.cpp +++ b/base/file_content.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/file_content.h" @@ -23,7 +23,7 @@ namespace base { -const size_t kChunkSize = 1024*64; // 64k +const size_t kChunkSize = 1024 * 64; // 64k buffer read_file_content(FILE* file) { @@ -53,8 +53,8 @@ buffer read_file_content(const std::string& filename) void write_file_content(FILE* file, const uint8_t* buf, size_t size) { - for (size_t pos=0; pos < size; ) { - const int write_bytes = std::min(kChunkSize, size-pos); + for (size_t pos = 0; pos < size;) { + const int write_bytes = std::min(kChunkSize, size - pos); const size_t written_bytes = std::fwrite(buf, 1, write_bytes, file); if (written_bytes < write_bytes) throw std::runtime_error("Cannot write all bytes"); diff --git a/base/file_content.h b/base/file_content.h index 14ab6c5f2..616943e2c 100644 --- a/base/file_content.h +++ b/base/file_content.h @@ -16,25 +16,27 @@ namespace base { - buffer read_file_content(FILE* file); - buffer read_file_content(const std::string& filename); - - void write_file_content(FILE* file, const uint8_t* data, size_t size); - void write_file_content(const std::string& filename, const uint8_t* data, size_t size); - - inline void write_file_content(FILE* file, const buffer& buf) { - if (!buf.empty()) - write_file_content(file, &buf[0], buf.size()); - } - - inline void write_file_content(const std::string& filename, const buffer& buf) { - if (!buf.empty()) - write_file_content(filename, &buf[0], buf.size()); - } - - // Can be used on Windows to write binary content to stdout or other - // FILE handles. - void set_write_binary_file_content(FILE* file); +buffer read_file_content(FILE* file); +buffer read_file_content(const std::string& filename); + +void write_file_content(FILE* file, const uint8_t* data, size_t size); +void write_file_content(const std::string& filename, const uint8_t* data, size_t size); + +inline void write_file_content(FILE* file, const buffer& buf) +{ + if (!buf.empty()) + write_file_content(file, &buf[0], buf.size()); +} + +inline void write_file_content(const std::string& filename, const buffer& buf) +{ + if (!buf.empty()) + write_file_content(filename, &buf[0], buf.size()); +} + +// Can be used on Windows to write binary content to stdout or other +// FILE handles. +void set_write_binary_file_content(FILE* file); } // namespace base diff --git a/base/file_content_tests.cpp b/base/file_content_tests.cpp index 1eba9354e..fc741236f 100644 --- a/base/file_content_tests.cpp +++ b/base/file_content_tests.cpp @@ -14,9 +14,9 @@ TEST(FileContent, ReadWrite) { const char* fn = "_test_.tmp"; - for (size_t s : { 30, 500, 1024*64, 1024*64*3+4 }) { + for (size_t s : { 30, 500, 1024 * 64, 1024 * 64 * 3 + 4 }) { buffer buf(s); - for (int i=0; i #if LAF_WINDOWS - #include #include + #include #endif -#include #include +#include #ifndef O_BINARY -#define O_BINARY 0 -#define O_TEXT 0 + #define O_BINARY 0 + #define O_TEXT 0 #endif using namespace std; @@ -48,8 +48,7 @@ static void throw_cannot_open_exception(const string& filename, const string& mo FILE* open_file_raw(const string& filename, const string& mode) { #if LAF_WINDOWS - return _wfopen(from_utf8(filename).c_str(), - from_utf8(mode).c_str()); + return _wfopen(from_utf8(filename).c_str(), from_utf8(mode).c_str()); #else return fopen(filename.c_str(), mode.c_str()); #endif @@ -58,13 +57,11 @@ FILE* open_file_raw(const string& filename, const string& mode) FILE* reopen_file_raw(const string& filename, const string& mode, FILE* stream) { #if LAF_WINDOWS - return _wfreopen((!filename.empty() ? from_utf8(filename).c_str(): nullptr), + return _wfreopen((!filename.empty() ? from_utf8(filename).c_str() : nullptr), from_utf8(mode).c_str(), stream); #else - return freopen((!filename.empty() ? filename.c_str(): nullptr), - mode.c_str(), - stream); + return freopen((!filename.empty() ? filename.c_str() : nullptr), mode.c_str(), stream); #endif } @@ -81,7 +78,8 @@ FileHandle open_file_with_exception(const string& filename, const string& mode) return f; } -FileHandle open_file_with_exception_sync_on_close(const std::string& filename, const std::string& mode) +FileHandle open_file_with_exception_sync_on_close(const std::string& filename, + const std::string& mode) { FileHandle f(open_file_raw(filename, mode), close_file_and_sync); if (!f) @@ -92,9 +90,12 @@ FileHandle open_file_with_exception_sync_on_close(const std::string& filename, c int open_file_descriptor_with_exception(const string& filename, const string& mode) { int flags = 0; - if (mode.find('r') != string::npos) flags |= O_RDONLY; - if (mode.find('w') != string::npos) flags |= O_RDWR | O_CREAT | O_TRUNC; - if (mode.find('b') != string::npos) flags |= O_BINARY; + if (mode.find('r') != string::npos) + flags |= O_RDONLY; + if (mode.find('w') != string::npos) + flags |= O_RDWR | O_CREAT | O_TRUNC; + if (mode.find('b') != string::npos) + flags |= O_BINARY; int fd; #if LAF_WINDOWS @@ -132,4 +133,4 @@ void close_file_and_sync(FILE* file) fclose(file); } -} +} // namespace base diff --git a/base/file_handle.h b/base/file_handle.h index ef9f3e73f..8ee85a34d 100644 --- a/base/file_handle.h +++ b/base/file_handle.h @@ -15,17 +15,18 @@ namespace base { - using FileHandle = std::shared_ptr; +using FileHandle = std::shared_ptr; - FILE* open_file_raw(const std::string& filename, const std::string& mode); - FILE* reopen_file_raw(const std::string& filename, const std::string& mode, FILE* stream); - FileHandle open_file(const std::string& filename, const std::string& mode); - FileHandle open_file_with_exception(const std::string& filename, const std::string& mode); - FileHandle open_file_with_exception_sync_on_close(const std::string& filename, const std::string& mode); - int open_file_descriptor_with_exception(const std::string& filename, const std::string& mode); - void sync_file_descriptor(int fd); - void close_file_and_sync(FILE* file); +FILE* open_file_raw(const std::string& filename, const std::string& mode); +FILE* reopen_file_raw(const std::string& filename, const std::string& mode, FILE* stream); +FileHandle open_file(const std::string& filename, const std::string& mode); +FileHandle open_file_with_exception(const std::string& filename, const std::string& mode); +FileHandle open_file_with_exception_sync_on_close(const std::string& filename, + const std::string& mode); +int open_file_descriptor_with_exception(const std::string& filename, const std::string& mode); +void sync_file_descriptor(int fd); +void close_file_and_sync(FILE* file); -} +} // namespace base #endif diff --git a/base/file_handle_tests.cpp b/base/file_handle_tests.cpp index b4a66f18a..d3a93d215 100644 --- a/base/file_handle_tests.cpp +++ b/base/file_handle_tests.cpp @@ -14,15 +14,15 @@ using namespace base; #ifdef _MSC_VER - #define posix_open _open - #define posix_close _close - #define posix_read _read - #define posix_write _write + #define posix_open _open + #define posix_close _close + #define posix_read _read + #define posix_write _write #else - #define posix_open open - #define posix_close close - #define posix_read read - #define posix_write write + #define posix_open open + #define posix_close close + #define posix_read read + #define posix_write write #endif TEST(FileHandle, Descriptors) @@ -31,35 +31,33 @@ TEST(FileHandle, Descriptors) // Delete the file if it exists. ASSERT_NO_THROW({ - if (is_file(fn)) - delete_file(fn); - }); + if (is_file(fn)) + delete_file(fn); + }); // Create file. ASSERT_NO_THROW({ - int fd = open_file_descriptor_with_exception(fn, "wb"); - posix_close(fd); - }); + int fd = open_file_descriptor_with_exception(fn, "wb"); + posix_close(fd); + }); // Truncate file. ASSERT_NO_THROW({ - int fd = open_file_descriptor_with_exception(fn, "wb"); - EXPECT_EQ(6, posix_write(fd, "hello", 6)); - posix_close(fd); - }); + int fd = open_file_descriptor_with_exception(fn, "wb"); + EXPECT_EQ(6, posix_write(fd, "hello", 6)); + posix_close(fd); + }); // Read. ASSERT_NO_THROW({ - int fd = open_file_descriptor_with_exception(fn, "rb"); - std::vector buf(6); - EXPECT_EQ(6, posix_read(fd, &buf[0], 6)); - EXPECT_EQ("hello", std::string(&buf[0])); - posix_close(fd); - }); + int fd = open_file_descriptor_with_exception(fn, "rb"); + std::vector buf(6); + EXPECT_EQ(6, posix_read(fd, &buf[0], 6)); + EXPECT_EQ("hello", std::string(&buf[0])); + posix_close(fd); + }); - ASSERT_NO_THROW({ - delete_file(fn); - }); + ASSERT_NO_THROW({ delete_file(fn); }); } int main(int argc, char** argv) diff --git a/base/fs.cpp b/base/fs.cpp index 2a3eaae6c..743ed3222 100644 --- a/base/fs.cpp +++ b/base/fs.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/fs.h" @@ -30,9 +30,9 @@ namespace base { // On Windows we can use \ or / as path separators, but on Unix-like // platforms it's just /, as \ can be part of the file name. #if LAF_WINDOWS - const std::string::value_type* path_separators = "\\/"; +const std::string::value_type* path_separators = "\\/"; #else - const std::string::value_type* path_separators = "/"; +const std::string::value_type* path_separators = "/"; #endif void make_all_directories(const std::string& path) @@ -62,14 +62,13 @@ std::string get_file_path(const std::string& filename) std::string::const_reverse_iterator rit; std::string res; - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) if (is_path_separator(*rit)) break; if (rit != filename.rend()) { ++rit; - std::copy(filename.begin(), std::string::const_iterator(rit.base()), - std::back_inserter(res)); + std::copy(filename.begin(), std::string::const_iterator(rit.base()), std::back_inserter(res)); } return res; @@ -80,12 +79,11 @@ std::string get_file_name(const std::string& filename) std::string::const_reverse_iterator rit; std::string result; - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) if (is_path_separator(*rit)) break; - std::copy(std::string::const_iterator(rit.base()), filename.end(), - std::back_inserter(result)); + std::copy(std::string::const_iterator(rit.base()), filename.end(), std::back_inserter(result)); return result; } @@ -96,7 +94,7 @@ std::string get_file_extension(const std::string& filename) std::string result; // search for the first dot from the end of the string - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) { + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) { if (is_path_separator(*rit)) return result; if (*rit == '.') @@ -104,8 +102,7 @@ std::string get_file_extension(const std::string& filename) } if (rit != filename.rend()) { - std::copy(std::string::const_iterator(rit.base()), filename.end(), - std::back_inserter(result)); + std::copy(std::string::const_iterator(rit.base()), filename.end(), std::back_inserter(result)); } return result; @@ -117,7 +114,7 @@ std::string replace_extension(const std::string& filename, const std::string& ex std::string result; // Search for the first dot from the end of the string. - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) { + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) { // Here is the dot of the extension. if (*rit == '.') break; @@ -132,8 +129,7 @@ std::string replace_extension(const std::string& filename, const std::string& ex if (rit != filename.rend()) { auto it = std::string::const_iterator(rit.base()); --it; - std::copy(filename.begin(), it, - std::back_inserter(result)); + std::copy(filename.begin(), it, std::back_inserter(result)); } else { result = filename; @@ -147,21 +143,20 @@ std::string replace_extension(const std::string& filename, const std::string& ex return result; } - std::string get_file_title(const std::string& filename) { std::string::const_reverse_iterator rit; std::string::const_iterator last_dot = filename.end(); std::string result; - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) { + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) { if (is_path_separator(*rit)) break; if (*rit == '.' && last_dot == filename.end()) - last_dot = rit.base()-1; + last_dot = rit.base() - 1; } - for (std::string::const_iterator it(rit.base()); it!=filename.end(); ++it) { + for (std::string::const_iterator it(rit.base()); it != filename.end(); ++it) { if (it == last_dot) break; result.push_back(*it); @@ -175,7 +170,7 @@ std::string get_file_title_with_path(const std::string& filename) std::string::const_reverse_iterator rit; // search for the first dot from the end of the string - for (rit=filename.rbegin(); rit!=filename.rend(); ++rit) { + for (rit = filename.rbegin(); rit != filename.rend(); ++rit) { if (is_path_separator(*rit)) return filename; if (*rit == '.') @@ -226,7 +221,7 @@ std::string join_path(const std::string& path, const std::string& file) std::string result(path); // Add a separator at the end if it is necessay - if (!result.empty() && !is_path_separator(*(result.end()-1))) + if (!result.empty() && !is_path_separator(*(result.end() - 1))) result.push_back(path_separator); // Add the file @@ -239,8 +234,8 @@ std::string remove_path_separator(const std::string& path) std::string result(path); // Erase all trailing separators - while (!result.empty() && is_path_separator(*(result.end()-1))) - result.erase(result.end()-1); + while (!result.empty() && is_path_separator(*(result.end() - 1))) + result.erase(result.end() - 1); return result; } @@ -254,16 +249,16 @@ std::string fix_path_separators(const std::string& filename) #if LAF_WINDOWS // Network paths can start with two backslashes - if (filename.size() >= 2 && - filename[0] == path_separator && // Check for equality to backslash (\), - filename[1] == path_separator) { // no for is_path_separator() + if (filename.size() >= 2 && filename[0] == path_separator && // Check for equality to backslash + // (\), + filename[1] == path_separator) { // no for is_path_separator() result.push_back(path_separator); result.push_back(path_separator); i += 2; } #endif - for (; i= 2 && - path[1] == path_separator) { + if (path.size() >= 2 && path[1] == path_separator) { fn.push_back(path_separator); } #endif @@ -309,14 +303,14 @@ std::string normalize_path(const std::string& _path) bool last_dot = false; auto n = int(parts.size()); - for (int i=0; i= '0') && (c <= '9')) - a_num = (a_num*10 + (c - '0')); + a_num = (a_num * 10 + (c - '0')); else break; } @@ -389,13 +382,13 @@ int compare_filenames(const std::string& a, const std::string& b) int b_num = (b_chr - '0'); while (const int c = b_dec2.next()) { if ((c >= '0') && (c <= '9')) - b_num = (b_num*10 + (c - '0')); + b_num = (b_num * 10 + (c - '0')); else break; } if (a_num != b_num) - return a_num - b_num < 0 ? -1: 1; + return a_num - b_num < 0 ? -1 : 1; } else if (is_path_separator(a_chr) && is_path_separator(b_chr)) { // Go to next char @@ -405,7 +398,7 @@ int compare_filenames(const std::string& a, const std::string& b) b_chr = std::tolower(b_chr); if (a_chr != b_chr) - return a_chr - b_chr < 0 ? -1: 1; + return a_chr - b_chr < 0 ? -1 : 1; } } diff --git a/base/fs.h b/base/fs.h index 7fac0b826..6ad632ff0 100644 --- a/base/fs.h +++ b/base/fs.h @@ -15,124 +15,121 @@ namespace base { - class Time; +class Time; - // Default path separator (on Windows it is '\' and on Unix-like - // systems it is '/'). +// Default path separator (on Windows it is '\' and on Unix-like +// systems it is '/'). #if LAF_WINDOWS - static constexpr const std::string::value_type path_separator = '\\'; +static constexpr const std::string::value_type path_separator = '\\'; #else - static constexpr const std::string::value_type path_separator = '/'; +static constexpr const std::string::value_type path_separator = '/'; #endif - extern const std::string::value_type* path_separators; +extern const std::string::value_type* path_separators; - bool is_file(const std::string& path); - bool is_directory(const std::string& path); +bool is_file(const std::string& path); +bool is_directory(const std::string& path); - size_t file_size(const std::string& path); +size_t file_size(const std::string& path); - void move_file(const std::string& src, const std::string& dst); - void copy_file(const std::string& src, const std::string& dst, bool overwrite); - void delete_file(const std::string& path); +void move_file(const std::string& src, const std::string& dst); +void copy_file(const std::string& src, const std::string& dst, bool overwrite); +void delete_file(const std::string& path); - bool has_readonly_attr(const std::string& path); - void remove_readonly_attr(const std::string& path); +bool has_readonly_attr(const std::string& path); +void remove_readonly_attr(const std::string& path); - Time get_modification_time(const std::string& path); +Time get_modification_time(const std::string& path); - void make_directory(const std::string& path); - void make_all_directories(const std::string& path); - void remove_directory(const std::string& path); +void make_directory(const std::string& path); +void make_all_directories(const std::string& path); +void remove_directory(const std::string& path); - std::string get_current_path(); - void set_current_path(const std::string& path); +std::string get_current_path(); +void set_current_path(const std::string& path); - std::string get_app_path(); - std::string get_temp_path(); - std::string get_user_docs_folder(); +std::string get_app_path(); +std::string get_temp_path(); +std::string get_user_docs_folder(); #if __APPLE__ - std::string get_lib_app_support_path(); +std::string get_lib_app_support_path(); #endif - // Converts an existing file path to an absolute one, or returns an - // empty string if the file doesn't exist. It uses realpath() on - // POSIX-like systems and GetFullPathName() on Windows. - std::string get_canonical_path(const std::string& path); - - // Returns the absolute path using lexical/string operations, and - // get_current_path() when needed. Doesn't require an existing file - // in "path". The returned path shouldn't contain "." or ".." - // elements (is a normalized path). - std::string get_absolute_path(const std::string& path); - - // Item types that list_files() can be filtered by - enum class ItemType { - All, - Directories, - Files - }; - - // List all the items in a given path by default, two other parameters second parameters: - // filter can be use to distinguish between All items, directories and files. - // The name search can be used to match files by extension with something like "*.png" or by exact - // match without wildcards. - paths list_files(const std::string& path, - ItemType filter = ItemType::All, - const std::string& = "*"); - - // Returns true if the given character is a valud path separator - // (any of '\' or '/' characters). - inline constexpr bool is_path_separator(std::string::value_type chr) { - return ( +// Converts an existing file path to an absolute one, or returns an +// empty string if the file doesn't exist. It uses realpath() on +// POSIX-like systems and GetFullPathName() on Windows. +std::string get_canonical_path(const std::string& path); + +// Returns the absolute path using lexical/string operations, and +// get_current_path() when needed. Doesn't require an existing file +// in "path". The returned path shouldn't contain "." or ".." +// elements (is a normalized path). +std::string get_absolute_path(const std::string& path); + +// Item types that list_files() can be filtered by +enum class ItemType { All, Directories, Files }; + +// List all the items in a given path by default, two other parameters second parameters: +// filter can be use to distinguish between All items, directories and files. +// The name search can be used to match files by extension with something like "*.png" or by exact +// match without wildcards. +paths list_files(const std::string& path, + ItemType filter = ItemType::All, + const std::string& = "*"); + +// Returns true if the given character is a valud path separator +// (any of '\' or '/' characters). +inline constexpr bool is_path_separator(std::string::value_type chr) +{ + return ( #if LAF_WINDOWS - chr == '\\' || + chr == '\\' || #endif - chr == '/'); - } + chr == '/'); +} - // Returns only the path (without the last trailing slash). - std::string get_file_path(const std::string& filename); +// Returns only the path (without the last trailing slash). +std::string get_file_path(const std::string& filename); - // Returns the file name with its extension, removing the path. - std::string get_file_name(const std::string& filename); +// Returns the file name with its extension, removing the path. +std::string get_file_name(const std::string& filename); - // Returns the extension of the file name (without the dot). - std::string get_file_extension(const std::string& filename); +// Returns the extension of the file name (without the dot). +std::string get_file_extension(const std::string& filename); - // Returns the whole path with another extension. - std::string replace_extension(const std::string& filename, const std::string& extension); +// Returns the whole path with another extension. +std::string replace_extension(const std::string& filename, const std::string& extension); - // Returns the file name without path and without extension. - std::string get_file_title(const std::string& filename); - std::string get_file_title_with_path(const std::string& filename); +// Returns the file name without path and without extension. +std::string get_file_title(const std::string& filename); +std::string get_file_title_with_path(const std::string& filename); - // Returns the relative path of the given filename from the base_path. - std::string get_relative_path(const std::string& filename, const std::string& base_path); +// Returns the relative path of the given filename from the base_path. +std::string get_relative_path(const std::string& filename, const std::string& base_path); - // Joins two paths or a path and a file name with a path-separator. - std::string join_path(const std::string& path, const std::string& file); +// Joins two paths or a path and a file name with a path-separator. +std::string join_path(const std::string& path, const std::string& file); - // Removes the trailing separator from the given path. - std::string remove_path_separator(const std::string& path); +// Removes the trailing separator from the given path. +std::string remove_path_separator(const std::string& path); - // Replaces all separators with the system separator. - std::string fix_path_separators(const std::string& filename); +// Replaces all separators with the system separator. +std::string fix_path_separators(const std::string& filename); - // Remove superfluous path elements ("/../" and "/./") and call - // fix_path_separators() for the given path. - std::string normalize_path(const std::string& path); +// Remove superfluous path elements ("/../" and "/./") and call +// fix_path_separators() for the given path. +std::string normalize_path(const std::string& path); - // Returns true if the filename contains one of the specified - // extensions. The "extensions" parameter must be a set of possible - // extensions. - bool has_file_extension(const std::string& filename, const base::paths& extensions); +// Returns true if the filename contains one of the specified +// extensions. The "extensions" parameter must be a set of possible +// extensions. +bool has_file_extension(const std::string& filename, const base::paths& extensions); - int compare_filenames(const std::string& a, const std::string& b); +int compare_filenames(const std::string& a, const std::string& b); #if LAF_WINDOWS - class Version; - Version get_file_version(const std::string& filename); - Version get_file_version(const wchar_t* filename); +class Version; +Version get_file_version(const std::string& filename); +Version get_file_version(const wchar_t* filename); #endif } // namespace base diff --git a/base/fs_osx.mm b/base/fs_osx.mm index a36d621a0..2cf7f08fa 100644 --- a/base/fs_osx.mm +++ b/base/fs_osx.mm @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -16,8 +16,8 @@ std::string get_lib_app_support_path() { - NSArray* dirs = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSArray* dirs = + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); if (dirs) { NSString* dir = [dirs firstObject]; if (dir) diff --git a/base/fs_tests.cpp b/base/fs_tests.cpp index 017a420ef..14b0a97a0 100644 --- a/base/fs_tests.cpp +++ b/base/fs_tests.cpp @@ -20,7 +20,7 @@ // We cannot use the on macOS yet because we are // targetting macOS 10.9 platform. #include - namespace fs = std::filesystem; +namespace fs = std::filesystem; #endif using namespace base; @@ -41,8 +41,8 @@ TEST(FS, FixPathSeparators) const std::string sep(1, path_separator); EXPECT_EQ(sep, fix_path_separators("/")); EXPECT_EQ(sep, fix_path_separators("///")); - EXPECT_EQ(sep+"a"+sep, fix_path_separators("//a/")); - EXPECT_EQ("a"+sep+"b"+sep, fix_path_separators("a///b/")); + EXPECT_EQ(sep + "a" + sep, fix_path_separators("//a/")); + EXPECT_EQ("a" + sep + "b" + sep, fix_path_separators("a///b/")); #if LAF_WINDOWS EXPECT_EQ("\\\\hostname\\a\\b", fix_path_separators("\\\\hostname\\\\a/b")); @@ -85,13 +85,13 @@ TEST(FS, MakeAllDirectories) TEST(FS, IsPathSeparator) { - EXPECT_TRUE (is_path_separator('/')); + EXPECT_TRUE(is_path_separator('/')); EXPECT_FALSE(is_path_separator('a')); EXPECT_FALSE(is_path_separator('+')); EXPECT_FALSE(is_path_separator(':')); #if LAF_WINDOWS - EXPECT_TRUE (is_path_separator('\\')); + EXPECT_TRUE(is_path_separator('\\')); #else EXPECT_FALSE(is_path_separator('\\')); #endif @@ -99,133 +99,136 @@ TEST(FS, IsPathSeparator) TEST(FS, GetFilePath) { - EXPECT_EQ("C:/foo", get_file_path("C:/foo/pack.tar.gz")); - EXPECT_EQ(".", get_file_path("./main.cpp")); - EXPECT_EQ("", get_file_path("\\main.cpp")); - EXPECT_EQ("", get_file_path("main.cpp")); - EXPECT_EQ("", get_file_path("main.")); - EXPECT_EQ("", get_file_path("main")); - EXPECT_EQ("C:/foo", get_file_path("C:/foo/")); - EXPECT_EQ("", get_file_path(".cpp")); - EXPECT_EQ("", get_file_path("")); + EXPECT_EQ("C:/foo", get_file_path("C:/foo/pack.tar.gz")); + EXPECT_EQ(".", get_file_path("./main.cpp")); + EXPECT_EQ("", get_file_path("\\main.cpp")); + EXPECT_EQ("", get_file_path("main.cpp")); + EXPECT_EQ("", get_file_path("main.")); + EXPECT_EQ("", get_file_path("main")); + EXPECT_EQ("C:/foo", get_file_path("C:/foo/")); + EXPECT_EQ("", get_file_path(".cpp")); + EXPECT_EQ("", get_file_path("")); #if LAF_WINDOWS - EXPECT_EQ("C:\\foo", get_file_path("C:\\foo\\main.cpp")); - EXPECT_EQ(".", get_file_path(".\\main.cpp")); - EXPECT_EQ("C:", get_file_path("C:\\")); - EXPECT_EQ("C:", get_file_path("C:\\.cpp")); + EXPECT_EQ("C:\\foo", get_file_path("C:\\foo\\main.cpp")); + EXPECT_EQ(".", get_file_path(".\\main.cpp")); + EXPECT_EQ("C:", get_file_path("C:\\")); + EXPECT_EQ("C:", get_file_path("C:\\.cpp")); #else - EXPECT_EQ("", get_file_path("C:\\foo\\main.cpp")); - EXPECT_EQ("", get_file_path(".\\main.cpp")); - EXPECT_EQ("", get_file_path("C:\\")); - EXPECT_EQ("", get_file_path("C:\\.cpp")); + EXPECT_EQ("", get_file_path("C:\\foo\\main.cpp")); + EXPECT_EQ("", get_file_path(".\\main.cpp")); + EXPECT_EQ("", get_file_path("C:\\")); + EXPECT_EQ("", get_file_path("C:\\.cpp")); #endif } TEST(FS, GetFileName) { - EXPECT_EQ("pack.tar.gz", get_file_name("C:/foo/pack.tar.gz")); - EXPECT_EQ("main.cpp", get_file_name("./main.cpp")); - EXPECT_EQ("main.cpp", get_file_name("main.cpp")); - EXPECT_EQ("main.", get_file_name("main.")); - EXPECT_EQ("main", get_file_name("main")); - EXPECT_EQ("", get_file_name("C:/foo/")); - EXPECT_EQ(".cpp", get_file_name(".cpp")); - EXPECT_EQ("", get_file_name("")); + EXPECT_EQ("pack.tar.gz", get_file_name("C:/foo/pack.tar.gz")); + EXPECT_EQ("main.cpp", get_file_name("./main.cpp")); + EXPECT_EQ("main.cpp", get_file_name("main.cpp")); + EXPECT_EQ("main.", get_file_name("main.")); + EXPECT_EQ("main", get_file_name("main")); + EXPECT_EQ("", get_file_name("C:/foo/")); + EXPECT_EQ(".cpp", get_file_name(".cpp")); + EXPECT_EQ("", get_file_name("")); #if LAF_WINDOWS - EXPECT_EQ("main.cpp", get_file_name("C:\\foo\\main.cpp")); - EXPECT_EQ("main.cpp", get_file_name(".\\main.cpp")); - EXPECT_EQ("main.cpp", get_file_name("\\main.cpp")); - EXPECT_EQ("", get_file_name("C:\\")); - EXPECT_EQ(".cpp", get_file_name("C:\\.cpp")); + EXPECT_EQ("main.cpp", get_file_name("C:\\foo\\main.cpp")); + EXPECT_EQ("main.cpp", get_file_name(".\\main.cpp")); + EXPECT_EQ("main.cpp", get_file_name("\\main.cpp")); + EXPECT_EQ("", get_file_name("C:\\")); + EXPECT_EQ(".cpp", get_file_name("C:\\.cpp")); #else EXPECT_EQ("C:\\foo\\main.cpp", get_file_name("C:\\foo\\main.cpp")); - EXPECT_EQ(".\\main.cpp", get_file_name(".\\main.cpp")); - EXPECT_EQ("\\main.cpp", get_file_name("\\main.cpp")); - EXPECT_EQ("C:\\", get_file_name("C:\\")); - EXPECT_EQ("C:\\.cpp", get_file_name("C:\\.cpp")); + EXPECT_EQ(".\\main.cpp", get_file_name(".\\main.cpp")); + EXPECT_EQ("\\main.cpp", get_file_name("\\main.cpp")); + EXPECT_EQ("C:\\", get_file_name("C:\\")); + EXPECT_EQ("C:\\.cpp", get_file_name("C:\\.cpp")); #endif } TEST(FS, GetFileExtension) { - EXPECT_EQ("gz", get_file_extension("C:/foo/pack.tar.gz")); - EXPECT_EQ("cpp", get_file_extension("./main.cpp")); - EXPECT_EQ("cpp", get_file_extension("main.cpp")); - EXPECT_EQ("", get_file_extension("main.")); - EXPECT_EQ("", get_file_extension("main")); - EXPECT_EQ("", get_file_extension("C:/foo/")); - EXPECT_EQ("cpp", get_file_extension(".cpp")); - EXPECT_EQ("", get_file_extension("")); + EXPECT_EQ("gz", get_file_extension("C:/foo/pack.tar.gz")); + EXPECT_EQ("cpp", get_file_extension("./main.cpp")); + EXPECT_EQ("cpp", get_file_extension("main.cpp")); + EXPECT_EQ("", get_file_extension("main.")); + EXPECT_EQ("", get_file_extension("main")); + EXPECT_EQ("", get_file_extension("C:/foo/")); + EXPECT_EQ("cpp", get_file_extension(".cpp")); + EXPECT_EQ("", get_file_extension("")); // Same results on Windows/macOS/Linux - EXPECT_EQ("cpp", get_file_extension("C:\\foo\\main.cpp")); - EXPECT_EQ("cpp", get_file_extension(".\\main.cpp")); - EXPECT_EQ("cpp", get_file_extension("\\main.cpp")); - EXPECT_EQ("", get_file_extension("C:\\")); - EXPECT_EQ("cpp", get_file_extension("C:\\.cpp")); + EXPECT_EQ("cpp", get_file_extension("C:\\foo\\main.cpp")); + EXPECT_EQ("cpp", get_file_extension(".\\main.cpp")); + EXPECT_EQ("cpp", get_file_extension("\\main.cpp")); + EXPECT_EQ("", get_file_extension("C:\\")); + EXPECT_EQ("cpp", get_file_extension("C:\\.cpp")); } TEST(FS, GetFileTitle) { EXPECT_EQ("pack.tar", get_file_title("C:/foo/pack.tar.gz")); - EXPECT_EQ("main", get_file_title("./main.cpp")); - EXPECT_EQ("main", get_file_title("main.cpp")); - EXPECT_EQ("main", get_file_title("main.")); - EXPECT_EQ("main", get_file_title("main")); - EXPECT_EQ("", get_file_title("C:/foo/")); - EXPECT_EQ("", get_file_title(".cpp")); - EXPECT_EQ("", get_file_title("")); + EXPECT_EQ("main", get_file_title("./main.cpp")); + EXPECT_EQ("main", get_file_title("main.cpp")); + EXPECT_EQ("main", get_file_title("main.")); + EXPECT_EQ("main", get_file_title("main")); + EXPECT_EQ("", get_file_title("C:/foo/")); + EXPECT_EQ("", get_file_title(".cpp")); + EXPECT_EQ("", get_file_title("")); #if LAF_WINDOWS - EXPECT_EQ("main", get_file_title("C:\\foo\\main.cpp")); - EXPECT_EQ("main", get_file_title(".\\main.cpp")); - EXPECT_EQ("main", get_file_title("\\main.cpp")); - EXPECT_EQ("", get_file_title("C:\\")); - EXPECT_EQ("", get_file_title("C:\\.cpp")); + EXPECT_EQ("main", get_file_title("C:\\foo\\main.cpp")); + EXPECT_EQ("main", get_file_title(".\\main.cpp")); + EXPECT_EQ("main", get_file_title("\\main.cpp")); + EXPECT_EQ("", get_file_title("C:\\")); + EXPECT_EQ("", get_file_title("C:\\.cpp")); #else EXPECT_EQ("C:\\foo\\main", get_file_title("C:\\foo\\main.cpp")); - EXPECT_EQ(".\\main", get_file_title(".\\main.cpp")); - EXPECT_EQ("\\main", get_file_title("\\main.cpp")); - EXPECT_EQ("C:\\", get_file_title("C:\\")); - EXPECT_EQ("C:\\", get_file_title("C:\\.cpp")); + EXPECT_EQ(".\\main", get_file_title(".\\main.cpp")); + EXPECT_EQ("\\main", get_file_title("\\main.cpp")); + EXPECT_EQ("C:\\", get_file_title("C:\\")); + EXPECT_EQ("C:\\", get_file_title("C:\\.cpp")); #endif } TEST(FS, GetFileTitleWithPath) { EXPECT_EQ("C:/foo/pack.tar", get_file_title_with_path("C:/foo/pack.tar.gz")); - EXPECT_EQ("./main", get_file_title_with_path("./main.cpp")); - EXPECT_EQ("main", get_file_title_with_path("main.cpp")); - EXPECT_EQ("main", get_file_title_with_path("main.")); - EXPECT_EQ("main", get_file_title_with_path("main")); - EXPECT_EQ("C:/foo/", get_file_title_with_path("C:/foo/")); - EXPECT_EQ("", get_file_title_with_path(".cpp")); - EXPECT_EQ("", get_file_title_with_path("")); + EXPECT_EQ("./main", get_file_title_with_path("./main.cpp")); + EXPECT_EQ("main", get_file_title_with_path("main.cpp")); + EXPECT_EQ("main", get_file_title_with_path("main.")); + EXPECT_EQ("main", get_file_title_with_path("main")); + EXPECT_EQ("C:/foo/", get_file_title_with_path("C:/foo/")); + EXPECT_EQ("", get_file_title_with_path(".cpp")); + EXPECT_EQ("", get_file_title_with_path("")); // Same results on Windows/macOS/Linux - EXPECT_EQ("C:\\foo\\main", get_file_title_with_path("C:\\foo\\main.cpp")); - EXPECT_EQ(".\\main", get_file_title_with_path(".\\main.cpp")); - EXPECT_EQ("\\main", get_file_title_with_path("\\main.cpp")); - EXPECT_EQ("C:\\", get_file_title_with_path("C:\\")); - EXPECT_EQ("C:\\", get_file_title_with_path("C:\\.cpp")); + EXPECT_EQ("C:\\foo\\main", get_file_title_with_path("C:\\foo\\main.cpp")); + EXPECT_EQ(".\\main", get_file_title_with_path(".\\main.cpp")); + EXPECT_EQ("\\main", get_file_title_with_path("\\main.cpp")); + EXPECT_EQ("C:\\", get_file_title_with_path("C:\\")); + EXPECT_EQ("C:\\", get_file_title_with_path("C:\\.cpp")); } TEST(FS, GetRelativePath) { - EXPECT_EQ("C:\\foo\\bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "D:\\another\\disk")); + EXPECT_EQ("C:\\foo\\bar\\test.file", + get_relative_path("C:\\foo\\bar\\test.file", "D:\\another\\disk")); #if LAF_WINDOWS - EXPECT_EQ("bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo")); - EXPECT_EQ("C:\\foo\\bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "D:\\another\\disk")); - EXPECT_EQ("..\\bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo\\another")); - EXPECT_EQ("..\\..\\bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo\\a\\b")); + EXPECT_EQ("bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo")); + EXPECT_EQ("C:\\foo\\bar\\test.file", + get_relative_path("C:\\foo\\bar\\test.file", "D:\\another\\disk")); + EXPECT_EQ("..\\bar\\test.file", get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo\\another")); + EXPECT_EQ("..\\..\\bar\\test.file", + get_relative_path("C:\\foo\\bar\\test.file", "C:\\foo\\a\\b")); #else - EXPECT_EQ("bar/test.file", get_relative_path("C:/foo/bar/test.file", "C:/foo")); - EXPECT_EQ("C:/foo/bar/test.file", get_relative_path("C:/foo/bar/test.file", "D:/another/disk")); - EXPECT_EQ("../bar/test.file", get_relative_path("/foo/bar/test.file", "/foo/another")); - EXPECT_EQ("../../bar/test.file", get_relative_path("/foo/bar/test.file", "/foo/a/b")); + EXPECT_EQ("bar/test.file", get_relative_path("C:/foo/bar/test.file", "C:/foo")); + EXPECT_EQ("C:/foo/bar/test.file", get_relative_path("C:/foo/bar/test.file", "D:/another/disk")); + EXPECT_EQ("../bar/test.file", get_relative_path("/foo/bar/test.file", "/foo/another")); + EXPECT_EQ("../../bar/test.file", get_relative_path("/foo/bar/test.file", "/foo/a/b")); #endif } @@ -271,22 +274,22 @@ TEST(FS, NormalizePath) EXPECT_EQ(".", normalize_path(".///./.")); EXPECT_EQ(".", normalize_path(".///./")); - EXPECT_EQ("a"+sep, normalize_path("a/.")); - EXPECT_EQ("a"+sep, normalize_path("a/")); + EXPECT_EQ("a" + sep, normalize_path("a/.")); + EXPECT_EQ("a" + sep, normalize_path("a/")); EXPECT_EQ("a", normalize_path("./a")); - EXPECT_EQ("a"+sep+"b"+sep+"c", normalize_path("a///b/./c")); + EXPECT_EQ("a" + sep + "b" + sep + "c", normalize_path("a///b/./c")); EXPECT_EQ("..", normalize_path("..")); - EXPECT_EQ(".."+sep+"..", normalize_path("../..")); - EXPECT_EQ(".."+sep+"..", normalize_path("../../")); - EXPECT_EQ(".."+sep+"..", normalize_path(".././..")); - EXPECT_EQ(".."+sep+"..", normalize_path("./.././../.")); + EXPECT_EQ(".." + sep + "..", normalize_path("../..")); + EXPECT_EQ(".." + sep + "..", normalize_path("../../")); + EXPECT_EQ(".." + sep + "..", normalize_path(".././..")); + EXPECT_EQ(".." + sep + "..", normalize_path("./.././../.")); EXPECT_EQ(".", normalize_path("a/..")); EXPECT_EQ("..", normalize_path("../a/..")); - EXPECT_EQ(".."+sep+"..", normalize_path("../a/../..")); + EXPECT_EQ(".." + sep + "..", normalize_path("../a/../..")); EXPECT_EQ("..", normalize_path("a/../..")); - EXPECT_EQ(sep+"b", normalize_path("/a/../b")); + EXPECT_EQ(sep + "b", normalize_path("/a/../b")); #if LAF_WINDOWS EXPECT_EQ("\\\\hostname\\b", normalize_path("\\\\hostname\\\\a/../b")); @@ -297,14 +300,26 @@ TEST(FS, NormalizePath) #if COMPARE_WITH_STD_FS TEST(FS, CompareNormalizePathWithStd) { - for (const char* sample : { "", ".", "./.", ".///./.", ".///./", - "a/.", "a/", "./a", "a///b/./c", - "..", "../..", - "../../", ".././..", "./.././../.", - "a/..", "../a/..", "../a/../..", "a/../..", + for (const char* sample : { "", + ".", + "./.", + ".///./.", + ".///./", + "a/.", + "a/", + "./a", + "a///b/./c", + "..", + "../..", + "../../", + ".././..", + "./.././../.", + "a/..", + "../a/..", + "../a/../..", + "a/../..", "/a/../b" }) { - EXPECT_EQ(fs::path(sample).lexically_normal(), - normalize_path(sample)) + EXPECT_EQ(fs::path(sample).lexically_normal(), normalize_path(sample)) << " sample=\"" << sample << "\""; } } @@ -314,46 +329,46 @@ TEST(FS, JoinPath) { const std::string sep(1, path_separator); - EXPECT_EQ("", join_path("", "")); - EXPECT_EQ("fn", join_path("", "fn")); - EXPECT_EQ("/fn", join_path("/", "fn")); - EXPECT_EQ("/this"+sep+"fn", join_path("/this", "fn")); + EXPECT_EQ("", join_path("", "")); + EXPECT_EQ("fn", join_path("", "fn")); + EXPECT_EQ("/fn", join_path("/", "fn")); + EXPECT_EQ("/this" + sep + "fn", join_path("/this", "fn")); - EXPECT_EQ("C:\\path"+sep+"fn", join_path("C:\\path", "fn")); + EXPECT_EQ("C:\\path" + sep + "fn", join_path("C:\\path", "fn")); #if LAF_WINDOWS - EXPECT_EQ("C:\\path\\fn", join_path("C:\\path\\", "fn")); + EXPECT_EQ("C:\\path\\fn", join_path("C:\\path\\", "fn")); #else - EXPECT_EQ("C:\\path\\/fn", join_path("C:\\path\\", "fn")); + EXPECT_EQ("C:\\path\\/fn", join_path("C:\\path\\", "fn")); #endif } TEST(FS, RemovePathSeparator) { - EXPECT_EQ("C:/foo", remove_path_separator("C:/foo/")); + EXPECT_EQ("C:/foo", remove_path_separator("C:/foo/")); EXPECT_EQ("C:\\foo\\main.cpp", remove_path_separator("C:\\foo\\main.cpp")); EXPECT_EQ("C:\\foo\\main.cpp", remove_path_separator("C:\\foo\\main.cpp/")); #if LAF_WINDOWS - EXPECT_EQ("C:\\foo", remove_path_separator("C:\\foo\\")); + EXPECT_EQ("C:\\foo", remove_path_separator("C:\\foo\\")); #else - EXPECT_EQ("C:\\foo\\", remove_path_separator("C:\\foo\\")); + EXPECT_EQ("C:\\foo\\", remove_path_separator("C:\\foo\\")); #endif } TEST(FS, HasFileExtension) { - EXPECT_TRUE (has_file_extension("hi.png", paths{"png"})); - EXPECT_FALSE(has_file_extension("hi.png", paths{"pngg"})); - EXPECT_FALSE(has_file_extension("hi.png", paths{"ppng"})); - EXPECT_TRUE (has_file_extension("hi.jpeg", paths{"jpg","jpeg"})); - EXPECT_TRUE (has_file_extension("hi.jpg", paths{"jpg","jpeg"})); - EXPECT_FALSE(has_file_extension("hi.ase", paths{"jpg","jpeg"})); - EXPECT_TRUE (has_file_extension("hi.ase", paths{"jpg","jpeg","ase"})); - EXPECT_TRUE (has_file_extension("hi.ase", paths{"ase","jpg","jpeg"})); - - EXPECT_TRUE (has_file_extension("hi.png", paths{"Png"})); - EXPECT_TRUE (has_file_extension("hi.pnG", paths{"bmp","PNg"})); - EXPECT_TRUE (has_file_extension("hi.bmP", paths{"bMP","PNg"})); + EXPECT_TRUE(has_file_extension("hi.png", paths{ "png" })); + EXPECT_FALSE(has_file_extension("hi.png", paths{ "pngg" })); + EXPECT_FALSE(has_file_extension("hi.png", paths{ "ppng" })); + EXPECT_TRUE(has_file_extension("hi.jpeg", paths{ "jpg", "jpeg" })); + EXPECT_TRUE(has_file_extension("hi.jpg", paths{ "jpg", "jpeg" })); + EXPECT_FALSE(has_file_extension("hi.ase", paths{ "jpg", "jpeg" })); + EXPECT_TRUE(has_file_extension("hi.ase", paths{ "jpg", "jpeg", "ase" })); + EXPECT_TRUE(has_file_extension("hi.ase", paths{ "ase", "jpg", "jpeg" })); + + EXPECT_TRUE(has_file_extension("hi.png", paths{ "Png" })); + EXPECT_TRUE(has_file_extension("hi.pnG", paths{ "bmp", "PNg" })); + EXPECT_TRUE(has_file_extension("hi.bmP", paths{ "bMP", "PNg" })); } TEST(FS, ReplaceExtension) diff --git a/base/fs_unix.h b/base/fs_unix.h index 59fc78791..9f0ef63f1 100644 --- a/base/fs_unix.h +++ b/base/fs_unix.h @@ -12,10 +12,10 @@ #include "base/time.h" #include +#include #include #include #include -#include #include #include @@ -39,52 +39,47 @@ namespace base { bool is_file(const std::string& path) { struct stat sts; - return (stat(path.c_str(), &sts) == 0 && S_ISREG(sts.st_mode)) ? true: false; + return (stat(path.c_str(), &sts) == 0 && S_ISREG(sts.st_mode)) ? true : false; } bool is_directory(const std::string& path) { struct stat sts; - return (stat(path.c_str(), &sts) == 0 && S_ISDIR(sts.st_mode)) ? true: false; + return (stat(path.c_str(), &sts) == 0 && S_ISDIR(sts.st_mode)) ? true : false; } void make_directory(const std::string& path) { int result = mkdir(path.c_str(), 0777); if (result != 0) { - throw std::runtime_error("Error creating directory: " + - std::string(std::strerror(errno))); + throw std::runtime_error("Error creating directory: " + std::string(std::strerror(errno))); } } size_t file_size(const std::string& path) { struct stat sts; - return (stat(path.c_str(), &sts) == 0) ? sts.st_size: 0; + return (stat(path.c_str(), &sts) == 0) ? sts.st_size : 0; } void move_file(const std::string& src, const std::string& dst) { int result = std::rename(src.c_str(), dst.c_str()); if (result != 0) - throw std::runtime_error("Error moving file: " + - std::string(std::strerror(errno))); + throw std::runtime_error("Error moving file: " + std::string(std::strerror(errno))); } -void copy_file(const std::string& src_fn, const std::string& dst_fn, - const bool overwrite) +void copy_file(const std::string& src_fn, const std::string& dst_fn, const bool overwrite) { // First copy the file content FileHandle src = open_file(src_fn, "rb"); if (!src) { - throw std::runtime_error("Cannot open source file " + - std::string(std::strerror(errno))); + throw std::runtime_error("Cannot open source file " + std::string(std::strerror(errno))); } FileHandle dst = open_file(dst_fn, "wb"); if (!dst) { - throw std::runtime_error("Cannot open destination file " + - std::string(std::strerror(errno))); + throw std::runtime_error("Cannot open destination file " + std::string(std::strerror(errno))); } // Copy data in 4KB chunks @@ -114,8 +109,7 @@ void delete_file(const std::string& path) { int result = unlink(path.c_str()); if (result != 0) - throw std::runtime_error("Error deleting file: " + - std::string(std::strerror(errno))); + throw std::runtime_error("Error deleting file: " + std::string(std::strerror(errno))); } bool has_readonly_attr(const std::string& path) @@ -145,17 +139,14 @@ Time get_modification_time(const std::string& path) std::tm t; safe_localtime(sts.st_mtime, &t); - return Time( - t.tm_year+1900, t.tm_mon+1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec); + return Time(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); } void remove_directory(const std::string& path) { int result = rmdir(path.c_str()); if (result != 0) - throw std::runtime_error("Error removing directory: " + - std::string(std::strerror(errno))); + throw std::runtime_error("Error removing directory: " + std::string(std::strerror(errno))); } std::string get_current_path() @@ -183,8 +174,8 @@ std::string get_app_path() size_t size = path.size(); const int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; while (sysctl(mib, 4, &path[0], &size, NULL, 0) == -1) - path.resize(size); -#else // Linux + path.resize(size); +#else // Linux if (readlink("/proc/self/exe", &path[0], path.size()) == -1) return std::string(); #endif @@ -215,7 +206,7 @@ std::string get_canonical_path(const std::string& path) // Ignore return value as realpath() returns nullptr anyway when the // resolved_path parameter is specified. if (realpath(full.c_str(), buffer)) - return buffer; // No error, the file/dir exists + return buffer; // No error, the file/dir exists return std::string(); } @@ -226,7 +217,7 @@ std::string get_absolute_path(const std::string& path) full = join_path(get_current_path(), full); full = normalize_path(full); if (!full.empty() && full.back() == path_separator) - full.erase(full.size()-1); + full.erase(full.size() - 1); return full; } @@ -251,7 +242,7 @@ paths list_files(const std::string& path, ItemType filter, const std::string& ma if (fnmatch(match.c_str(), item->d_name, FNM_CASEFOLD) == FNM_NOMATCH) continue; - + files.push_back(item->d_name); } @@ -259,4 +250,4 @@ paths list_files(const std::string& path, ItemType filter, const std::string& ma return files; } -} +} // namespace base diff --git a/base/fs_win32.h b/base/fs_win32.h index 9d5424145..925436ef4 100644 --- a/base/fs_win32.h +++ b/base/fs_win32.h @@ -12,10 +12,10 @@ #include "base/version.h" #include "base/win/win32_exception.h" -#include -#include #include +#include #include +#include namespace base { @@ -25,8 +25,7 @@ bool is_file(const std::string& path) // GetFileAttributes returns INVALID_FILE_ATTRIBUTES in case of // fail. - return ((attr != INVALID_FILE_ATTRIBUTES) && - !(attr & FILE_ATTRIBUTE_DIRECTORY)); + return ((attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_DIRECTORY)); } bool is_directory(const std::string& path) @@ -40,7 +39,7 @@ bool is_directory(const std::string& path) size_t file_size(const std::string& path) { struct _stat sts; - return (_wstat(from_utf8(path).c_str(), &sts) == 0) ? sts.st_size: 0; + return (_wstat(from_utf8(path).c_str(), &sts) == 0) ? sts.st_size : 0; } void move_file(const std::string& src, const std::string& dst) @@ -96,9 +95,7 @@ Time get_modification_time(const std::string& path) FileTimeToSystemTime(&data.ftLastWriteTime, &utc); SystemTimeToTzSpecificLocalTime(NULL, &utc, &local); - return Time( - local.wYear, local.wMonth, local.wDay, - local.wHour, local.wMinute, local.wSecond); + return Time(local.wYear, local.wMonth, local.wDay, local.wHour, local.wMinute, local.wSecond); } void make_directory(const std::string& path) @@ -117,8 +114,8 @@ void remove_directory(const std::string& path) std::string get_current_path() { - TCHAR buffer[MAX_PATH+1]; - if (::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), buffer)) + TCHAR buffer[MAX_PATH + 1]; + if (::GetCurrentDirectory(sizeof(buffer) / sizeof(TCHAR), buffer)) return to_utf8(buffer); return std::string(); } @@ -130,25 +127,23 @@ void set_current_path(const std::string& path) std::string get_app_path() { - TCHAR buffer[MAX_PATH+1]; - if (::GetModuleFileName(NULL, buffer, sizeof(buffer)/sizeof(TCHAR))) + TCHAR buffer[MAX_PATH + 1]; + if (::GetModuleFileName(NULL, buffer, sizeof(buffer) / sizeof(TCHAR))) return to_utf8(buffer); return std::string(); } std::string get_temp_path() { - TCHAR buffer[MAX_PATH+1]; - DWORD result = ::GetTempPath(sizeof(buffer)/sizeof(TCHAR), buffer); + TCHAR buffer[MAX_PATH + 1]; + DWORD result = ::GetTempPath(sizeof(buffer) / sizeof(TCHAR), buffer); return to_utf8(buffer); } std::string get_user_docs_folder() { - TCHAR buffer[MAX_PATH+1]; - HRESULT hr = SHGetFolderPath( - NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, - buffer); + TCHAR buffer[MAX_PATH + 1]; + HRESULT hr = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buffer); if (hr == S_OK) return to_utf8(buffer); return std::string(); @@ -171,18 +166,12 @@ std::string get_absolute_path(const std::string& path) else full = path; - TCHAR buffer[MAX_PATH+1]; - GetFullPathName( - from_utf8(full).c_str(), - sizeof(buffer)/sizeof(TCHAR), - buffer, - nullptr); + TCHAR buffer[MAX_PATH + 1]; + GetFullPathName(from_utf8(full).c_str(), sizeof(buffer) / sizeof(TCHAR), buffer, nullptr); return to_utf8(buffer); } -paths list_files(const std::string& path, - ItemType filter, - const std::string& match) +paths list_files(const std::string& path, ItemType filter, const std::string& match) { WIN32_FIND_DATA fd; paths files; @@ -190,8 +179,7 @@ paths list_files(const std::string& path, base::from_utf8(base::join_path(path, match)).c_str(), FindExInfoBasic, &fd, - (filter == ItemType::Directories) ? FindExSearchLimitToDirectories : - FindExSearchNameMatch, + (filter == ItemType::Directories) ? FindExSearchLimitToDirectories : FindExSearchNameMatch, NULL, 0); @@ -203,8 +191,7 @@ paths list_files(const std::string& path, if (filter == ItemType::Files) continue; - if (lstrcmpW(fd.cFileName, L".") == 0 || - lstrcmpW(fd.cFileName, L"..") == 0) + if (lstrcmpW(fd.cFileName, L".") == 0 || lstrcmpW(fd.cFileName, L"..") == 0) continue; } else if (filter == ItemType::Directories) @@ -236,14 +223,15 @@ Version get_file_version(const wchar_t* filename) VS_FIXEDFILEINFO* fi = nullptr; UINT fiLen = 0; - if (!VerQueryValueW(&data[0], L"\\", (LPVOID*)&fi, &fiLen) || - fiLen < sizeof(VS_FIXEDFILEINFO) || + if (!VerQueryValueW(&data[0], L"\\", (LPVOID*)&fi, &fiLen) || fiLen < sizeof(VS_FIXEDFILEINFO) || fi->dwSignature != 0xfeef04bd) { return Version(); } - return Version(fi->dwFileVersionMS >> 16, fi->dwFileVersionMS & 0xffff, - fi->dwFileVersionLS >> 16, fi->dwFileVersionLS & 0xffff); + return Version(fi->dwFileVersionMS >> 16, + fi->dwFileVersionMS & 0xffff, + fi->dwFileVersionLS >> 16, + fi->dwFileVersionLS & 0xffff); } -} +} // namespace base diff --git a/base/gcd.h b/base/gcd.h index f19bf12e1..8731acd4c 100644 --- a/base/gcd.h +++ b/base/gcd.h @@ -10,27 +10,28 @@ namespace base { - template - T gcd(T a, T b) { - a = (a < 0 ? -a: a); - b = (b < 0 ? -b: b); - if (a > 1 && b > 1) { - if (a == b) +template +T gcd(T a, T b) +{ + a = (a < 0 ? -a : a); + b = (b < 0 ? -b : b); + if (a > 1 && b > 1) { + if (a == b) + return a; + while (a != b) { + if (a > b) { + a = a - b; + } + else if (a < b) { + b = b - a; + } + if (a == b) { return a; - while (a != b) { - if (a > b) { - a = a - b; - } - else if (a < b) { - b = b - a; - } - if (a == b) { - return a; - } } } - return T(1); } + return T(1); +} } // namespace base diff --git a/base/hex.h b/base/hex.h index 2423e4810..dad69a50e 100644 --- a/base/hex.h +++ b/base/hex.h @@ -11,18 +11,21 @@ namespace base { - inline bool is_hex_digit(const char c) { - return ((c >= '0' && c <= '9') || - (c >= 'A' && c <= 'F') || - (c >= 'a' && c <= 'f')); - } +inline bool is_hex_digit(const char c) +{ + return ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')); +} - inline int hex_to_int(const char c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - return 0; - } +inline int hex_to_int(const char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + return 0; +} } // namespace base diff --git a/base/launcher.cpp b/base/launcher.cpp index fb80b126a..0d60482a3 100644 --- a/base/launcher.cpp +++ b/base/launcher.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/exception.h" @@ -17,10 +17,10 @@ #include #if LAF_WINDOWS -#include -#ifndef SEE_MASK_DEFAULT -#define SEE_MASK_DEFAULT 0x00000000 -#endif + #include + #ifndef SEE_MASK_DEFAULT + #define SEE_MASK_DEFAULT 0x00000000 + #endif static int win32_shell_execute(const wchar_t* verb, const wchar_t* file, const wchar_t* params) { @@ -35,7 +35,7 @@ static int win32_shell_execute(const wchar_t* verb, const wchar_t* file, const w if (!ShellExecuteEx(&sh)) { int ret = GetLastError(); -#if 0 + #if 0 if (ret != 0) { DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | @@ -53,16 +53,15 @@ static int win32_shell_execute(const wchar_t* verb, const wchar_t* file, const w ret = 0; } } -#endif + #endif return ret; } else return 0; } -#endif // LAF_WINDOWS +#endif // LAF_WINDOWS -namespace base { -namespace launcher { +namespace base { namespace launcher { bool open_url(const std::string& url) { @@ -75,15 +74,14 @@ bool open_file(const std::string& file) #if LAF_WINDOWS - ret = win32_shell_execute(L"open", - base::from_utf8(file).c_str(), NULL); + ret = win32_shell_execute(L"open", base::from_utf8(file).c_str(), NULL); #elif HAVE_SYSTEM #if __APPLE__ - ret = std::system(("open \"" + file + "\"").c_str()); + ret = std::system(("open \"" + file + "\"").c_str()); #else - ret = std::system(("setsid xdg-open \"" + file + "\"").c_str()); + ret = std::system(("setsid xdg-open \"" + file + "\"").c_str()); #endif #endif @@ -99,12 +97,13 @@ bool open_folder(const std::string& _file) int ret; if (base::is_directory(file)) { - ret = win32_shell_execute(NULL, L"explorer", - (L"/n,/e,\"" + base::from_utf8(file) + L"\"").c_str()); + ret = + win32_shell_execute(NULL, L"explorer", (L"/n,/e,\"" + base::from_utf8(file) + L"\"").c_str()); } else { - ret = win32_shell_execute(NULL, L"explorer", - (L"/e,/select,\"" + base::from_utf8(file) + L"\"").c_str()); + ret = win32_shell_execute(NULL, + L"explorer", + (L"/e,/select,\"" + base::from_utf8(file) + L"\"").c_str()); } return (ret == 0); @@ -112,29 +111,28 @@ bool open_folder(const std::string& _file) #if __APPLE__ - int ret; - if (base::is_directory(file)) - ret = std::system(("open \"" + file + "\"").c_str()); - else - ret = std::system(("open --reveal \"" + file + "\"").c_str()); - return (ret == 0); + int ret; + if (base::is_directory(file)) + ret = std::system(("open \"" + file + "\"").c_str()); + else + ret = std::system(("open --reveal \"" + file + "\"").c_str()); + return (ret == 0); #else - if (!base::is_directory(file)) - file = base::get_file_path(file); + if (!base::is_directory(file)) + file = base::get_file_path(file); - const int ret = std::system(("setsid xdg-open \"" + file + "\"").c_str()); - return (ret == 0); + const int ret = std::system(("setsid xdg-open \"" + file + "\"").c_str()); + return (ret == 0); #endif -#else // HAVE_SYSTEM +#else // HAVE_SYSTEM return false; #endif } -} // namespace launcher -} // namespace base +}} // namespace base::launcher diff --git a/base/launcher.h b/base/launcher.h index 949724379..05bb3459f 100644 --- a/base/launcher.h +++ b/base/launcher.h @@ -10,14 +10,12 @@ #include -namespace base { -namespace launcher { +namespace base { namespace launcher { bool open_url(const std::string& url); bool open_file(const std::string& file); bool open_folder(const std::string& file); -} // namespace launcher -} // namespace base +}} // namespace base::launcher #endif diff --git a/base/log.cpp b/base/log.cpp index 745e6311f..5d579d89a 100644 --- a/base/log.cpp +++ b/base/log.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/log.h" @@ -70,9 +70,9 @@ static void LOGva(const char* format, va_list ap) const int size = std::vsnprintf(nullptr, 0, format, apTmp); va_end(apTmp); if (size < 1) - return; // Nothing to log + return; // Nothing to log - std::vector buf(size+1); + std::vector buf(size + 1); std::vsnprintf(buf.data(), buf.size(), format, ap); { diff --git a/base/log.h b/base/log.h index 6135f22c4..2d5f6384a 100644 --- a/base/log.h +++ b/base/log.h @@ -8,33 +8,33 @@ // Always undefine ERROR macro just in case (so we can include // base/log.h as the last header file) #ifdef ERROR -#undef ERROR + #undef ERROR #endif #ifndef BASE_LOG_H_INCLUDED -#define BASE_LOG_H_INCLUDED + #define BASE_LOG_H_INCLUDED // Don't use pragma once because we want to undef ERROR each time this // file is included. -//#pragma once +// #pragma once enum LogLevel { - NONE = 0, // Default log level: do not log - FATAL = 1, // Something failed and we CANNOT continue the execution - ERROR = 2, // Something failed, the UI should show this, and we can continue + NONE = 0, // Default log level: do not log + FATAL = 1, // Something failed and we CANNOT continue the execution + ERROR = 2, // Something failed, the UI should show this, and we can continue WARNING = 3, // Something failed, the UI don't need to show this, and we can continue - INFO = 4, // Information about some important event + INFO = 4, // Information about some important event VERBOSE = 5, // Information step by step }; -#ifdef __cplusplus -#include + #ifdef __cplusplus + #include namespace base { - void set_log_filename(const char* filename); - void set_log_level(LogLevel level); - LogLevel get_log_level(); +void set_log_filename(const char* filename); +void set_log_level(LogLevel level); +LogLevel get_log_level(); } // namespace base @@ -42,7 +42,8 @@ namespace base { void LOG(const char* format, ...); void LOG(LogLevel level, const char* format, ...); -inline void LOG(int) { +inline void LOG(int) +{ // This is in case LOG() is used with an integer value instead of // LogLevel, an error must be triggered (e.g. on wingdi.h ERROR is // defined as 0, and with this definition we avoid calling LOG(const @@ -50,6 +51,6 @@ inline void LOG(int) { // time. } -#endif + #endif #endif diff --git a/base/mask_shift.h b/base/mask_shift.h index b9a82ad90..21e58267a 100644 --- a/base/mask_shift.h +++ b/base/mask_shift.h @@ -10,17 +10,18 @@ namespace base { - template - int mask_shift(T mask) { - int shift = 0; - int bit = 1; - while (((mask & bit) == 0) && shift < 8*sizeof(mask)) { - bit <<= 1; - ++shift; - } - return shift; +template +int mask_shift(T mask) +{ + int shift = 0; + int bit = 1; + while (((mask & bit) == 0) && shift < 8 * sizeof(mask)) { + bit <<= 1; + ++shift; } - + return shift; } +} // namespace base + #endif diff --git a/base/mem_utils.cpp b/base/mem_utils.cpp index 692b3b5ba..eb1062ec9 100644 --- a/base/mem_utils.cpp +++ b/base/mem_utils.cpp @@ -6,11 +6,11 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif -#include #include +#include namespace base { @@ -23,11 +23,11 @@ string get_pretty_memory_size(size_t memsize) if (memsize < 1000) { std::snprintf(buf, sizeof(buf), "%zu bytes", memsize); } - else if (memsize < 1000*1000) { - std::snprintf(buf, sizeof(buf), "%0.1fK", memsize/1024.0f); + else if (memsize < 1000 * 1000) { + std::snprintf(buf, sizeof(buf), "%0.1fK", memsize / 1024.0f); } else { - std::snprintf(buf, sizeof(buf), "%0.1fM", memsize/(1024.0f*1024.0f)); + std::snprintf(buf, sizeof(buf), "%0.1fM", memsize / (1024.0f * 1024.0f)); } return buf; diff --git a/base/mem_utils.h b/base/mem_utils.h index 826dbeeaf..8c05bfde9 100644 --- a/base/mem_utils.h +++ b/base/mem_utils.h @@ -12,7 +12,7 @@ namespace base { - std::string get_pretty_memory_size(std::size_t memsize); +std::string get_pretty_memory_size(std::size_t memsize); } // namespace base diff --git a/base/memory.cpp b/base/memory.cpp index 5ac2ec213..153e4c82d 100644 --- a/base/memory.cpp +++ b/base/memory.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/debug.h" @@ -19,7 +19,7 @@ using namespace std; -#if !defined LAF_MEMLEAK // Without leak detection +#if !defined LAF_MEMLEAK // Without leak detection void* base_malloc(size_t bytes) { @@ -45,25 +45,25 @@ void base_free(void* mem) char* base_strdup(const char* string) { assert(string); -#ifdef _MSC_VER + #ifdef _MSC_VER return _strdup(string); -#else + #else return strdup(string); -#endif + #endif } -#else // With leak detection +#else // With leak detection -#define BACKTRACE_LEVELS 16 + #define BACKTRACE_LEVELS 16 -#ifdef _MSC_VER - #include + #ifdef _MSC_VER + #include - #include + #include - typedef USHORT (WINAPI* RtlCaptureStackBackTraceType)(ULONG, ULONG, PVOID*, PULONG); - static RtlCaptureStackBackTraceType pRtlCaptureStackBackTrace; -#endif +typedef USHORT(WINAPI* RtlCaptureStackBackTraceType)(ULONG, ULONG, PVOID*, PULONG); +static RtlCaptureStackBackTraceType pRtlCaptureStackBackTrace; + #endif struct slot_t { void* backtrace[BACKTRACE_LEVELS]; @@ -78,12 +78,11 @@ static std::mutex g_mutex; void base_memleak_init() { -#ifdef _MSC_VER - pRtlCaptureStackBackTrace = - (RtlCaptureStackBackTraceType)(::GetProcAddress( - ::LoadLibrary(L"kernel32.dll"), - "RtlCaptureStackBackTrace")); -#endif + #ifdef _MSC_VER + pRtlCaptureStackBackTrace = (RtlCaptureStackBackTraceType)(::GetProcAddress( + ::LoadLibrary(L"kernel32.dll"), + "RtlCaptureStackBackTrace")); + #endif assert(!memleak_status); @@ -101,7 +100,7 @@ void base_memleak_exit() slot_t* it; if (f != NULL) { -#ifdef _MSC_VER + #ifdef _MSC_VER struct SYMBOL_INFO_EX { IMAGEHLP_SYMBOL64 header; char filename[MAX_SYM_NAME]; @@ -121,14 +120,14 @@ void base_memleak_exit() char filename[MAX_PATH]; ::GetModuleFileNameA(NULL, filename, sizeof(filename) / sizeof(filename[0])); ::SymLoadModule64(hproc, NULL, filename, NULL, 0, 0); -#endif + #endif // Memory leaks - for (it=headslot; it!=NULL; it=it->next) { + for (it = headslot; it != NULL; it = it->next) { fprintf(f, "\nLEAK address: %p, size: %lu\n", it->ptr, it->size); - for (int c=0; cbacktrace[c], &displacement, &line)) { @@ -136,21 +135,23 @@ void base_memleak_exit() ::SymGetSymFromAddr64(hproc, (DWORD)it->backtrace[c], NULL, &si.header); - fprintf(f, "%p : %s(%lu) [%s]\n", + fprintf(f, + "%p : %s(%lu) [%s]\n", it->backtrace[c], - line.FileName, line.LineNumber, + line.FileName, + line.LineNumber, si.header.Name); } else -#endif + #endif fprintf(f, "%p\n", it->backtrace[c]); } } fclose(f); -#ifdef _MSC_VER + #ifdef _MSC_VER ::SymCleanup(hproc); -#endif + #endif } } @@ -164,21 +165,21 @@ static void addslot(void* ptr, size_t size) assert(ptr); // __builtin_return_address is a GCC extension -#if defined(__GNUC__) + #if defined(__GNUC__) p->backtrace[0] = __builtin_return_address(4); p->backtrace[1] = __builtin_return_address(3); p->backtrace[2] = __builtin_return_address(2); p->backtrace[3] = __builtin_return_address(1); -#elif defined(_MSC_VER) + #elif defined(_MSC_VER) { - for (int c=0; cbacktrace[c] = 0; pRtlCaptureStackBackTrace(0, BACKTRACE_LEVELS, p->backtrace, NULL); } -#else - #error Not supported -#endif + #else + #error Not supported + #endif p->ptr = ptr; p->size = size; @@ -199,7 +200,7 @@ static void delslot(void* ptr) const std::lock_guard lock(g_mutex); - for (it=headslot; it!=nullptr; prev=it, it=it->next) { + for (it = headslot; it != nullptr; prev = it, it = it->next) { if (it->ptr == ptr) { if (prev) prev->next = it->next; diff --git a/base/memory.h b/base/memory.h index 0d6f6ffc5..394e7d021 100644 --- a/base/memory.h +++ b/base/memory.h @@ -12,31 +12,31 @@ #ifdef __cplusplus #ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__ - static constexpr size_t base_alignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__; +static constexpr size_t base_alignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__; #else - static constexpr size_t base_alignment = 1; +static constexpr size_t base_alignment = 1; #endif - constexpr size_t base_align_size(const size_t n, - const size_t alignment = base_alignment) { - size_t remaining = (n % alignment); - size_t aligned_n = n + (remaining ? (alignment - remaining): 0); - if (aligned_n > alignment) - return aligned_n; - return alignment; - } +constexpr size_t base_align_size(const size_t n, const size_t alignment = base_alignment) +{ + size_t remaining = (n % alignment); + size_t aligned_n = n + (remaining ? (alignment - remaining) : 0); + if (aligned_n > alignment) + return aligned_n; + return alignment; +} #endif -void* base_malloc (std::size_t bytes); +void* base_malloc(std::size_t bytes); void* base_malloc0(std::size_t bytes); void* base_realloc(void* mem, std::size_t bytes); -void base_free (void* mem); -char* base_strdup (const char* string); +void base_free(void* mem); +char* base_strdup(const char* string); #ifdef __cplusplus - void* base_aligned_alloc(std::size_t bytes, std::size_t alignment = base_alignment); +void* base_aligned_alloc(std::size_t bytes, std::size_t alignment = base_alignment); #else - void* base_aligned_alloc(std::size_t bytes, std::size_t alignment); +void* base_aligned_alloc(std::size_t bytes, std::size_t alignment); #endif void base_aligned_free(void* mem); diff --git a/base/memory_dump.cpp b/base/memory_dump.cpp index dffd3756f..feaf55453 100644 --- a/base/memory_dump.cpp +++ b/base/memory_dump.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/memory_dump.h" @@ -19,8 +19,7 @@ namespace base { -MemoryDump::MemoryDump() - : m_impl(new MemoryDumpImpl) +MemoryDump::MemoryDump() : m_impl(new MemoryDumpImpl) { } diff --git a/base/memory_dump_none.h b/base/memory_dump_none.h index 094d4f491..e2500eaf4 100644 --- a/base/memory_dump_none.h +++ b/base/memory_dump_none.h @@ -8,18 +8,20 @@ #define BASE_MEMORY_DUMP_NONE_H_INCLUDED #pragma once -class base::MemoryDump::MemoryDumpImpl -{ +class base::MemoryDump::MemoryDumpImpl { public: - MemoryDumpImpl() { + MemoryDumpImpl() + { // Do nothing } - ~MemoryDumpImpl() { + ~MemoryDumpImpl() + { // Do nothing } - void setFileName(const std::string& fileName) { + void setFileName(const std::string& fileName) + { // Do nothing } }; diff --git a/base/memory_dump_win32.h b/base/memory_dump_win32.h index 58872ab17..f97d9770d 100644 --- a/base/memory_dump_win32.h +++ b/base/memory_dump_win32.h @@ -19,23 +19,20 @@ static std::wstring memoryDumpFile; -class base::MemoryDump::MemoryDumpImpl -{ +class base::MemoryDump::MemoryDumpImpl { public: - MemoryDumpImpl() { + MemoryDumpImpl() + { memoryDumpFile = L"memory.dmp"; ::SetUnhandledExceptionFilter(MemoryDumpImpl::unhandledException); } - ~MemoryDumpImpl() { - ::SetUnhandledExceptionFilter(NULL); - } + ~MemoryDumpImpl() { ::SetUnhandledExceptionFilter(NULL); } - void setFileName(const std::string& fileName) { - memoryDumpFile = base::from_utf8(fileName); - } + void setFileName(const std::string& fileName) { memoryDumpFile = base::from_utf8(fileName); } - static LONG WINAPI unhandledException(_EXCEPTION_POINTERS* exceptionPointers) { + static LONG WINAPI unhandledException(_EXCEPTION_POINTERS* exceptionPointers) + { MemoryDumpImpl::createMemoryDump(exceptionPointers); return EXCEPTION_EXECUTE_HANDLER; } @@ -43,35 +40,39 @@ class base::MemoryDump::MemoryDumpImpl private: class MemoryDumpFile { public: - MemoryDumpFile() { + MemoryDumpFile() + { m_handle = ::CreateFile(memoryDumpFile.c_str(), - GENERIC_WRITE, 0, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - } - ~MemoryDumpFile() { - ::CloseHandle(m_handle); + GENERIC_WRITE, + 0, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); } + ~MemoryDumpFile() { ::CloseHandle(m_handle); } HANDLE handle() { return m_handle; } + private: HANDLE m_handle; }; - static void createMemoryDump(_EXCEPTION_POINTERS* exceptionPointers) { + static void createMemoryDump(_EXCEPTION_POINTERS* exceptionPointers) + { MemoryDumpFile file; MINIDUMP_EXCEPTION_INFORMATION ei; - ei.ThreadId = GetCurrentThreadId(); - ei.ExceptionPointers = exceptionPointers; - ei.ClientPointers = FALSE; + ei.ThreadId = GetCurrentThreadId(); + ei.ExceptionPointers = exceptionPointers; + ei.ClientPointers = FALSE; ::MiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(), file.handle(), MiniDumpNormal, - (exceptionPointers ? &ei: NULL), + (exceptionPointers ? &ei : NULL), NULL, NULL); - } }; diff --git a/base/paths.h b/base/paths.h index 65f0bc019..dc6efd940 100644 --- a/base/paths.h +++ b/base/paths.h @@ -13,7 +13,7 @@ namespace base { - typedef std::vector paths; +typedef std::vector paths; } // namespace base diff --git a/base/pi.h b/base/pi.h index 4a9dba3d2..5105f2b55 100644 --- a/base/pi.h +++ b/base/pi.h @@ -10,7 +10,7 @@ #pragma once #ifndef PI -#define PI 3.14159265358979323846 + #define PI 3.14159265358979323846 #endif #include @@ -18,19 +18,20 @@ namespace base { // Puts the angle in the -PI to PI range. -inline double fmod_radians(double angle) { +inline double fmod_radians(double angle) +{ if (angle < -PI) { - if (angle < -2.0*PI) - angle = -std::fmod(-angle, 2.0*PI); - angle += 2.0*PI; + if (angle < -2.0 * PI) + angle = -std::fmod(-angle, 2.0 * PI); + angle += 2.0 * PI; } - if (angle > 2.0*PI) - angle = std::fmod(angle, 2.0*PI); + if (angle > 2.0 * PI) + angle = std::fmod(angle, 2.0 * PI); if (angle > PI) - angle -= 2.0*PI; + angle -= 2.0 * PI; return angle; } -} +} // namespace base #endif diff --git a/base/pi_tests.cpp b/base/pi_tests.cpp index e6ac39b52..1aeb57170 100644 --- a/base/pi_tests.cpp +++ b/base/pi_tests.cpp @@ -13,17 +13,17 @@ using namespace base; TEST(Pi, FModRadians) { EXPECT_DOUBLE_EQ(0.0, fmod_radians(0.0)); - EXPECT_DOUBLE_EQ(0.0, fmod_radians(2*PI)); + EXPECT_DOUBLE_EQ(0.0, fmod_radians(2 * PI)); EXPECT_DOUBLE_EQ(PI, fmod_radians(PI)); EXPECT_DOUBLE_EQ(-PI, fmod_radians(-PI)); - EXPECT_DOUBLE_EQ(-3*PI/4, fmod_radians(5*PI/4)); - EXPECT_DOUBLE_EQ(-3*PI/4, fmod_radians(5*PI/4 + 2*PI)); - EXPECT_DOUBLE_EQ(PI/2, fmod_radians(10*PI/4)); + EXPECT_DOUBLE_EQ(-3 * PI / 4, fmod_radians(5 * PI / 4)); + EXPECT_DOUBLE_EQ(-3 * PI / 4, fmod_radians(5 * PI / 4 + 2 * PI)); + EXPECT_DOUBLE_EQ(PI / 2, fmod_radians(10 * PI / 4)); - for (double a=-100*PI; a<=100*PI; a+=PI/4) { + for (double a = -100 * PI; a <= 100 * PI; a += PI / 4) { double b = fmod_radians(a); - EXPECT_GE(b, -PI-1e-10) << a << " radians, " << (180.0 * a / PI) << " degrees"; - EXPECT_LE(b, +PI+1e-10) << a << " radians, " << (180.0 * a / PI) << " degrees"; + EXPECT_GE(b, -PI - 1e-10) << a << " radians, " << (180.0 * a / PI) << " degrees"; + EXPECT_LE(b, +PI + 1e-10) << a << " radians, " << (180.0 * a / PI) << " degrees"; } } diff --git a/base/platform.cpp b/base/platform.cpp index 0fc9874c0..8743dfb5c 100644 --- a/base/platform.cpp +++ b/base/platform.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/platform.h" @@ -13,8 +13,8 @@ #if LAF_WINDOWS #include - typedef LONG (WINAPI* RtlGetVersion_Func)(OSVERSIONINFOEX*); -#elif LAF_LINUX // Unix-like system +typedef LONG(WINAPI* RtlGetVersion_Func)(OSVERSIONINFOEX*); +#elif LAF_LINUX // Unix-like system #include #endif @@ -36,31 +36,22 @@ Platform get_platform() // after Windows 8 and RtlGetVersion() returns the correct version // and build number for Windows 10 and 11. static const auto fnRtlGetVersion = reinterpret_cast( - GetProcAddress(GetModuleHandle(L"ntdll.dll"), - "RtlGetVersion")); - if (!fnRtlGetVersion || - !fnRtlGetVersion(&osv) || - !osv.dwMajorVersion) { + GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlGetVersion")); + if (!fnRtlGetVersion || !fnRtlGetVersion(&osv) || !osv.dwMajorVersion) { OSVERSIONINFOEX osv; osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); // Ignore deprecated function warning -#pragma warning(push) -#pragma warning(disable : 4996) + #pragma warning(push) + #pragma warning(disable : 4996) GetVersionEx((OSVERSIONINFO*)&osv); -#pragma warning(pop) + #pragma warning(pop) } - p.osVer = Version(osv.dwMajorVersion, - osv.dwMinorVersion, - osv.dwBuildNumber, 0); + p.osVer = Version(osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber, 0); switch (osv.wProductType) { case VER_NT_DOMAIN_CONTROLLER: - case VER_NT_SERVER: - p.windowsType = Platform::WindowsType::Server; - break; - case VER_NT_WORKSTATION: - p.windowsType = Platform::WindowsType::NT; - break; + case VER_NT_SERVER: p.windowsType = Platform::WindowsType::Server; break; + case VER_NT_WORKSTATION: p.windowsType = Platform::WindowsType::NT; break; } p.servicePack = Version(osv.wServicePackMajor, osv.wServicePackMinor, 0, 0); diff --git a/base/platform.h b/base/platform.h index 03ac3ac4b..7c7b65950 100644 --- a/base/platform.h +++ b/base/platform.h @@ -28,9 +28,9 @@ struct Platform { }; enum class Arch { - x86, // Windows 32-bit, Linux 32-bit - x64, // Windows 64-bit, Mac Intel - arm64, // Mac Apple Silicon (M1, M1 Pro), Raspberry Pi? + x86, // Windows 32-bit, Linux 32-bit + x64, // Windows 64-bit, Mac Intel + arm64, // Mac Apple Silicon (M1, M1 Pro), Raspberry Pi? }; static constexpr OS os = @@ -41,7 +41,7 @@ struct Platform { #else OS::Linux #endif - ; + ; static constexpr Arch arch = #if defined(__arm64__) || defined(__aarch64__) @@ -54,8 +54,7 @@ struct Platform { ; static_assert((arch == Arch::x86 && sizeof(void*) == 4) || - ((arch == Arch::x64 || - arch == Arch::arm64) && sizeof(void*) == 8), + ((arch == Arch::x64 || arch == Arch::arm64) && sizeof(void*) == 8), "Invalid identification of CPU architecture"); Version osVer; @@ -63,34 +62,33 @@ struct Platform { #if LAF_WINDOWS enum class WindowsType { Unknown, Server, NT }; WindowsType windowsType = WindowsType::Unknown; - Version servicePack; // Service pack version - bool isWow64 = false; // 32-bit version running on 64-bit + Version servicePack; // Service pack version + bool isWow64 = false; // 32-bit version running on 64-bit const char* wineVer = nullptr; // Are we running on Wine emulator? #elif LAF_MACOS - // Nothing extra (macOS version on "osVer" field) + // Nothing extra (macOS version on "osVer" field) #elif LAF_LINUX - std::string distroName; // Linux distribution name - std::string distroVer; // Distribution version + std::string distroName; // Linux distribution name + std::string distroVer; // Distribution version #endif - }; Platform get_platform(); #if LAF_WINDOWS - bool is_wow64(); - const char* get_wine_version(); +bool is_wow64(); +const char* get_wine_version(); #elif LAF_MACOS - Version get_osx_version(); +Version get_osx_version(); #elif LAF_LINUX - // Reads all the information of the current Linux distro from - // /etc/os-release or /etc/lsb-release (you specify the filename) - std::map get_linux_release_info(const std::string& fn); +// Reads all the information of the current Linux distro from +// /etc/os-release or /etc/lsb-release (you specify the filename) +std::map get_linux_release_info(const std::string& fn); #endif diff --git a/base/platform_osx.mm b/base/platform_osx.mm index 6d5ffaec1..e2489d5f3 100644 --- a/base/platform_osx.mm +++ b/base/platform_osx.mm @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/platform.h" diff --git a/base/platform_unix.cpp b/base/platform_unix.cpp index 062033a5d..f65cb6a2d 100644 --- a/base/platform_unix.cpp +++ b/base/platform_unix.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/platform.h" @@ -28,7 +28,7 @@ std::map get_linux_release_info(const std::string& fn) std::string value; while (std::fgets(buf.data(), buf.size(), f.get())) { - for (auto i=buf.begin(), end=buf.end(); i != end; ++i) { + for (auto i = buf.begin(), end = buf.end(); i != end; ++i) { // Commented line if (*i == '#') break; @@ -38,8 +38,7 @@ std::map get_linux_release_info(const std::string& fn) // Read the key if (*i >= 'A' && *i <= 'Z') { auto j = i; - while (j != end && ((*j >= 'A' && *j <= 'Z') || - (*j >= '0' && *j <= '9') || (*j == '_'))) { + while (j != end && ((*j >= 'A' && *j <= 'Z') || (*j >= '0' && *j <= '9') || (*j == '_'))) { ++j; } @@ -49,7 +48,7 @@ std::map get_linux_release_info(const std::string& fn) while (j != end && *j == ' ') ++j; if (j != end && *j == '=') { - ++j; // Skip '=' + ++j; // Skip '=' // Ignore white space between "KEY= ... VALUE" while (j != end && *j == ' ') ++j; @@ -71,9 +70,7 @@ std::map get_linux_release_info(const std::string& fn) } } else { - while (j != end && (*j != ' ' && - *j != '\r' && - *j != '\n')) { + while (j != end && (*j != ' ' && *j != '\r' && *j != '\n')) { value.push_back(*j); ++j; } diff --git a/base/platform_win.cpp b/base/platform_win.cpp index 02170f571..0698b261f 100644 --- a/base/platform_win.cpp +++ b/base/platform_win.cpp @@ -5,13 +5,13 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include -typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); -typedef const char* (CDECL* LPFN_WINE_GET_VERSION)(void); +typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); +typedef const char*(CDECL* LPFN_WINE_GET_VERSION)(void); static LPFN_ISWOW64PROCESS fnIsWow64Process = NULL; static LPFN_WINE_GET_VERSION fnWineGetVersion = NULL; @@ -21,23 +21,21 @@ namespace base { bool is_wow64() { if (!fnIsWow64Process) { - fnIsWow64Process = (LPFN_ISWOW64PROCESS) - GetProcAddress(GetModuleHandle(L"kernel32"), - "IsWow64Process"); + fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(L"kernel32"), + "IsWow64Process"); } BOOL isWow64 = FALSE; if (fnIsWow64Process) fnIsWow64Process(GetCurrentProcess(), &isWow64); - return isWow64 ? true: false; + return isWow64 ? true : false; } const char* get_wine_version() { if (!fnWineGetVersion) { - fnWineGetVersion = (LPFN_WINE_GET_VERSION) - GetProcAddress(GetModuleHandle(L"ntdll.dll"), - "wine_get_version"); + fnWineGetVersion = (LPFN_WINE_GET_VERSION)GetProcAddress(GetModuleHandle(L"ntdll.dll"), + "wine_get_version"); } if (fnWineGetVersion) return fnWineGetVersion(); diff --git a/base/process.cpp b/base/process.cpp index 4fa04a48f..90ae62fab 100644 --- a/base/process.cpp +++ b/base/process.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/process.h" @@ -62,7 +62,7 @@ std::string get_process_name(pid pid) HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid); if (handle) { WCHAR exeName[MAX_PATH]; - DWORD len = MAX_PATH-1; + DWORD len = MAX_PATH - 1; if (QueryFullProcessImageNameW(handle, 0, exeName, &len)) { name = base::get_file_name(base::to_utf8(exeName)); } @@ -83,17 +83,16 @@ bool is_process_running(pid pid) return (kill(pid, 0) == 0); } -#if LAF_MACOS + #if LAF_MACOS std::string get_process_name(pid pid) { struct proc_bsdinfo process; - proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, - &process, PROC_PIDTBSDINFO_SIZE); + proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &process, PROC_PIDTBSDINFO_SIZE); return process.pbi_name; } -#else + #else std::string get_process_name(pid pid) { @@ -110,8 +109,8 @@ std::string get_process_name(pid pid) return exename; } -#endif + #endif -#endif // LAF_WINDOWS +#endif // LAF_WINDOWS } // namespace base diff --git a/base/process.h b/base/process.h index 3e71bc14d..398027384 100644 --- a/base/process.h +++ b/base/process.h @@ -15,17 +15,17 @@ namespace base { - #ifdef LAF_WINDOWS - using pid = uint32_t; // DWORD - #else - using pid = int; - #endif +#ifdef LAF_WINDOWS +using pid = uint32_t; // DWORD +#else +using pid = int; +#endif - pid get_current_process_id(); +pid get_current_process_id(); - bool is_process_running(pid pid); +bool is_process_running(pid pid); - std::string get_process_name(pid pid); +std::string get_process_name(pid pid); } // namespace base diff --git a/base/program_options.cpp b/base/program_options.cpp index caee73105..69739d2ce 100644 --- a/base/program_options.cpp +++ b/base/program_options.cpp @@ -6,33 +6,30 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/program_options.h" #include -#include #include +#include namespace base { - struct same_name { const std::string& name; - same_name(const std::string& name) : name(name) { } - bool operator()(const ProgramOptions::Option* a) { - return (a->name() == name || - a->alias() == name); + same_name(const std::string& name) : name(name) {} + bool operator()(const ProgramOptions::Option* a) + { + return (a->name() == name || a->alias() == name); } }; struct same_mnemonic { char mnemonic; - same_mnemonic(char mnemonic) : mnemonic(mnemonic) { } - bool operator()(const ProgramOptions::Option* a) const { - return a->mnemonic() == mnemonic; - } + same_mnemonic(char mnemonic) : mnemonic(mnemonic) {} + bool operator()(const ProgramOptions::Option* a) const { return a->mnemonic() == mnemonic; } }; ProgramOptions::ProgramOptions() @@ -41,8 +38,7 @@ ProgramOptions::ProgramOptions() ProgramOptions::~ProgramOptions() { - for (OptionList::const_iterator - it=m_options.begin(), end=m_options.end(); it != end; ++it) + for (OptionList::const_iterator it = m_options.begin(), end = m_options.end(); it != end; ++it) delete *it; } @@ -55,14 +51,14 @@ ProgramOptions::Option& ProgramOptions::add(const std::string& name) void ProgramOptions::parse(int argc, const char* argv[]) { - for (int i=1; idoesRequireValue()) { if (usedBy != 0) { std::stringstream msg; - msg << "You cannot use '-" << option->mnemonic() - << "' and '-" << usedBy << "' " + msg << "You cannot use '-" << option->mnemonic() << "' and '-" << usedBy << "' " << "together, both options need one extra argument"; throw InvalidProgramOptionsCombination(msg.str()); } - if (i+1 >= argc) { + if (i + 1 >= argc) { std::stringstream msg; - msg << "Option '-" << option->mnemonic() - << "' needs one extra argument"; + msg << "Option '-" << option->mnemonic() << "' needs one extra argument"; throw ProgramOptionNeedsValue(msg.str()); } @@ -193,22 +187,26 @@ std::string ProgramOptions::value_of(const Option& option) const std::ostream& operator<<(std::ostream& os, const base::ProgramOptions& po) { std::size_t maxOptionWidth = 0; - for (base::ProgramOptions::OptionList::const_iterator - it=po.options().begin(), end=po.options().end(); it != end; ++it) { + for (base::ProgramOptions::OptionList::const_iterator it = po.options().begin(), + end = po.options().end(); + it != end; + ++it) { const base::ProgramOptions::Option* option = *it; const std::size_t optionWidth = - 6+std::max(option->name().size(), option->alias().size())+1+ - (option->doesRequireValue() ? option->getValueName().size()+1: 0); + 6 + std::max(option->name().size(), option->alias().size()) + 1 + + (option->doesRequireValue() ? option->getValueName().size() + 1 : 0); if (maxOptionWidth < optionWidth) maxOptionWidth = optionWidth; } - for (base::ProgramOptions::OptionList::const_iterator - it=po.options().begin(), end=po.options().end(); it != end; ++it) { + for (base::ProgramOptions::OptionList::const_iterator it = po.options().begin(), + end = po.options().end(); + it != end; + ++it) { const base::ProgramOptions::Option* option = *it; - std::size_t optionWidth = 6+option->name().size()+1+ - (option->doesRequireValue() ? option->getValueName().size()+1: 0); + std::size_t optionWidth = 6 + option->name().size() + 1 + + (option->doesRequireValue() ? option->getValueName().size() + 1 : 0); if (option->mnemonic() != 0) os << std::setw(3) << '-' << option->mnemonic() << ", "; @@ -220,23 +218,19 @@ std::ostream& operator<<(std::ostream& os, const base::ProgramOptions& po) // Show alias if (!option->alias().empty()) { - os << " or\n" - << std::setw(6) << ' ' - << "--" << option->alias(); + os << " or\n" << std::setw(6) << ' ' << "--" << option->alias(); if (option->doesRequireValue()) os << " " << option->getValueName(); - optionWidth = 6+option->alias().size()+1+ - (option->doesRequireValue() ? option->getValueName().size()+1: 0); + optionWidth = 6 + option->alias().size() + 1 + + (option->doesRequireValue() ? option->getValueName().size() + 1 : 0); } if (!option->description().empty()) { - const bool multilines = - (option->description().find('\n') != std::string::npos); + const bool multilines = (option->description().find('\n') != std::string::npos); if (!multilines) { - os << std::setw(maxOptionWidth - optionWidth + 1) << ' ' << option->description() - << "\n"; + os << std::setw(maxOptionWidth - optionWidth + 1) << ' ' << option->description() << "\n"; } else { std::istringstream s(option->description()); @@ -244,7 +238,7 @@ std::ostream& operator<<(std::ostream& os, const base::ProgramOptions& po) if (std::getline(s, line)) { os << std::setw(maxOptionWidth - optionWidth + 1) << ' ' << line << '\n'; while (std::getline(s, line)) { - os << std::setw(maxOptionWidth+2) << ' ' << line << '\n'; + os << std::setw(maxOptionWidth + 2) << ' ' << line << '\n'; } } } diff --git a/base/program_options.h b/base/program_options.h index 4d93b83fe..4f4bea9d6 100644 --- a/base/program_options.h +++ b/base/program_options.h @@ -8,111 +8,119 @@ #define BASE_PROGRAM_OPTIONS_H_INCLUDED #pragma once -#include -#include #include #include +#include +#include namespace base { - class InvalidProgramOption : public std::runtime_error { - public: - InvalidProgramOption(const std::string& msg) - : std::runtime_error(msg) { } - }; +class InvalidProgramOption : public std::runtime_error { +public: + InvalidProgramOption(const std::string& msg) : std::runtime_error(msg) {} +}; - class InvalidProgramOptionsCombination : public std::runtime_error { - public: - InvalidProgramOptionsCombination(const std::string& msg) - : std::runtime_error(msg) { } - }; +class InvalidProgramOptionsCombination : public std::runtime_error { +public: + InvalidProgramOptionsCombination(const std::string& msg) : std::runtime_error(msg) {} +}; + +class ProgramOptionNeedsValue : public std::runtime_error { +public: + ProgramOptionNeedsValue(const std::string& msg) : std::runtime_error(msg) {} +}; - class ProgramOptionNeedsValue : public std::runtime_error { +class ProgramOptions { +public: + class Option { public: - ProgramOptionNeedsValue(const std::string& msg) - : std::runtime_error(msg) { } + Option(const std::string& name) : m_name(name), m_mnemonic(0) {} + // Getters + const std::string& name() const { return m_name; } + const std::string& alias() const { return m_alias; } + const std::string& description() const { return m_description; } + const std::string& getValueName() const { return m_valueName; } + char mnemonic() const { return m_mnemonic; } + bool doesRequireValue() const { return !m_valueName.empty(); } + // Setters + Option& alias(const std::string& alias) + { + m_alias = alias; + return *this; + } + Option& description(const std::string& desc) + { + m_description = desc; + return *this; + } + Option& mnemonic(char mnemonic) + { + m_mnemonic = mnemonic; + return *this; + } + Option& requiresValue(const std::string& valueName) + { + m_valueName = valueName; + return *this; + } + + private: + std::string m_name; // Name of the option (e.g. "help" for "--help") + std::string m_alias; + std::string m_description; // Description of the option (this can be used when the help is + // printed). + std::string m_valueName; // Empty if this option doesn't require a value, or the name of the + // expected value. + char m_mnemonic; // One character that can be used in the command line to use this option. + + friend class ProgramOptions; }; - class ProgramOptions { + class Value { public: - class Option { - public: - Option(const std::string& name) - : m_name(name) - , m_mnemonic(0) { - } - // Getters - const std::string& name() const { return m_name; } - const std::string& alias() const { return m_alias; } - const std::string& description() const { return m_description; } - const std::string& getValueName() const { return m_valueName; } - char mnemonic() const { return m_mnemonic; } - bool doesRequireValue() const { return !m_valueName.empty(); } - // Setters - Option& alias(const std::string& alias) { m_alias = alias; return *this; } - Option& description(const std::string& desc) { m_description = desc; return *this; } - Option& mnemonic(char mnemonic) { m_mnemonic = mnemonic; return *this; } - Option& requiresValue(const std::string& valueName) { - m_valueName = valueName; - return *this; - } - private: - std::string m_name; // Name of the option (e.g. "help" for "--help") - std::string m_alias; - std::string m_description; // Description of the option (this can be used when the help is printed). - std::string m_valueName; // Empty if this option doesn't require a value, or the name of the expected value. - char m_mnemonic; // One character that can be used in the command line to use this option. - - friend class ProgramOptions; - }; - - class Value { - public: - Value(Option* option, const std::string& value) - : m_option(option) - , m_value(value) { - } - const Option* option() const { return m_option; } - const std::string& value() const { return m_value; } - private: - Option* m_option; - std::string m_value; - }; - - typedef std::vector OptionList; - typedef std::vector ValueList; - - ProgramOptions(); - - // After destructing the ProgramOptions, you cannot continue using - // references to "Option" instances obtained through add() function. - ~ProgramOptions(); - - // Adds a option for the program. The options must be specified - // before calling parse(). The returned reference must be used in - // the ProgramOptions lifetime. - Option& add(const std::string& name); - - // Detects which options where specified in the command line. - void parse(int argc, const char* argv[]); - - // Reset all option values/flags. - void reset(); - - // Returns the list of available options for the user. - const OptionList& options() const { return m_options; } - - // List of specified options/values in the command line. - const ValueList& values() const { return m_values; } - - bool enabled(const Option& option) const; - std::string value_of(const Option& option) const; + Value(Option* option, const std::string& value) : m_option(option), m_value(value) {} + const Option* option() const { return m_option; } + const std::string& value() const { return m_value; } private: - OptionList m_options; - ValueList m_values; + Option* m_option; + std::string m_value; }; + typedef std::vector OptionList; + typedef std::vector ValueList; + + ProgramOptions(); + + // After destructing the ProgramOptions, you cannot continue using + // references to "Option" instances obtained through add() function. + ~ProgramOptions(); + + // Adds a option for the program. The options must be specified + // before calling parse(). The returned reference must be used in + // the ProgramOptions lifetime. + Option& add(const std::string& name); + + // Detects which options where specified in the command line. + void parse(int argc, const char* argv[]); + + // Reset all option values/flags. + void reset(); + + // Returns the list of available options for the user. + const OptionList& options() const { return m_options; } + + // List of specified options/values in the command line. + const ValueList& values() const { return m_values; } + + bool enabled(const Option& option) const; + std::string value_of(const Option& option) const; + +private: + OptionList m_options; + ValueList m_values; +}; + } // namespace base // Prints the program options correctly formatted to be read by diff --git a/base/program_options_tests.cpp b/base/program_options_tests.cpp index 089b1349a..806f0473b 100644 --- a/base/program_options_tests.cpp +++ b/base/program_options_tests.cpp @@ -13,10 +13,8 @@ using namespace base; TEST(ProgramOptions, OptionMembers) { ProgramOptions po; - ProgramOptions::Option& help = - po.add("help").mnemonic('h').description("Show the help"); - ProgramOptions::Option& output = - po.add("output").mnemonic('O').requiresValue("OUTPUT"); + ProgramOptions::Option& help = po.add("help").mnemonic('h').description("Show the help"); + ProgramOptions::Option& output = po.add("output").mnemonic('O').requiresValue("OUTPUT"); EXPECT_EQ("help", help.name()); EXPECT_EQ("Show the help", help.description()); @@ -104,7 +102,8 @@ TEST(ProgramOptions, Parse) EXPECT_EQ("output.html", po.values()[2].value()); EXPECT_EQ("extra-file.txt", po.values()[3].value()); - const char* argv6[] = { "program.exe", "value1", "value2", "-o", "output", "value3", "--input=input", "value4" }; + const char* argv6[] = { "program.exe", "value1", "value2", "-o", + "output", "value3", "--input=input", "value4" }; po.reset(); po.parse(8, argv6); ASSERT_EQ(6, po.values().size()); @@ -136,7 +135,7 @@ TEST(ProgramOptions, ParseErrors) po.reset(); EXPECT_FALSE(po.enabled(help)); EXPECT_THROW(po.parse(2, argv4), InvalidProgramOption); - EXPECT_TRUE(po.enabled(help)); // -? is parsed anyway, -a is the invalid option + EXPECT_TRUE(po.enabled(help)); // -? is parsed anyway, -a is the invalid option const char* argv5[] = { "program.exe", "-io", "input-and-output.txt" }; po.reset(); diff --git a/base/ref.h b/base/ref.h index 8bcfdad52..49e280590 100644 --- a/base/ref.h +++ b/base/ref.h @@ -15,181 +15,207 @@ namespace base { - template - class RefCountT { - public: - RefCountT() : m_ref(1) { } - - ~RefCountT() { - // m_ref can be 1 in case that RefCountT() was created in the - // stack, and 0 when it's deleted from unref(). - ASSERT(m_ref == 0 || m_ref == 1); - } +template +class RefCountT { +public: + RefCountT() : m_ref(1) {} + + ~RefCountT() + { + // m_ref can be 1 in case that RefCountT() was created in the + // stack, and 0 when it's deleted from unref(). + ASSERT(m_ref == 0 || m_ref == 1); + } - RefCountT(const RefCountT&) : m_ref(1) { } - RefCountT& operator=(const RefCountT&) { return *this; } + RefCountT(const RefCountT&) : m_ref(1) {} + RefCountT& operator=(const RefCountT&) { return *this; } - void ref() { - ASSERT(m_ref > 0); - m_ref.fetch_add(1, std::memory_order_relaxed); - } + void ref() + { + ASSERT(m_ref > 0); + m_ref.fetch_add(1, std::memory_order_relaxed); + } - void unref() { - ASSERT(m_ref > 0); - if (m_ref.fetch_sub(1, std::memory_order_acq_rel) == 1) - delete (T*)this; - } + void unref() + { + ASSERT(m_ref > 0); + if (m_ref.fetch_sub(1, std::memory_order_acq_rel) == 1) + delete (T*)this; + } -#ifdef _DEBUG // For debugging purposes only (TRACE, TRACEARGS, etc.) - uint32_t ref_count() const { return m_ref; } +#ifdef _DEBUG // For debugging purposes only (TRACE, TRACEARGS, etc.) + uint32_t ref_count() const { return m_ref; } #endif - private: - std::atomic m_ref; - }; - - class RefCount : public RefCountT { - public: - RefCount() { } - virtual ~RefCount() { } - - // Copy and move disabled for classes with virtual destruction - RefCount(const RefCount&) = delete; - RefCount(RefCount&&) = delete; - RefCount& operator=(const RefCount&) = delete; - RefCount& operator=(RefCount&&) = delete; - }; - - // Smart pointer for RefCountT objects - template - class Ref { - public: - Ref() noexcept : m_ptr(nullptr) { } - Ref(std::nullptr_t) noexcept : m_ptr(nullptr) { } - - explicit Ref(T* ptr) noexcept : m_ptr(ptr) { } - template - explicit Ref(U* ptr) noexcept : m_ptr(static_cast(ptr)) { } - - Ref(Ref&& ref) noexcept : m_ptr(ref.release()) { } - template - Ref(Ref&& ref) noexcept : m_ptr(static_cast(ref.release())) { } - - Ref(const Ref& ref) : m_ptr(ref.m_ptr) { - if (m_ptr) m_ptr->ref(); - } - template - Ref(const Ref& ref) : m_ptr(static_cast(ref.m_ptr)) { - if (m_ptr) m_ptr->ref(); - } - - ~Ref() { if (m_ptr) m_ptr->unref(); } - - void reset(T* ptr = nullptr) { - if (m_ptr) m_ptr->unref(); - m_ptr = ptr; - if (m_ptr) m_ptr->ref(); - } - - T* release() { - T* ptr = m_ptr; - m_ptr = nullptr; - return ptr; - } - - T* get() const { return m_ptr; } - T* operator->() const { return m_ptr; } - T& operator*() const { return *m_ptr; } - - // Do not define operator=(T*) because stealing references from - // raw pointers is like an implicit copy ctor from a raw pointer. - // Use AddRef() for these cases, e.g.: - // - // void function(T* refCountedObj) { - // Ref p; - // p = AddRef(refCountedObj); - // ... - // } - Ref& operator=(T* ptr) = delete; - - Ref& operator=(std::nullptr_t) { - reset(); - return *this; - } - - Ref& operator=(Ref&& ref) noexcept { - if (m_ptr) m_ptr->unref(); - m_ptr = ref.release(); - return *this; - } - - Ref& operator=(const Ref& ref) { - if (this == &ref) - return *this; - if (m_ptr) { - if (m_ptr == ref.m_ptr) - return *this; - m_ptr->unref(); - } - m_ptr = ref.m_ptr; - if (m_ptr) m_ptr->ref(); - return *this; - } - - // Comparison between other Ref, raw pointers and nullpointers - bool operator==(const Ref& r) const { return m_ptr == r.m_ptr; } - bool operator!=(const Ref& r) const { return m_ptr != r.m_ptr; } - bool operator==(const T* p) const { return m_ptr == p; } - bool operator!=(const T* p) const { return m_ptr != p; } - bool operator==(std::nullptr_t) const { return m_ptr == nullptr; } - bool operator!=(std::nullptr_t) const { return m_ptr != nullptr; } - - explicit operator bool() const { - return m_ptr != nullptr; - } +private: + std::atomic m_ref; +}; + +class RefCount : public RefCountT { +public: + RefCount() {} + virtual ~RefCount() {} + + // Copy and move disabled for classes with virtual destruction + RefCount(const RefCount&) = delete; + RefCount(RefCount&&) = delete; + RefCount& operator=(const RefCount&) = delete; + RefCount& operator=(RefCount&&) = delete; +}; + +// Smart pointer for RefCountT objects +template +class Ref { +public: + Ref() noexcept : m_ptr(nullptr) {} + Ref(std::nullptr_t) noexcept : m_ptr(nullptr) {} + + explicit Ref(T* ptr) noexcept : m_ptr(ptr) {} + template + explicit Ref(U* ptr) noexcept : m_ptr(static_cast(ptr)) + { + } - void swap(Ref& r) noexcept { - std::swap(m_ptr, r.m_ptr); - } + Ref(Ref&& ref) noexcept : m_ptr(ref.release()) {} + template + Ref(Ref&& ref) noexcept : m_ptr(static_cast(ref.release())) + { + } - private: - T* m_ptr; - }; + Ref(const Ref& ref) : m_ptr(ref.m_ptr) + { + if (m_ptr) + m_ptr->ref(); + } + template + Ref(const Ref& ref) : m_ptr(static_cast(ref.m_ptr)) + { + if (m_ptr) + m_ptr->ref(); + } - template - inline bool operator==(T* ptr, const Ref& r) { - return r.get() == ptr; + ~Ref() + { + if (m_ptr) + m_ptr->unref(); } - template - inline bool operator!=(T* ptr, const Ref& r) { - return r.get() != ptr; + void reset(T* ptr = nullptr) + { + if (m_ptr) + m_ptr->unref(); + m_ptr = ptr; + if (m_ptr) + m_ptr->ref(); } - template - inline bool operator==(std::nullptr_t, const Ref& r) { - return r.get() == nullptr; + T* release() + { + T* ptr = m_ptr; + m_ptr = nullptr; + return ptr; } - template - inline bool operator!=(std::nullptr_t, const Ref& r) { - return r.get() != nullptr; + T* get() const { return m_ptr; } + T* operator->() const { return m_ptr; } + T& operator*() const { return *m_ptr; } + + // Do not define operator=(T*) because stealing references from + // raw pointers is like an implicit copy ctor from a raw pointer. + // Use AddRef() for these cases, e.g.: + // + // void function(T* refCountedObj) { + // Ref p; + // p = AddRef(refCountedObj); + // ... + // } + Ref& operator=(T* ptr) = delete; + + Ref& operator=(std::nullptr_t) + { + reset(); + return *this; } - template - Ref make_ref(Args&&...args) { - return Ref(new T(std::forward(args)...)); + Ref& operator=(Ref&& ref) noexcept + { + if (m_ptr) + m_ptr->unref(); + m_ptr = ref.release(); + return *this; } - // AddRef() is like Ref() ctor but adding a new ref (useful to - // create a new ref from a raw pointer). - template - inline Ref AddRef(T* r) { - if (r) r->ref(); - return Ref(r); + Ref& operator=(const Ref& ref) + { + if (this == &ref) + return *this; + if (m_ptr) { + if (m_ptr == ref.m_ptr) + return *this; + m_ptr->unref(); + } + m_ptr = ref.m_ptr; + if (m_ptr) + m_ptr->ref(); + return *this; } + // Comparison between other Ref, raw pointers and nullpointers + bool operator==(const Ref& r) const { return m_ptr == r.m_ptr; } + bool operator!=(const Ref& r) const { return m_ptr != r.m_ptr; } + bool operator==(const T* p) const { return m_ptr == p; } + bool operator!=(const T* p) const { return m_ptr != p; } + bool operator==(std::nullptr_t) const { return m_ptr == nullptr; } + bool operator!=(std::nullptr_t) const { return m_ptr != nullptr; } + + explicit operator bool() const { return m_ptr != nullptr; } + + void swap(Ref& r) noexcept { std::swap(m_ptr, r.m_ptr); } + +private: + T* m_ptr; +}; + +template +inline bool operator==(T* ptr, const Ref& r) +{ + return r.get() == ptr; +} + +template +inline bool operator!=(T* ptr, const Ref& r) +{ + return r.get() != ptr; +} + +template +inline bool operator==(std::nullptr_t, const Ref& r) +{ + return r.get() == nullptr; +} + +template +inline bool operator!=(std::nullptr_t, const Ref& r) +{ + return r.get() != nullptr; +} + +template +Ref make_ref(Args&&... args) +{ + return Ref(new T(std::forward(args)...)); +} + +// AddRef() is like Ref() ctor but adding a new ref (useful to +// create a new ref from a raw pointer). +template +inline Ref AddRef(T* r) +{ + if (r) + r->ref(); + return Ref(r); +} + } // namespace base #endif diff --git a/base/ref_tests.cpp b/base/ref_tests.cpp index 8bb1b1158..9089da642 100644 --- a/base/ref_tests.cpp +++ b/base/ref_tests.cpp @@ -88,7 +88,7 @@ class AVirt : public RefCount { class BVirt : public AVirt { public: - BVirt(int v) : AVirt(v) { } + BVirt(int v) : AVirt(v) {} ~BVirt() { ++b_dtors; } }; diff --git a/base/remove_from_container.h b/base/remove_from_container.h index 03533f1d0..793bb75a3 100644 --- a/base/remove_from_container.h +++ b/base/remove_from_container.h @@ -15,9 +15,7 @@ template void remove_from_container(ContainerType& container, typename ContainerType::const_reference element) { - for (typename ContainerType::iterator - it = container.begin(), - end = container.end(); it != end; ) { + for (typename ContainerType::iterator it = container.begin(), end = container.end(); it != end;) { if (*it == element) { it = container.erase(it); end = container.end(); @@ -27,6 +25,6 @@ void remove_from_container(ContainerType& container, } } -} +} // namespace base #endif diff --git a/base/replace_string.cpp b/base/replace_string.cpp index 0369a8a45..e9a5c51c3 100644 --- a/base/replace_string.cpp +++ b/base/replace_string.cpp @@ -5,19 +5,18 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/replace_string.h" namespace base { -void replace_string( - std::string& subject, - const std::string& replace_this, - const std::string& with_that) +void replace_string(std::string& subject, + const std::string& replace_this, + const std::string& with_that) { - if (replace_this.empty()) // Do nothing case + if (replace_this.empty()) // Do nothing case return; std::size_t i = 0; diff --git a/base/replace_string.h b/base/replace_string.h index bc5c93087..e1dc1b400 100644 --- a/base/replace_string.h +++ b/base/replace_string.h @@ -12,10 +12,9 @@ namespace base { - void replace_string( - std::string& subject, - const std::string& replace_this, - const std::string& with_that); +void replace_string(std::string& subject, + const std::string& replace_this, + const std::string& with_that); } diff --git a/base/replace_string_tests.cpp b/base/replace_string_tests.cpp index 549e7c61b..7ee494f8d 100644 --- a/base/replace_string_tests.cpp +++ b/base/replace_string_tests.cpp @@ -8,7 +8,8 @@ #include "base/replace_string.h" -inline std::string rs(const std::string& s, const std::string& a, const std::string& b) { +inline std::string rs(const std::string& s, const std::string& a, const std::string& b) +{ std::string res = s; base::replace_string(res, a, b); return res; diff --git a/base/rw_lock.cpp b/base/rw_lock.cpp index c49b0ca79..437283cae 100644 --- a/base/rw_lock.cpp +++ b/base/rw_lock.cpp @@ -6,14 +6,14 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/rw_lock.h" // Uncomment this line in case that you want TRACE() lock/unlock // operations. -//#define DEBUG_OBJECT_LOCKS +// #define DEBUG_OBJECT_LOCKS #include "base/debug.h" #include "base/thread.h" @@ -40,8 +40,7 @@ bool RWLock::canWriteLockFromRead() const // If this thread already have a writer lock, we can upgrade any // reader lock to writer in the same thread (re-entrant locks). - if (m_write_lock && - m_write_thread == std::this_thread::get_id()) { + if (m_write_lock && m_write_thread == std::this_thread::get_id()) { return true; } // If only we are reading (one lock) and nobody is writing, we can @@ -56,8 +55,7 @@ RWLock::LockResult RWLock::lock(LockType lockType, int timeout) // if (lockType == WriteLock) { { const std::lock_guard lock(m_mutex); - if (m_write_lock && - m_write_thread == std::this_thread::get_id()) { + if (m_write_lock && m_write_thread == std::this_thread::get_id()) { return LockResult::Reentrant; } } @@ -67,7 +65,6 @@ RWLock::LockResult RWLock::lock(LockType lockType, int timeout) const std::lock_guard lock(m_mutex); switch (lockType) { - case ReadLock: // If no body is writing the object... if (!m_write_lock) { @@ -101,7 +98,6 @@ RWLock::LockResult RWLock::lock(LockType lockType, int timeout) return LockResult::OK; } break; - } go_wait:; @@ -123,7 +119,10 @@ RWLock::LockResult RWLock::lock(LockType lockType, int timeout) #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: Cannot lock <%p> to %s (has %d read locks and %d write locks)\n", - this, (lockType == ReadLock ? "read": "write"), m_read_locks, m_write_lock); + this, + (lockType == ReadLock ? "read" : "write"), + m_read_locks, + m_write_lock); #endif return LockResult::Fail; @@ -167,8 +166,7 @@ bool RWLock::weakLock(std::atomic* weak_lock_flag) { const std::lock_guard lock(m_mutex); - if (m_weak_lock || - m_write_lock) + if (m_weak_lock || m_write_lock) return false; m_weak_lock = weak_lock_flag; @@ -196,8 +194,7 @@ RWLock::LockResult RWLock::upgradeToWrite(int timeout) // same thread are allowed). { const std::lock_guard lock(m_mutex); - if (m_write_lock && - m_write_thread == std::this_thread::get_id()) { + if (m_write_lock && m_write_thread == std::this_thread::get_id()) { return LockResult::Reentrant; } } @@ -251,7 +248,9 @@ RWLock::LockResult RWLock::upgradeToWrite(int timeout) #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: Cannot lock <%p> to write (has %d read locks and %d write locks)\n", - this, m_read_locks, m_write_lock); + this, + m_read_locks, + m_write_lock); #endif return LockResult::Fail; diff --git a/base/rw_lock.h b/base/rw_lock.h index 2d4fb8958..95bf80d6e 100644 --- a/base/rw_lock.h +++ b/base/rw_lock.h @@ -17,84 +17,81 @@ namespace base { - // A readers-writer lock implementation - class RWLock { - public: - enum LockType { - ReadLock, - WriteLock - }; - - enum WeakLock { - WeakUnlocked, - WeakUnlocking, - WeakLocked, - }; - - // Result of a lock operation. This result must be used in the - // unlock function to know if we should really unlock it - // (e.g. only the first write-lock in the same thread will - // write-unlock it). - enum class LockResult { - Fail, // Cannot lock now - Reentrant, // Already locked in thread (we can continue) - OK, // Locked right now in this thread - }; - - RWLock(); - ~RWLock(); - - // Returns true if we can lock this object for writing purposes in - // case that the current thread has it locked for reading. - bool canWriteLockFromRead() const; - - // Locks the object to read or write on it, returning OK if the - // object can be accessed in the desired mode, ReentrantLock if - // the mode is compatible with the thread that locked this object, - // or Failed if the mode is incompatible. - LockResult lock(LockType lockType, int timeout); - - // If you've locked the object to read, using this method you can - // raise your access level to write it. - LockResult upgradeToWrite(int timeout); - - // If we've locked the object to write, using this method we can - // lower our access to read-only. - void downgradeToRead(LockResult lockResult); - - // Unlocks a previously successfully lock() operation. - void unlock(LockResult lockResult); - - // Tries to lock the object for read access in a "weak way" so - // other thread (e.g. UI thread) can lock the object removing this - // weak lock. - // - // The "weak_lock_flag" is used to notify when the "weak lock" is - // lost. - bool weakLock(std::atomic* weak_lock_flag); - void weakUnlock(); - - private: - // Mutex to modify the 'locked' flag. - mutable std::mutex m_mutex; - - // True if some thread is writing the object. - bool m_write_lock = false; - std::thread::id m_write_thread = {}; - - // Greater than zero when one or more threads are reading the object. - int m_read_locks = 0; - - // If this isn' nullptr, it means that it points to an unique - // "weak" lock that can be unlocked from other thread. E.g. the - // backup/data recovery thread might weakly lock the object so if - // the user UI thread needs the object again, the backup process - // can stop. - std::atomic* m_weak_lock = nullptr; - - DISABLE_COPYING(RWLock); +// A readers-writer lock implementation +class RWLock { +public: + enum LockType { ReadLock, WriteLock }; + + enum WeakLock { + WeakUnlocked, + WeakUnlocking, + WeakLocked, }; + // Result of a lock operation. This result must be used in the + // unlock function to know if we should really unlock it + // (e.g. only the first write-lock in the same thread will + // write-unlock it). + enum class LockResult { + Fail, // Cannot lock now + Reentrant, // Already locked in thread (we can continue) + OK, // Locked right now in this thread + }; + + RWLock(); + ~RWLock(); + + // Returns true if we can lock this object for writing purposes in + // case that the current thread has it locked for reading. + bool canWriteLockFromRead() const; + + // Locks the object to read or write on it, returning OK if the + // object can be accessed in the desired mode, ReentrantLock if + // the mode is compatible with the thread that locked this object, + // or Failed if the mode is incompatible. + LockResult lock(LockType lockType, int timeout); + + // If you've locked the object to read, using this method you can + // raise your access level to write it. + LockResult upgradeToWrite(int timeout); + + // If we've locked the object to write, using this method we can + // lower our access to read-only. + void downgradeToRead(LockResult lockResult); + + // Unlocks a previously successfully lock() operation. + void unlock(LockResult lockResult); + + // Tries to lock the object for read access in a "weak way" so + // other thread (e.g. UI thread) can lock the object removing this + // weak lock. + // + // The "weak_lock_flag" is used to notify when the "weak lock" is + // lost. + bool weakLock(std::atomic* weak_lock_flag); + void weakUnlock(); + +private: + // Mutex to modify the 'locked' flag. + mutable std::mutex m_mutex; + + // True if some thread is writing the object. + bool m_write_lock = false; + std::thread::id m_write_thread = {}; + + // Greater than zero when one or more threads are reading the object. + int m_read_locks = 0; + + // If this isn' nullptr, it means that it points to an unique + // "weak" lock that can be unlocked from other thread. E.g. the + // backup/data recovery thread might weakly lock the object so if + // the user UI thread needs the object again, the backup process + // can stop. + std::atomic* m_weak_lock = nullptr; + + DISABLE_COPYING(RWLock); +}; + } // namespace base #endif diff --git a/base/rw_lock_tests.cpp b/base/rw_lock_tests.cpp index 64b2f9ce1..cdd88871d 100644 --- a/base/rw_lock_tests.cpp +++ b/base/rw_lock_tests.cpp @@ -18,7 +18,7 @@ using LockResult = RWLock::LockResult; #define EXPECT_REENTRANT(a) EXPECT_EQ(LockResult::Reentrant, a) #define EXPECT_OK(a) EXPECT_EQ(LockResult::OK, a) -#define BGTHREAD(code) std::thread([&a]{ code; }).join(); +#define BGTHREAD(code) std::thread([&a] { code; }).join(); TEST(RWLock, MultipleReaders) { @@ -90,7 +90,7 @@ TEST(RWLock, WeakLock) // We can lock for read-only without timeout and the weak lock // should stay locked. EXPECT_OK(res[0] = a.lock(RWLock::ReadLock, 0)); - a.unlock(res[0]); // Unlock the read-only lock + a.unlock(res[0]); // Unlock the read-only lock EXPECT_EQ(RWLock::WeakLocked, flag); // If we want to lock for writing purposes, it should fail, but the @@ -102,7 +102,7 @@ TEST(RWLock, WeakLock) EXPECT_OK(res[0] = a.lock(RWLock::WriteLock, 0)); EXPECT_FALSE(a.weakLock(&flag)); - a.unlock(res[0]); // Unlock the write lock + a.unlock(res[0]); // Unlock the write lock } int main(int argc, char** argv) diff --git a/base/scoped_value.h b/base/scoped_value.h index ebe4d2a81..26f870b77 100644 --- a/base/scoped_value.h +++ b/base/scoped_value.h @@ -11,34 +11,33 @@ namespace base { - // Changes the value of "instance" with "inValue" in the - // ScopedValue's lifespan, then restore its value (or restore - // another value as specified by "outValue"). - template - class ScopedValue { - public: - ScopedValue(T& instance, const U inValue) - : m_instance(instance) - // Restore the current value - , m_outValue(instance) { - m_instance = inValue; - } - - ScopedValue(T& instance, const U inValue, const U outValue) - : m_instance(instance) - , m_outValue(outValue) { - m_instance = inValue; - } - - ~ScopedValue() { - m_instance = m_outValue; - } - - private: - T& m_instance; - U m_outValue; - }; +// Changes the value of "instance" with "inValue" in the +// ScopedValue's lifespan, then restore its value (or restore +// another value as specified by "outValue"). +template +class ScopedValue { +public: + ScopedValue(T& instance, const U inValue) + : m_instance(instance) + // Restore the current value + , m_outValue(instance) + { + m_instance = inValue; + } + + ScopedValue(T& instance, const U inValue, const U outValue) + : m_instance(instance) + , m_outValue(outValue) + { + m_instance = inValue; + } + + ~ScopedValue() { m_instance = m_outValue; } + +private: + T& m_instance; + U m_outValue; +}; } // namespace base diff --git a/base/serialization.cpp b/base/serialization.cpp index ebb88d0e9..0d234a929 100644 --- a/base/serialization.cpp +++ b/base/serialization.cpp @@ -5,15 +5,14 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/serialization.h" #include -namespace base { -namespace serialization { +namespace base { namespace serialization { std::ostream& write8(std::ostream& os, uint8_t byte) { @@ -108,14 +107,9 @@ uint64_t little_endian::read64(std::istream& is) b6 = is.get(); b7 = is.get(); b8 = is.get(); - return (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + return (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); } float little_endian::read_float(std::istream& is) @@ -140,14 +134,9 @@ double little_endian::read_double(std::istream& is) b6 = is.get(); b7 = is.get(); b8 = is.get(); - int v = (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + int v = (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); return *reinterpret_cast(&v); } @@ -233,14 +222,9 @@ uint64_t big_endian::read64(std::istream& is) b3 = is.get(); b2 = is.get(); b1 = is.get(); - return (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + return (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); } float big_endian::read_float(std::istream& is) @@ -265,17 +249,10 @@ double big_endian::read_double(std::istream& is) b3 = is.get(); b2 = is.get(); b1 = is.get(); - int v = (((long long)b8 << 56) | - ((long long)b7 << 48) | - ((long long)b6 << 40) | - ((long long)b5 << 32) | - ((long long)b4 << 24) | - ((long long)b3 << 16) | - ((long long)b2 << 8) | - (long long)b1); + int v = (((long long)b8 << 56) | ((long long)b7 << 48) | ((long long)b6 << 40) | + ((long long)b5 << 32) | ((long long)b4 << 24) | ((long long)b3 << 16) | + ((long long)b2 << 8) | (long long)b1); return *reinterpret_cast(&v); } - -} // namespace serialization -} // namespace base +}} // namespace base::serialization diff --git a/base/serialization.h b/base/serialization.h index 1b4adf8c5..a8c42a1de 100644 --- a/base/serialization.h +++ b/base/serialization.h @@ -11,43 +11,41 @@ #include "base/ints.h" #include -namespace base { -namespace serialization { - - std::ostream& write8(std::ostream& os, uint8_t byte); - uint8_t read8(std::istream& is); - - namespace little_endian { - - std::ostream& write16(std::ostream& os, uint16_t word); - std::ostream& write32(std::ostream& os, uint32_t dword); - std::ostream& write64(std::ostream& os, uint64_t qword); - std::ostream& write_float(std::ostream& os, float value); - std::ostream& write_double(std::ostream& os, double value); - uint16_t read16(std::istream& is); - uint32_t read32(std::istream& is); - uint64_t read64(std::istream& is); - float read_float(std::istream& is); - double read_double(std::istream& is); - - } // little_endian namespace - - namespace big_endian { - - std::ostream& write16(std::ostream& os, uint16_t word); - std::ostream& write32(std::ostream& os, uint32_t dword); - std::ostream& write64(std::ostream& os, uint64_t qword); - std::ostream& write_float(std::ostream& os, float value); - std::ostream& write_double(std::ostream& os, double value); - uint16_t read16(std::istream& is); - uint32_t read32(std::istream& is); - uint64_t read64(std::istream& is); - float read_float(std::istream& is); - double read_double(std::istream& is); - - } // big_endian namespace - -} // serialization namespace -} // base namespace +namespace base { namespace serialization { + +std::ostream& write8(std::ostream& os, uint8_t byte); +uint8_t read8(std::istream& is); + +namespace little_endian { + +std::ostream& write16(std::ostream& os, uint16_t word); +std::ostream& write32(std::ostream& os, uint32_t dword); +std::ostream& write64(std::ostream& os, uint64_t qword); +std::ostream& write_float(std::ostream& os, float value); +std::ostream& write_double(std::ostream& os, double value); +uint16_t read16(std::istream& is); +uint32_t read32(std::istream& is); +uint64_t read64(std::istream& is); +float read_float(std::istream& is); +double read_double(std::istream& is); + +} // namespace little_endian + +namespace big_endian { + +std::ostream& write16(std::ostream& os, uint16_t word); +std::ostream& write32(std::ostream& os, uint32_t dword); +std::ostream& write64(std::ostream& os, uint64_t qword); +std::ostream& write_float(std::ostream& os, float value); +std::ostream& write_double(std::ostream& os, double value); +uint16_t read16(std::istream& is); +uint32_t read32(std::istream& is); +uint64_t read64(std::istream& is); +float read_float(std::istream& is); +double read_double(std::istream& is); + +} // namespace big_endian + +}} // namespace base::serialization #endif diff --git a/base/sha1.cpp b/base/sha1.cpp index 06dc65d1a..c82b1e5bb 100644 --- a/base/sha1.cpp +++ b/base/sha1.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/debug.h" @@ -17,13 +17,11 @@ namespace base { -Sha1::Sha1() - : m_digest(20, 0) +Sha1::Sha1() : m_digest(20, 0) { } -Sha1::Sha1(const std::vector& digest) - : m_digest(digest) +Sha1::Sha1(const std::vector& digest) : m_digest(digest) { ASSERT(digest.size() == HashSize); } diff --git a/base/sha1.h b/base/sha1.h index 09928bffa..f8c28c6b3 100644 --- a/base/sha1.h +++ b/base/sha1.h @@ -8,8 +8,8 @@ #define BASE_SHA1_H_INCLUDED #pragma once -#include #include +#include #include "base/ints.h" @@ -17,36 +17,30 @@ extern "C" struct SHA1Context; namespace base { - class Sha1 { - public: - enum { HashSize = 20 }; +class Sha1 { +public: + enum { HashSize = 20 }; - Sha1(); - explicit Sha1(const std::vector& digest); + Sha1(); + explicit Sha1(const std::vector& digest); - // Calculates the SHA1 of the given file or string. - static Sha1 calculateFromFile(const std::string& fileName); - static Sha1 calculateFromString(const std::string& text); + // Calculates the SHA1 of the given file or string. + static Sha1 calculateFromFile(const std::string& fileName); + static Sha1 calculateFromString(const std::string& text); - bool operator==(const Sha1& other) const; - bool operator!=(const Sha1& other) const; + bool operator==(const Sha1& other) const; + bool operator!=(const Sha1& other) const; - uint8_t operator[](int index) const { - return m_digest[index]; - } + uint8_t operator[](int index) const { return m_digest[index]; } - const uint8_t *digest() const { - return m_digest.data(); - } + const uint8_t* digest() const { return m_digest.data(); } - size_t size() const { - return m_digest.size(); - } + size_t size() const { return m_digest.size(); } - private: - std::vector m_digest; - }; +private: + std::vector m_digest; +}; } // namespace base -#endif // BASE_SHA1_H_INCLUDED +#endif // BASE_SHA1_H_INCLUDED diff --git a/base/sha1_rfc3174.c b/base/sha1_rfc3174.c index f529d8863..6b9115e42 100644 --- a/base/sha1_rfc3174.c +++ b/base/sha1_rfc3174.c @@ -30,7 +30,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/ints.h" #include "base/sha1_rfc3174.h" @@ -38,12 +38,11 @@ /* * Define the SHA1 circular left shift macro */ -#define SHA1CircularShift(bits,word) \ - (((word) << (bits)) | ((word) >> (32-(bits)))) +#define SHA1CircularShift(bits, word) (((word) << (bits)) | ((word) >> (32 - (bits)))) /* Local Function Prototyptes */ -void SHA1PadMessage(SHA1Context *); -void SHA1ProcessMessageBlock(SHA1Context *); +void SHA1PadMessage(SHA1Context*); +void SHA1ProcessMessageBlock(SHA1Context*); /* * SHA1Reset @@ -60,27 +59,26 @@ void SHA1ProcessMessageBlock(SHA1Context *); * sha Error Code. * */ -int SHA1Reset(SHA1Context *context) +int SHA1Reset(SHA1Context* context) { - if (!context) - { - return shaNull; - } + if (!context) { + return shaNull; + } - context->Length_Low = 0; - context->Length_High = 0; - context->Message_Block_Index = 0; + context->Length_Low = 0; + context->Length_High = 0; + context->Message_Block_Index = 0; - context->Intermediate_Hash[0] = 0x67452301; - context->Intermediate_Hash[1] = 0xEFCDAB89; - context->Intermediate_Hash[2] = 0x98BADCFE; - context->Intermediate_Hash[3] = 0x10325476; - context->Intermediate_Hash[4] = 0xC3D2E1F0; + context->Intermediate_Hash[0] = 0x67452301; + context->Intermediate_Hash[1] = 0xEFCDAB89; + context->Intermediate_Hash[2] = 0x98BADCFE; + context->Intermediate_Hash[3] = 0x10325476; + context->Intermediate_Hash[4] = 0xC3D2E1F0; - context->Computed = 0; - context->Corrupted = 0; + context->Computed = 0; + context->Corrupted = 0; - return shaSuccess; + return shaSuccess; } /* @@ -102,42 +100,34 @@ int SHA1Reset(SHA1Context *context) * sha Error Code. * */ -int SHA1Result( SHA1Context *context, - uint8_t Message_Digest[SHA1HashSize]) +int SHA1Result(SHA1Context* context, uint8_t Message_Digest[SHA1HashSize]) { - int i; - - if (!context || !Message_Digest) - { - return shaNull; - } + int i; - if (context->Corrupted) - { - return context->Corrupted; - } + if (!context || !Message_Digest) { + return shaNull; + } - if (!context->Computed) - { - SHA1PadMessage(context); - for(i=0; i<64; ++i) - { - /* message may be sensitive, clear it out */ - context->Message_Block[i] = 0; - } - context->Length_Low = 0; /* and clear length */ - context->Length_High = 0; - context->Computed = 1; + if (context->Corrupted) { + return context->Corrupted; + } + if (!context->Computed) { + SHA1PadMessage(context); + for (i = 0; i < 64; ++i) { + /* message may be sensitive, clear it out */ + context->Message_Block[i] = 0; } + context->Length_Low = 0; /* and clear length */ + context->Length_High = 0; + context->Computed = 1; + } - for(i = 0; i < SHA1HashSize; ++i) - { - Message_Digest[i] = context->Intermediate_Hash[i>>2] - >> 8 * ( 3 - ( i & 0x03 ) ); - } + for (i = 0; i < SHA1HashSize; ++i) { + Message_Digest[i] = context->Intermediate_Hash[i >> 2] >> 8 * (3 - (i & 0x03)); + } - return shaSuccess; + return shaSuccess; } /* @@ -160,56 +150,45 @@ int SHA1Result( SHA1Context *context, * sha Error Code. * */ -int SHA1Input( SHA1Context *context, - const uint8_t *message_array, - unsigned int length) +int SHA1Input(SHA1Context* context, const uint8_t* message_array, unsigned int length) { - if (!length) - { - return shaSuccess; - } + if (!length) { + return shaSuccess; + } - if (!context || !message_array) - { - return shaNull; - } + if (!context || !message_array) { + return shaNull; + } - if (context->Computed) - { - context->Corrupted = shaStateError; + if (context->Computed) { + context->Corrupted = shaStateError; - return shaStateError; - } + return shaStateError; + } - if (context->Corrupted) - { - return context->Corrupted; - } - while(length-- && !context->Corrupted) - { - context->Message_Block[context->Message_Block_Index++] = - (*message_array & 0xFF); + if (context->Corrupted) { + return context->Corrupted; + } + while (length-- && !context->Corrupted) { + context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); context->Length_Low += 8; - if (context->Length_Low == 0) - { - context->Length_High++; - if (context->Length_High == 0) - { - /* Message is too long */ - context->Corrupted = 1; - } + if (context->Length_Low == 0) { + context->Length_High++; + if (context->Length_High == 0) { + /* Message is too long */ + context->Corrupted = 1; + } } - if (context->Message_Block_Index == 64) - { - SHA1ProcessMessageBlock(context); + if (context->Message_Block_Index == 64) { + SHA1ProcessMessageBlock(context); } message_array++; - } + } - return shaSuccess; + return shaSuccess; } /* @@ -233,91 +212,83 @@ int SHA1Input( SHA1Context *context, * * */ -void SHA1ProcessMessageBlock(SHA1Context *context) +void SHA1ProcessMessageBlock(SHA1Context* context) { - const uint32_t K[] = { /* Constants defined in SHA-1 */ - 0x5A827999, - 0x6ED9EBA1, - 0x8F1BBCDC, - 0xCA62C1D6 - }; - int t; /* Loop counter */ - uint32_t temp; /* Temporary word value */ - uint32_t W[80]; /* Word sequence */ - uint32_t A, B, C, D, E; /* Word buffers */ - - /* - * Initialize the first 16 words in the array W - */ - for(t = 0; t < 16; t++) - { - W[t] = context->Message_Block[t * 4] << 24; - W[t] |= context->Message_Block[t * 4 + 1] << 16; - W[t] |= context->Message_Block[t * 4 + 2] << 8; - W[t] |= context->Message_Block[t * 4 + 3]; - } - - for(t = 16; t < 80; t++) - { - W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); - } - - A = context->Intermediate_Hash[0]; - B = context->Intermediate_Hash[1]; - C = context->Intermediate_Hash[2]; - D = context->Intermediate_Hash[3]; - E = context->Intermediate_Hash[4]; - - for(t = 0; t < 20; t++) - { - temp = SHA1CircularShift(5,A) + - ((B & C) | ((~B) & D)) + E + W[t] + K[0]; - E = D; - D = C; - C = SHA1CircularShift(30,B); - - B = A; - A = temp; - } - - for(t = 20; t < 40; t++) - { - temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; - E = D; - D = C; - C = SHA1CircularShift(30,B); - B = A; - A = temp; - } - - for(t = 40; t < 60; t++) - { - temp = SHA1CircularShift(5,A) + - ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; - E = D; - D = C; - C = SHA1CircularShift(30,B); - B = A; - A = temp; - } - - for(t = 60; t < 80; t++) - { - temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; - E = D; - D = C; - C = SHA1CircularShift(30,B); - B = A; - A = temp; - } - - context->Intermediate_Hash[0] += A; - context->Intermediate_Hash[1] += B; - context->Intermediate_Hash[2] += C; - context->Intermediate_Hash[3] += D; - context->Intermediate_Hash[4] += E; - - context->Message_Block_Index = 0; + const uint32_t K[] = { /* Constants defined in SHA-1 */ + 0x5A827999, + 0x6ED9EBA1, + 0x8F1BBCDC, + 0xCA62C1D6 + }; + int t; /* Loop counter */ + uint32_t temp; /* Temporary word value */ + uint32_t W[80]; /* Word sequence */ + uint32_t A, B, C, D, E; /* Word buffers */ + + /* + * Initialize the first 16 words in the array W + */ + for (t = 0; t < 16; t++) { + W[t] = context->Message_Block[t * 4] << 24; + W[t] |= context->Message_Block[t * 4 + 1] << 16; + W[t] |= context->Message_Block[t * 4 + 2] << 8; + W[t] |= context->Message_Block[t * 4 + 3]; + } + + for (t = 16; t < 80; t++) { + W[t] = SHA1CircularShift(1, W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]); + } + + A = context->Intermediate_Hash[0]; + B = context->Intermediate_Hash[1]; + C = context->Intermediate_Hash[2]; + D = context->Intermediate_Hash[3]; + E = context->Intermediate_Hash[4]; + + for (t = 0; t < 20; t++) { + temp = SHA1CircularShift(5, A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; + E = D; + D = C; + C = SHA1CircularShift(30, B); + + B = A; + A = temp; + } + + for (t = 20; t < 40; t++) { + temp = SHA1CircularShift(5, A) + (B ^ C ^ D) + E + W[t] + K[1]; + E = D; + D = C; + C = SHA1CircularShift(30, B); + B = A; + A = temp; + } + + for (t = 40; t < 60; t++) { + temp = SHA1CircularShift(5, A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; + E = D; + D = C; + C = SHA1CircularShift(30, B); + B = A; + A = temp; + } + + for (t = 60; t < 80; t++) { + temp = SHA1CircularShift(5, A) + (B ^ C ^ D) + E + W[t] + K[3]; + E = D; + D = C; + C = SHA1CircularShift(30, B); + B = A; + A = temp; + } + + context->Intermediate_Hash[0] += A; + context->Intermediate_Hash[1] += B; + context->Intermediate_Hash[2] += C; + context->Intermediate_Hash[3] += D; + context->Intermediate_Hash[4] += E; + + context->Message_Block_Index = 0; } /* @@ -344,50 +315,44 @@ void SHA1ProcessMessageBlock(SHA1Context *context) * */ -void SHA1PadMessage(SHA1Context *context) +void SHA1PadMessage(SHA1Context* context) { - /* - * Check to see if the current message block is too small to hold - * the initial padding bits and length. If so, we will pad the - * block, process it, and then continue padding into a second - * block. - */ - if (context->Message_Block_Index > 55) - { - context->Message_Block[context->Message_Block_Index++] = 0x80; - while(context->Message_Block_Index < 64) - { - context->Message_Block[context->Message_Block_Index++] = 0; - } - - SHA1ProcessMessageBlock(context); - - while(context->Message_Block_Index < 56) - { - context->Message_Block[context->Message_Block_Index++] = 0; - } - } - else - { - context->Message_Block[context->Message_Block_Index++] = 0x80; - while(context->Message_Block_Index < 56) - { - - context->Message_Block[context->Message_Block_Index++] = 0; - } + /* + * Check to see if the current message block is too small to hold + * the initial padding bits and length. If so, we will pad the + * block, process it, and then continue padding into a second + * block. + */ + if (context->Message_Block_Index > 55) { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while (context->Message_Block_Index < 64) { + context->Message_Block[context->Message_Block_Index++] = 0; } - /* - * Store the message length as the last 8 octets - */ - context->Message_Block[56] = context->Length_High >> 24; - context->Message_Block[57] = context->Length_High >> 16; - context->Message_Block[58] = context->Length_High >> 8; - context->Message_Block[59] = context->Length_High; - context->Message_Block[60] = context->Length_Low >> 24; - context->Message_Block[61] = context->Length_Low >> 16; - context->Message_Block[62] = context->Length_Low >> 8; - context->Message_Block[63] = context->Length_Low; - SHA1ProcessMessageBlock(context); + + while (context->Message_Block_Index < 56) { + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + else { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while (context->Message_Block_Index < 56) { + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + + /* + * Store the message length as the last 8 octets + */ + context->Message_Block[56] = context->Length_High >> 24; + context->Message_Block[57] = context->Length_High >> 16; + context->Message_Block[58] = context->Length_High >> 8; + context->Message_Block[59] = context->Length_High; + context->Message_Block[60] = context->Length_Low >> 24; + context->Message_Block[61] = context->Length_Low >> 16; + context->Message_Block[62] = context->Length_Low >> 8; + context->Message_Block[63] = context->Length_Low; + + SHA1ProcessMessageBlock(context); } diff --git a/base/sha1_rfc3174.h b/base/sha1_rfc3174.h index 2ba591abb..7c9a70a4e 100644 --- a/base/sha1_rfc3174.h +++ b/base/sha1_rfc3174.h @@ -35,13 +35,12 @@ extern "C" { */ #ifndef _SHA_enum_ -#define _SHA_enum_ -enum -{ - shaSuccess = 0, - shaNull, /* Null pointer parameter */ - shaInputTooLong, /* input data too long */ - shaStateError /* called Input after Result */ + #define _SHA_enum_ +enum { + shaSuccess = 0, + shaNull, /* Null pointer parameter */ + shaInputTooLong, /* input data too long */ + shaStateError /* called Input after Result */ }; #endif #define SHA1HashSize 20 @@ -50,34 +49,30 @@ enum * This structure will hold context information for the SHA-1 * hashing operation */ -typedef struct SHA1Context -{ - uint32_t Intermediate_Hash[SHA1HashSize/4]; /* Message Digest */ +typedef struct SHA1Context { + uint32_t Intermediate_Hash[SHA1HashSize / 4]; /* Message Digest */ - uint32_t Length_Low; /* Message length in bits */ - uint32_t Length_High; /* Message length in bits */ + uint32_t Length_Low; /* Message length in bits */ + uint32_t Length_High; /* Message length in bits */ - /* Index into message block array */ - int16_t Message_Block_Index; - uint8_t Message_Block[64]; /* 512-bit message blocks */ + /* Index into message block array */ + int16_t Message_Block_Index; + uint8_t Message_Block[64]; /* 512-bit message blocks */ - int Computed; /* Is the digest computed? */ - int Corrupted; /* Is the message digest corrupted? */ + int Computed; /* Is the digest computed? */ + int Corrupted; /* Is the message digest corrupted? */ } SHA1Context; /* * Function Prototypes */ -int SHA1Reset( SHA1Context *); -int SHA1Input( SHA1Context *, - const uint8_t *, - unsigned int); -int SHA1Result( SHA1Context *, - uint8_t Message_Digest[SHA1HashSize]); +int SHA1Reset(SHA1Context*); +int SHA1Input(SHA1Context*, const uint8_t*, unsigned int); +int SHA1Result(SHA1Context*, uint8_t Message_Digest[SHA1HashSize]); #ifdef __cplusplus } #endif -#endif // BASE_SHA1_RFC3174_H_INCLUDED +#endif // BASE_SHA1_RFC3174_H_INCLUDED diff --git a/base/split_string.cpp b/base/split_string.cpp index 747c06f5b..e89a53e4d 100644 --- a/base/split_string.cpp +++ b/base/split_string.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/split_string.h" @@ -14,33 +14,30 @@ namespace { - struct is_separator { - const std::string* separators; +struct is_separator { + const std::string* separators; - is_separator(const std::string* seps) : separators(seps) { - } + is_separator(const std::string* seps) : separators(seps) {} - bool operator()(std::string::value_type chr) const - { - for (std::string::const_iterator - it = separators->begin(), - end = separators->end(); it != end; ++it) { - if (chr == *it) - return true; - } - return false; + bool operator()(std::string::value_type chr) const + { + for (std::string::const_iterator it = separators->begin(), end = separators->end(); it != end; + ++it) { + if (chr == *it) + return true; } - }; + return false; + } +}; -} +} // namespace void base::split_string(const std::string& string, std::vector& parts, const std::string& separators) { const std::size_t elements = - 1 + std::count_if(string.begin(), string.end(), - is_separator(&separators)); + 1 + std::count_if(string.begin(), string.end(), is_separator(&separators)); parts.reserve(elements); std::size_t beg = 0, end; @@ -48,7 +45,7 @@ void base::split_string(const std::string& string, end = string.find_first_of(separators, beg); if (end != std::string::npos) { parts.push_back(string.substr(beg, end - beg)); - beg = end+1; + beg = end + 1; } else { parts.push_back(string.substr(beg)); diff --git a/base/split_string.h b/base/split_string.h index 65c896dbe..6907fa717 100644 --- a/base/split_string.h +++ b/base/split_string.h @@ -13,9 +13,9 @@ namespace base { - void split_string(const std::string& string, - std::vector& parts, - const std::string& separators); +void split_string(const std::string& string, + std::vector& parts, + const std::string& separators); } diff --git a/base/string.cpp b/base/string.cpp index 6942f97f7..3b6c1f19d 100644 --- a/base/string.cpp +++ b/base/string.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/debug.h" @@ -38,7 +38,7 @@ std::string string_vprintf(const char* format, va_list ap) va_copy(ap2, ap); const size_t required_size = std::vsnprintf(nullptr, 0, format, ap); if (required_size > 0) { - buf.resize(required_size+1); + buf.resize(required_size + 1); std::vsnprintf(buf.data(), buf.size(), format, ap2); } va_end(ap2); @@ -73,39 +73,28 @@ std::string string_to_upper(const std::string& original) std::string to_utf8(const wchar_t* src, const size_t n) { - int required_size = - ::WideCharToMultiByte(CP_UTF8, 0, - src, (int)n, - NULL, 0, NULL, NULL); + int required_size = ::WideCharToMultiByte(CP_UTF8, 0, src, (int)n, NULL, 0, NULL, NULL); if (required_size == 0) return std::string(); std::vector buf(++required_size); - ::WideCharToMultiByte(CP_UTF8, 0, - src, (int)n, - &buf[0], required_size, - NULL, NULL); + ::WideCharToMultiByte(CP_UTF8, 0, src, (int)n, &buf[0], required_size, NULL, NULL); return std::string(&buf[0]); } std::wstring from_utf8(const std::string& src) { - int required_size = - MultiByteToWideChar(CP_UTF8, 0, - src.c_str(), (int)src.size(), - NULL, 0); + int required_size = MultiByteToWideChar(CP_UTF8, 0, src.c_str(), (int)src.size(), NULL, 0); if (required_size == 0) return std::wstring(); std::vector buf(++required_size); - ::MultiByteToWideChar(CP_UTF8, 0, - src.c_str(), (int)src.size(), - &buf[0], required_size); + ::MultiByteToWideChar(CP_UTF8, 0, src.c_str(), (int)src.size(), &buf[0], required_size); return std::wstring(&buf[0]); } @@ -124,7 +113,7 @@ static std::size_t insert_utf8_char(std::string* result, wchar_t chr) } bits = 7; - while (chr >= (1<= (1 << bits)) bits++; size = 2; @@ -136,16 +125,16 @@ static std::size_t insert_utf8_char(std::string* result, wchar_t chr) } if (result) { - b -= (7-size); - int firstbyte = chr>>b; - for (i=0; i>i); + b -= (7 - size); + int firstbyte = chr >> b; + for (i = 0; i < size; i++) + firstbyte |= (0x80 >> i); result->push_back(firstbyte); - for (i=1; ipush_back(0x80 | ((chr>>b)&0x3F)); + result->push_back(0x80 | ((chr >> b) & 0x3F)); } } @@ -158,7 +147,7 @@ std::string to_utf8(const wchar_t* src, const size_t n) // doesn't need to reallocate its data. std::size_t required_size = 0; const auto* p = src; - for (size_t i=0; i buf(++required_size); std::vector::iterator buf_it = buf.begin(); -#ifdef _DEBUG + #ifdef _DEBUG std::vector::iterator buf_end = buf.end(); -#endif + #endif utf8_decode decode(src); while (const int chr = decode.next()) { @@ -209,9 +198,7 @@ int utf8_icmp(const std::string& a, const std::string& b, int n) utf8_decode b_decode(b); int i = 0; - for (; (n == 0 || i < n) - && !a_decode.is_end() - && !b_decode.is_end(); ++i) { + for (; (n == 0 || i < n) && !a_decode.is_end() && !b_decode.is_end(); ++i) { int a_chr = a_decode.next(); if (!a_chr) break; @@ -223,8 +210,10 @@ int utf8_icmp(const std::string& a, const std::string& b, int n) a_chr = std::tolower(a_chr); b_chr = std::tolower(b_chr); - if (a_chr < b_chr) return -1; - if (a_chr > b_chr) return 1; + if (a_chr < b_chr) + return -1; + if (a_chr > b_chr) + return 1; } if (n > 0 && i == n) diff --git a/base/string.h b/base/string.h index 08a8e60c1..d53285533 100644 --- a/base/string.h +++ b/base/string.h @@ -15,23 +15,24 @@ namespace base { - std::string string_printf(const char* format, ...); - std::string string_vprintf(const char* format, std::va_list ap); +std::string string_printf(const char* format, ...); +std::string string_vprintf(const char* format, std::va_list ap); - std::string string_to_lower(const std::string& original); - std::string string_to_upper(const std::string& original); +std::string string_to_lower(const std::string& original); +std::string string_to_upper(const std::string& original); - std::string to_utf8(const wchar_t* src, size_t n); +std::string to_utf8(const wchar_t* src, size_t n); - inline std::string to_utf8(const std::wstring& widestring) { - return to_utf8(widestring.c_str(), widestring.size()); - } +inline std::string to_utf8(const std::wstring& widestring) +{ + return to_utf8(widestring.c_str(), widestring.size()); +} - std::wstring from_utf8(const std::string& utf8string); +std::wstring from_utf8(const std::string& utf8string); - int utf8_length(const std::string& utf8string); - int utf8_icmp(const std::string& a, const std::string& b, int n = 0); +int utf8_length(const std::string& utf8string); +int utf8_icmp(const std::string& a, const std::string& b, int n = 0); -} +} // namespace base #endif diff --git a/base/string_tests.cpp b/base/string_tests.cpp index 65b519735..dbb657ddb 100644 --- a/base/string_tests.cpp +++ b/base/string_tests.cpp @@ -15,7 +15,8 @@ using namespace base; -int count_utf8_codepoints(const std::string& str) { +int count_utf8_codepoints(const std::string& str) +{ int count = 0; utf8_decode dec(str); while (dec.next()) @@ -56,9 +57,9 @@ TEST(String, Utf8Decode) dec = utf8_decode(d); while (const int ch = dec.next()) { // 日本語 switch (i++) { - case 0: EXPECT_EQ(ch, 0x65E5); break; - case 1: EXPECT_EQ(ch, 0x672C); break; - case 2: EXPECT_EQ(ch, 0x8A9E); break; + case 0: EXPECT_EQ(ch, 0x65E5); break; + case 1: EXPECT_EQ(ch, 0x672C); break; + case 2: EXPECT_EQ(ch, 0x8A9E); break; default: EXPECT_FALSE(true); break; } } @@ -78,7 +79,7 @@ TEST(String, Utf8Decode) ASSERT_EQ(11, count_utf8_codepoints(f)); ASSERT_EQ('C', f_dec.next()); ASSERT_EQ('o', f_dec.next()); - for (int i=0; i<8; ++i) // Skip 8 chars + for (int i = 0; i < 8; ++i) // Skip 8 chars f_dec.next(); ASSERT_EQ(0xA9, f_dec.next()); ASSERT_EQ(0, f_dec.next()); @@ -124,9 +125,9 @@ TEST(String, StringToLowerByUnicodeCharIssue1065) // Required to make old string_to_lower() version fail. std::setlocale(LC_ALL, "en-US"); - std::string a = "\xC2\xBA"; + std::string a = "\xC2\xBA"; std::wstring b = from_utf8(a); - std::string c = to_utf8(b); + std::string c = to_utf8(b); ASSERT_EQ(a, c); ASSERT_EQ("\xC2\xBA", c); @@ -151,34 +152,27 @@ TEST(String, StringToLowerByUnicodeCharIssue1065) // decoding state as invalid). TEST(String, Utf8DecodeDontCrash) { - auto decodeAllChars = - [](const std::string& str, bool shouldBeValid) -> int { - utf8_decode decode(str); - int chrs = 0; - while (int chr = decode.next()) { - ++chrs; - } - if (shouldBeValid) - EXPECT_TRUE(decode.is_valid()); - else - EXPECT_FALSE(decode.is_valid()); - return chrs; - }; + auto decodeAllChars = [](const std::string& str, bool shouldBeValid) -> int { + utf8_decode decode(str); + int chrs = 0; + while (int chr = decode.next()) { + ++chrs; + } + if (shouldBeValid) + EXPECT_TRUE(decode.is_valid()); + else + EXPECT_FALSE(decode.is_valid()); + return chrs; + }; std::string str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"; // 日本語 ASSERT_EQ(9, str.size()); bool valid_decoding[10] = { true, // Empty string is decoded correctly - false, false, true, - false, false, true, - false, false, true }; - int decoded_chars[10] = { 0, - 0, 0, 1, - 1, 1, 2, - 2, 2, 3 }; - - for (int n=0; n<=str.size(); ++n) { - int chrs = decodeAllChars(str.substr(0, n).c_str(), - valid_decoding[n]); + false, false, true, false, false, true, false, false, true }; + int decoded_chars[10] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 3 }; + + for (int n = 0; n <= str.size(); ++n) { + int chrs = decodeAllChars(str.substr(0, n).c_str(), valid_decoding[n]); EXPECT_EQ(decoded_chars[n], chrs); } } diff --git a/base/system_console.cpp b/base/system_console.cpp index 8ebf51e41..49ad6b70e 100644 --- a/base/system_console.cpp +++ b/base/system_console.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/system_console.h" @@ -17,11 +17,11 @@ // linked with /subsystem:windows. These adjustments are not great but // are good enough. See system_console.h for more information. -#include -#include + #include + #include -#include -#include + #include + #include namespace base { @@ -46,8 +46,10 @@ SystemConsole::SystemConsole() if (withConsole) { // Here we redirect stdout/stderr to use the parent console's ones. - if (unknownOut) std::freopen("CONOUT$", "w", stdout); - if (unknownErr) std::freopen("CONOUT$", "w", stderr); + if (unknownOut) + std::freopen("CONOUT$", "w", stdout); + if (unknownErr) + std::freopen("CONOUT$", "w", stderr); // Synchronize C++'s cout/cerr streams with C's stdout/stderr. std::ios::sync_with_stdio(); @@ -83,16 +85,22 @@ void SystemConsole::prepareShell() std::ios::sync_with_stdio(); } -} +} // namespace base -#else // On Unix-like systems the console works just fine +#else // On Unix-like systems the console works just fine namespace base { -SystemConsole::SystemConsole() { } -SystemConsole::~SystemConsole() { } -void SystemConsole::prepareShell() { } - +SystemConsole::SystemConsole() +{ } +SystemConsole::~SystemConsole() +{ +} +void SystemConsole::prepareShell() +{ +} + +} // namespace base #endif diff --git a/base/system_console.h b/base/system_console.h index 1bf6653fd..fd6e4d4ef 100644 --- a/base/system_console.h +++ b/base/system_console.h @@ -38,8 +38,7 @@ namespace base { // possible. The output/input is deattached as soon as cmd.exe knows // that the program was linked with /subsystem:windows. // -class SystemConsole -{ +class SystemConsole { public: SystemConsole(); ~SystemConsole(); diff --git a/base/task.cpp b/base/task.cpp index 0d48dea4e..ad6f5094d 100644 --- a/base/task.cpp +++ b/base/task.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/task.h" @@ -15,9 +15,7 @@ namespace base { -task::task() - : m_running(false) - , m_completed(false) +task::task() : m_running(false), m_completed(false) { } @@ -28,7 +26,7 @@ task::~task() // m_completed can be false in this case if the task was never // started (i.e. the user never called task::start()). - //ASSERT(m_completed); + // ASSERT(m_completed); } task_token& task::start(thread_pool& pool) @@ -41,7 +39,7 @@ task_token& task::start(thread_pool& pool) m_completed = false; m_token.reset(); - pool.execute([this]{ in_worker_thread(); }); + pool.execute([this] { in_worker_thread(); }); return m_token; } diff --git a/base/task.h b/base/task.h index ff8a8d89f..ae55a9683 100644 --- a/base/task.h +++ b/base/task.h @@ -16,70 +16,69 @@ namespace base { - class task; - class thread_pool; - - class task_token { - friend class task; - public: - task_token() - : m_canceled(false) - , m_progress(0.0f) - , m_progress_min(0.0f) - , m_progress_max(1.0f) { } - - bool canceled() const { return m_canceled; } - float progress() const { return m_progress; } - - void cancel() { m_canceled = true; } - void set_progress(float p) { - ASSERT(p >= 0.0f && p <= 1.0f); - m_progress = m_progress_min - + p * (m_progress_max - m_progress_min); - } - void set_progress_range(float min, float max) { - m_progress_min = min; - m_progress_max = max; - } - - private: - void reset() { - m_canceled = false; - m_progress = 0.0f; - } - - std::atomic m_canceled; - std::atomic m_progress; - float m_progress_min, m_progress_max; - }; - - class task { - public: - typedef std::function func_t; - - task(); - ~task(); - - void on_execute(func_t&& f) { m_execute = std::move(f); } - - task_token& start(thread_pool& pool); - - bool running() const { return m_running; } - - // Returns true when the task is completed (whether it was - // canceled or not). If this is true, it's safe to delete the task - // instance (it will not be used anymore by any othe background - // thread). - bool completed() const { return m_completed; } - - private: - void in_worker_thread(); - - std::atomic m_running; - std::atomic m_completed; - task_token m_token; - func_t m_execute; - }; +class task; +class thread_pool; + +class task_token { + friend class task; + +public: + task_token() : m_canceled(false), m_progress(0.0f), m_progress_min(0.0f), m_progress_max(1.0f) {} + + bool canceled() const { return m_canceled; } + float progress() const { return m_progress; } + + void cancel() { m_canceled = true; } + void set_progress(float p) + { + ASSERT(p >= 0.0f && p <= 1.0f); + m_progress = m_progress_min + p * (m_progress_max - m_progress_min); + } + void set_progress_range(float min, float max) + { + m_progress_min = min; + m_progress_max = max; + } + +private: + void reset() + { + m_canceled = false; + m_progress = 0.0f; + } + + std::atomic m_canceled; + std::atomic m_progress; + float m_progress_min, m_progress_max; +}; + +class task { +public: + typedef std::function func_t; + + task(); + ~task(); + + void on_execute(func_t&& f) { m_execute = std::move(f); } + + task_token& start(thread_pool& pool); + + bool running() const { return m_running; } + + // Returns true when the task is completed (whether it was + // canceled or not). If this is true, it's safe to delete the task + // instance (it will not be used anymore by any othe background + // thread). + bool completed() const { return m_completed; } + +private: + void in_worker_thread(); + + std::atomic m_running; + std::atomic m_completed; + task_token m_token; + func_t m_execute; +}; } // namespace base diff --git a/base/task_tests.cpp b/base/task_tests.cpp index 3012d5ba3..7c90d81d8 100644 --- a/base/task_tests.cpp +++ b/base/task_tests.cpp @@ -17,7 +17,7 @@ TEST(Task, Basic) std::atomic c(0); thread_pool p(10); for (task& t : tasks) { - t.on_execute([&c](task_token&){ ++c; }); + t.on_execute([&c](task_token&) { ++c; }); t.start(p); } p.wait_all(); @@ -34,12 +34,12 @@ TEST(Task, MultiplePools) std::atomic c(0); - for (int i=0; i<100; ++i) { - tasks1[i].on_execute([&c](task_token&){ c += 2; }); - tasks2[i].on_execute([&c](task_token&){ --c; }); + for (int i = 0; i < 100; ++i) { + tasks1[i].on_execute([&c](task_token&) { c += 2; }); + tasks2[i].on_execute([&c](task_token&) { --c; }); } - for (int i=0; i<100; ++i) { + for (int i = 0; i < 100; ++i) { tasks1[i].start(p1); tasks2[i].start(p2); } @@ -48,7 +48,7 @@ TEST(Task, MultiplePools) p2.wait_all(); EXPECT_EQ(100, c); - for (int i=0; i<100; ++i) + for (int i = 0; i < 100; ++i) tasks2[i].start(p2); p2.wait_all(); EXPECT_EQ(0, c); diff --git a/base/thread.cpp b/base/thread.cpp index 95a524c77..6fd35cd51 100644 --- a/base/thread.cpp +++ b/base/thread.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/thread.h" @@ -15,15 +15,15 @@ #include "base/dll.h" #include "base/string.h" - #include - #include #include + #include + #include #else - #include // Use pthread library in Unix-like systems + #include // Use pthread library in Unix-like systems - #include - #include #include + #include + #include #endif #if LAF_WINDOWS @@ -37,11 +37,14 @@ class KernelBaseApi { SetThreadDescription_Func SetThreadDescription = nullptr; GetThreadDescription_Func GetThreadDescription = nullptr; - KernelBaseApi() { + KernelBaseApi() + { m_dll = base::load_dll("KernelBase.dll"); if (m_dll) { - SetThreadDescription = base::get_dll_proc(m_dll, "SetThreadDescription"); - GetThreadDescription = base::get_dll_proc(m_dll, "GetThreadDescription"); + SetThreadDescription = base::get_dll_proc(m_dll, + "SetThreadDescription"); + GetThreadDescription = base::get_dll_proc(m_dll, + "GetThreadDescription"); } } @@ -93,8 +96,7 @@ void this_thread::set_name(const std::string& name) { #if LAF_WINDOWS if (kernelBaseApi.SetThreadDescription) - kernelBaseApi.SetThreadDescription(GetCurrentThread(), - base::from_utf8(name).c_str()); + kernelBaseApi.SetThreadDescription(GetCurrentThread(), base::from_utf8(name).c_str()); #elif LAF_MACOS // macOS has a non-standard pthread_setname_np() impl int res = pthread_setname_np(name.c_str()); @@ -125,7 +127,7 @@ std::string this_thread::get_name() } #else char name[65]; - const int result = pthread_getname_np(pthread_self(), name, sizeof(name)-1); + const int result = pthread_getname_np(pthread_self(), name, sizeof(name) - 1); if (result == 0) { // Returns 0 if it was successful // pthread_getname_np() returns a null terminated name. return std::string(name); diff --git a/base/thread.h b/base/thread.h index 613999575..b1a794f5c 100644 --- a/base/thread.h +++ b/base/thread.h @@ -11,8 +11,7 @@ #include -namespace base { -namespace this_thread { +namespace base { namespace this_thread { void yield(); @@ -25,7 +24,6 @@ void sleep_for(double seconds); void set_name(const std::string& name); std::string get_name(); -} // this_thread -} // base +}} // namespace base::this_thread #endif diff --git a/base/thread_pool.cpp b/base/thread_pool.cpp index f9c184ea5..1d17330d3 100644 --- a/base/thread_pool.cpp +++ b/base/thread_pool.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/debug.h" @@ -14,14 +14,11 @@ namespace base { -thread_pool::thread_pool(const size_t n) - : m_running(true) - , m_threads(n) - , m_doingWork(0) +thread_pool::thread_pool(const size_t n) : m_running(true), m_threads(n), m_doingWork(0) { const std::unique_lock lock(m_mutex); - for (size_t i=0; i&& func) void thread_pool::wait_all() { std::unique_lock lock(m_mutex); - m_cvWait.wait(lock, [this]() -> bool { - return - !m_running || - (m_work.empty() && m_doingWork == 0); - }); + m_cvWait.wait(lock, + [this]() -> bool { return !m_running || (m_work.empty() && m_doingWork == 0); }); } void thread_pool::join_all() @@ -82,9 +76,7 @@ void thread_pool::worker() std::function func; { std::unique_lock lock(m_mutex); - m_cv.wait(lock, [this]() -> bool { - return !m_running || !m_work.empty(); - }); + m_cv.wait(lock, [this]() -> bool { return !m_running || !m_work.empty(); }); running = m_running; if (m_running && !m_work.empty()) { func = std::move(m_work.front()); @@ -115,4 +107,4 @@ void thread_pool::worker() } } -} +} // namespace base diff --git a/base/thread_pool.h b/base/thread_pool.h index 12f3a0c3d..671369e3d 100644 --- a/base/thread_pool.h +++ b/base/thread_pool.h @@ -17,32 +17,32 @@ namespace base { - class thread_pool { - public: - thread_pool(const size_t n); - ~thread_pool(); +class thread_pool { +public: + thread_pool(const size_t n); + ~thread_pool(); - void execute(std::function&& func); + void execute(std::function&& func); - // Waits until the queue is empty. - void wait_all(); + // Waits until the queue is empty. + void wait_all(); - private: - // Joins all threads without waiting the queue to be processed. - void join_all(); +private: + // Joins all threads without waiting the queue to be processed. + void join_all(); - // Called for each worker thread. - void worker(); + // Called for each worker thread. + void worker(); - bool m_running; - std::vector m_threads; - std::mutex m_mutex; - std::condition_variable m_cv; - std::condition_variable m_cvWait; - std::queue> m_work; - int m_doingWork; - }; + bool m_running; + std::vector m_threads; + std::mutex m_mutex; + std::condition_variable m_cv; + std::condition_variable m_cvWait; + std::queue> m_work; + int m_doingWork; +}; -} +} // namespace base #endif diff --git a/base/thread_pool_tests.cpp b/base/thread_pool_tests.cpp index ccf5bbe17..5454f9bc1 100644 --- a/base/thread_pool_tests.cpp +++ b/base/thread_pool_tests.cpp @@ -16,8 +16,8 @@ TEST(ThreadPool, Basic) { thread_pool p(10); std::atomic c(0); - for (int i=0; i<10000; ++i) - p.execute([&c]{ ++c; }); + for (int i = 0; i < 10000; ++i) + p.execute([&c] { ++c; }); p.wait_all(); EXPECT_EQ(10000, c); diff --git a/base/thread_tests.cpp b/base/thread_tests.cpp index 8cbdec599..747e025ec 100644 --- a/base/thread_tests.cpp +++ b/base/thread_tests.cpp @@ -41,7 +41,8 @@ TEST(Thread, NameLimits) // Limited to 64 chars (including the null char) EXPECT_EQ("123456789012345678901234567890" "123456789012345678901234567890" - "123", this_thread::get_name()); + "123", + this_thread::get_name()); #else // Limited to 16 chars (including the null char) EXPECT_EQ("123456789012345", this_thread::get_name()); diff --git a/base/time.cpp b/base/time.cpp index 130bc57e0..c991a088f 100644 --- a/base/time.cpp +++ b/base/time.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/time.h" @@ -45,9 +45,7 @@ Time current_time() const std::time_t now = std::time(nullptr); std::tm t; safe_localtime(now, &t); - return Time( - t.tm_year+1900, t.tm_mon+1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec); + return Time(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); #endif } @@ -70,12 +68,13 @@ tick_t current_tick() static mach_timebase_info_data_t timebase = { 0, 0 }; if (timebase.denom == 0) (void)mach_timebase_info(&timebase); - return tick_t(double(mach_absolute_time()) * double(timebase.numer) / double(timebase.denom) / 1.0e6); + return tick_t(double(mach_absolute_time()) * double(timebase.numer) / double(timebase.denom) / + 1.0e6); #else // TODO use clock_gettime(CLOCK_MONOTONIC, &now); if it's possible struct timeval now; gettimeofday(&now, nullptr); - return now.tv_sec*1000 + now.tv_usec/1000; + return now.tv_sec * 1000 + now.tv_usec / 1000; #endif } @@ -86,8 +85,8 @@ Time& Time::addSeconds(const int seconds) tm.tm_min = minute; tm.tm_hour = hour; tm.tm_mday = day; - tm.tm_mon = month-1; - tm.tm_year = year-1900; + tm.tm_mon = month - 1; + tm.tm_year = year - 1900; tm.tm_wday = 0; tm.tm_yday = 0; @@ -103,8 +102,8 @@ Time& Time::addSeconds(const int seconds) std::tm t; safe_localtime(tt, &t); - year = t.tm_year+1900; - month = t.tm_mon+1; + year = t.tm_year + 1900; + month = t.tm_mon + 1; day = t.tm_mday; hour = t.tm_hour; minute = t.tm_min; @@ -116,19 +115,24 @@ Time& Time::addSeconds(const int seconds) bool Time::operator<(const Time& other) const { int d = year - other.year; - if (d != 0) return (d < 0); + if (d != 0) + return (d < 0); d = month - other.month; - if (d != 0) return (d < 0); + if (d != 0) + return (d < 0); d = day - other.day; - if (d != 0) return (d < 0); + if (d != 0) + return (d < 0); d = hour - other.hour; - if (d != 0) return (d < 0); + if (d != 0) + return (d < 0); d = minute - other.minute; - if (d != 0) return (d < 0); + if (d != 0) + return (d < 0); return (second < other.second); } diff --git a/base/time.h b/base/time.h index ae4228017..8586ab27e 100644 --- a/base/time.h +++ b/base/time.h @@ -16,61 +16,49 @@ namespace base { - // ~1000 per second - typedef uint64_t tick_t; - - class Time { - public: - int year, month, day; - int hour, minute, second; - - Time(int year = 0, int month = 0, int day = 0, - int hour = 0, int minute = 0, int second = 0) - : year(year), month(month), day(day) - , hour(hour), minute(minute), second(second) { - } - - bool valid() const { - return (year != 0 && month != 0 && day != 0); - } - - void dateOnly() { - hour = minute = second = 0; - } - - Time& addSeconds(int seconds); - Time& addMinutes(const int minutes) { - return addSeconds(minutes*60); - } - Time& addHours(const int hours) { - return addSeconds(hours*60*60); - } - Time& addDays(const int days) { - return addSeconds(days*24*60*60); - } - - bool operator==(const Time& other) const { - return - year == other.year && - month == other.month && - day == other.day && - hour == other.hour && - minute == other.minute && - second == other.second; - } - - bool operator!=(const Time& other) const { - return !operator==(other); - } - - bool operator<(const Time& other) const; - }; - - bool safe_localtime(std::time_t time, std::tm* result); - - Time current_time(); - tick_t current_tick(); - -} +// ~1000 per second +typedef uint64_t tick_t; + +class Time { +public: + int year, month, day; + int hour, minute, second; + + Time(int year = 0, int month = 0, int day = 0, int hour = 0, int minute = 0, int second = 0) + : year(year) + , month(month) + , day(day) + , hour(hour) + , minute(minute) + , second(second) + { + } + + bool valid() const { return (year != 0 && month != 0 && day != 0); } + + void dateOnly() { hour = minute = second = 0; } + + Time& addSeconds(int seconds); + Time& addMinutes(const int minutes) { return addSeconds(minutes * 60); } + Time& addHours(const int hours) { return addSeconds(hours * 60 * 60); } + Time& addDays(const int days) { return addSeconds(days * 24 * 60 * 60); } + + bool operator==(const Time& other) const + { + return year == other.year && month == other.month && day == other.day && hour == other.hour && + minute == other.minute && second == other.second; + } + + bool operator!=(const Time& other) const { return !operator==(other); } + + bool operator<(const Time& other) const; +}; + +bool safe_localtime(std::time_t time, std::tm* result); + +Time current_time(); +tick_t current_tick(); + +} // namespace base #endif diff --git a/base/time_tests.cpp b/base/time_tests.cpp index 6f1ece077..218c62c8d 100644 --- a/base/time_tests.cpp +++ b/base/time_tests.cpp @@ -12,17 +12,14 @@ using namespace base; namespace base { - std::ostream& operator<<(std::ostream& os, const Time& t) { - return os << t.year << '-' - << t.month << '-' - << t.day << ' ' - << t.hour << ':' - << t.minute << ':' - << t.second; - } - +std::ostream& operator<<(std::ostream& os, const Time& t) +{ + return os << t.year << '-' << t.month << '-' << t.day << ' ' << t.hour << ':' << t.minute << ':' + << t.second; } +} // namespace base + TEST(Time, Cmp) { EXPECT_EQ(Time(2018, 5, 2, 0, 0, 1), Time(2018, 5, 2, 0, 0, 0).addSeconds(1)); diff --git a/base/tok.h b/base/tok.h index e7c870d76..89022078a 100644 --- a/base/tok.h +++ b/base/tok.h @@ -14,11 +14,14 @@ #include #include -namespace base { -namespace tok { +namespace base { namespace tok { -struct ignore_empties { enum { allow_empty = false }; }; -struct include_empties { enum { allow_empty = true }; }; +struct ignore_empties { + enum { allow_empty = false }; +}; +struct include_empties { + enum { allow_empty = true }; +}; template class token_iterator { @@ -34,17 +37,17 @@ class token_iterator { token_iterator() = delete; token_iterator(const token_iterator&) = default; - token_iterator(const internal_iterator& begin, - const internal_iterator& end, - char_type chr) : - begin_(begin), - inter_(begin), - end_(end), - chr_(chr) { + token_iterator(const internal_iterator& begin, const internal_iterator& end, char_type chr) + : begin_(begin) + , inter_(begin) + , end_(end) + , chr_(chr) + { operator++(); // Find first word to fill "str_" field } - token_iterator& operator++() { + token_iterator& operator++() + { if constexpr (EmptyPolicy::allow_empty) { if (inter_ != end_ && *inter_ == chr_) { ++inter_; @@ -63,13 +66,9 @@ class token_iterator { return *this; } - const_reference operator*() { - return str_; - } + const_reference operator*() { return str_; } - bool operator!=(const token_iterator& that) const { - return (begin_ != that.end_); - } + bool operator!=(const token_iterator& that) const { return (begin_ != that.end_); } private: internal_iterator begin_, inter_, end_; @@ -83,7 +82,7 @@ class token_range { using char_type = typename T::value_type; using iterator = token_iterator; - token_range(const T& str, char_type chr) : str_(str), chr_(chr) { } + token_range(const T& str, char_type chr) : str_(str), chr_(chr) {} iterator begin() const { return iterator(str_.begin(), str_.end(), chr_); } iterator end() const { return iterator(str_.end(), str_.end(), chr_); } @@ -94,20 +93,17 @@ class token_range { }; template -token_range -split_tokens(const T& str, - typename T::value_type chr) { +token_range split_tokens(const T& str, typename T::value_type chr) +{ return token_range(str, chr); } template -token_range -csv(const T& str, - typename T::value_type chr = ',') { +token_range csv(const T& str, typename T::value_type chr = ',') +{ return token_range(str, chr); } -} // namespace tok -} // namespace base +}} // namespace base::tok #endif diff --git a/base/tok_tests.cpp b/base/tok_tests.cpp index 140848c5c..e27c6e29e 100644 --- a/base/tok_tests.cpp +++ b/base/tok_tests.cpp @@ -18,7 +18,8 @@ TEST(Tok, SplitTokens) { int i = 0; - auto a_result = std::vector{ "This", "is", "a", "phrase.", "Several", "whitespaces", "are", "ignored." }; + auto a_result = std::vector{ "This", "is", "a", "phrase.", + "Several", "whitespaces", "are", "ignored." }; std::string a = "This is a phrase. Several whitespaces are ignored."; for (auto& tok : base::tok::split_tokens(a, ' ')) { std::cout << "\"" << tok << "\"\n"; @@ -29,7 +30,8 @@ TEST(Tok, SplitTokens) TEST(Tok, Csv) { int i = 0; - auto b_result = std::vector{ "In comma", "separated", "", "values", "", "", "empties are included" }; + auto b_result = std::vector{ "In comma", "separated", "", "values", "", + "", "empties are included" }; std::string b = "In comma,separated,,values,,,empties are included"; for (auto& tok : base::tok::csv(b, ',')) { std::cout << "\"" << tok << "\"\n"; diff --git a/base/trim_string.h b/base/trim_string.h index ba72dee06..0c79648a5 100644 --- a/base/trim_string.h +++ b/base/trim_string.h @@ -14,17 +14,15 @@ namespace base { template -void trim_string(const std::string& input, - std::string& output, - const Pred& pred) +void trim_string(const std::string& input, std::string& output, const Pred& pred) { int i, j; - for (i=0; i<(int)input.size(); ++i) + for (i = 0; i < (int)input.size(); ++i) if (!pred(input.at(i))) break; - for (j=(int)input.size()-1; j>i; --j) + for (j = (int)input.size() - 1; j > i; --j) if (!pred(input.at(j))) break; @@ -34,11 +32,11 @@ void trim_string(const std::string& input, output = std::string(); } -inline void trim_string(const std::string& input, - std::string& output) { +inline void trim_string(const std::string& input, std::string& output) +{ trim_string(input, output, std::isspace); } -} +} // namespace base #endif diff --git a/base/utf8_decode.h b/base/utf8_decode.h index c49b7aa69..9ccd0172f 100644 --- a/base/utf8_decode.h +++ b/base/utf8_decode.h @@ -12,97 +12,89 @@ namespace base { - class utf8_decode { - public: - using string = std::string; - using string_ref = const std::string&; - using iterator = std::string::const_iterator; - - utf8_decode() { } - utf8_decode(const utf8_decode&) = default; - utf8_decode& operator=(const utf8_decode&) = default; - - explicit utf8_decode(string_ref str) - : m_it(str.begin()) - , m_end(str.end()) { - } - - iterator pos() const { - return m_it; - } - - bool is_end() const { - return m_it == m_end; - } - - bool is_valid() const { - return m_valid; - } +class utf8_decode { +public: + using string = std::string; + using string_ref = const std::string&; + using iterator = std::string::const_iterator; + + utf8_decode() {} + utf8_decode(const utf8_decode&) = default; + utf8_decode& operator=(const utf8_decode&) = default; + + explicit utf8_decode(string_ref str) : m_it(str.begin()), m_end(str.end()) {} + + iterator pos() const { return m_it; } + + bool is_end() const { return m_it == m_end; } + + bool is_valid() const { return m_valid; } + + int next() + { + if (m_it == m_end) + return 0; + + int c = *m_it; + ++m_it; + + // UTF-8 escape bit 0x80 to encode larger code points + if (c & 0b1000'0000) { + // Get the number of bits following the first one 0b1xxx'xxxx, + // which indicates the number of extra bytes in the input + // string following this one, and that will be part of the + // final Unicode code point. + // + // This is like "number of leading ones", similar to a + // __builtin_clz(~x)-24 (for 8 bits), anyway doing some tests, + // the CLZ intrinsic is not faster than this code in x86_64. + int n = 0; + int f = 0b0100'0000; + while (c & f) { + ++n; + f >>= 1; + } - int next() { - if (m_it == m_end) + if (n == 0) { + // Invalid UTF-8: 0b10xx'xxxx alone, i.e. not inside a + // escaped sequence (e.g. after 0b110xx'xxx + m_valid = false; return 0; + } - int c = *m_it; - ++m_it; - - // UTF-8 escape bit 0x80 to encode larger code points - if (c & 0b1000'0000) { - // Get the number of bits following the first one 0b1xxx'xxxx, - // which indicates the number of extra bytes in the input - // string following this one, and that will be part of the - // final Unicode code point. - // - // This is like "number of leading ones", similar to a - // __builtin_clz(~x)-24 (for 8 bits), anyway doing some tests, - // the CLZ intrinsic is not faster than this code in x86_64. - int n = 0; - int f = 0b0100'0000; - while (c & f) { - ++n; - f >>= 1; - } + // Keep only the few initial data bits from the first byte (6 + // first bits if we have only one extra char, then for each + // extra char we have less useful data in this first byte). + c &= (0b0001'1111 >> (n - 1)); - if (n == 0) { - // Invalid UTF-8: 0b10xx'xxxx alone, i.e. not inside a - // escaped sequence (e.g. after 0b110xx'xxx + while (n--) { + if (m_it == m_end) { + // Invalid UTF-8: missing 0b10xx'xxxx bytes m_valid = false; return 0; } - - // Keep only the few initial data bits from the first byte (6 - // first bits if we have only one extra char, then for each - // extra char we have less useful data in this first byte). - c &= (0b0001'1111 >> (n-1)); - - while (n--) { - if (m_it == m_end) { - // Invalid UTF-8: missing 0b10xx'xxxx bytes - m_valid = false; - return 0; - } - const int chr = *m_it; - ++m_it; - if ((chr & 0b1100'0000) != 0b1000'0000) { - // Invalid UTF-8: Extra byte doesn't contain 0b10xx'xxxx - m_valid = false; - return 0; - } - // Each extra byte in the encoded string adds 6 bits of - // information for the final Unicode code point. - c = (c << 6) | (chr & 0b0011'1111); + const int chr = *m_it; + ++m_it; + if ((chr & 0b1100'0000) != 0b1000'0000) { + // Invalid UTF-8: Extra byte doesn't contain 0b10xx'xxxx + m_valid = false; + return 0; } + // Each extra byte in the encoded string adds 6 bits of + // information for the final Unicode code point. + c = (c << 6) | (chr & 0b0011'1111); } - - return c; } - private: - iterator m_it; - iterator m_end; - bool m_valid = true; - }; + return c; + } + +private: + iterator m_it; + iterator m_end; + bool m_valid = true; +}; -} +} // namespace base #endif diff --git a/base/uuid.h b/base/uuid.h index 62049531b..5e96d91b8 100644 --- a/base/uuid.h +++ b/base/uuid.h @@ -14,7 +14,7 @@ // Uncomment if you want to debug the generation of the UUID, and the // its string conversion. -//#define LAF_BASE_TRACE_UUID 1 +// #define LAF_BASE_TRACE_UUID 1 #if LAF_BASE_TRACE_UUID #include "base/convert_to.h" #include "base/string.h" @@ -22,23 +22,23 @@ namespace base { - // A universally unique identifier. - class Uuid { - public: - enum { HashSize = 36 }; +// A universally unique identifier. +class Uuid { +public: + enum { HashSize = 36 }; - static Uuid Generate(); + static Uuid Generate(); - uint8_t operator[](int i) const { return m_data[i]; } - bool operator==(const Uuid& b) const { return std::memcmp(m_data, b.m_data, 16) == 0; } - bool operator!=(const Uuid& b) const { return !operator==(b); } + uint8_t operator[](int i) const { return m_data[i]; } + bool operator==(const Uuid& b) const { return std::memcmp(m_data, b.m_data, 16) == 0; } + bool operator!=(const Uuid& b) const { return !operator==(b); } - const uint8_t* bytes() const { return &m_data[0]; } - uint8_t* bytes() { return &m_data[0]; } + const uint8_t* bytes() const { return &m_data[0]; } + uint8_t* bytes() { return &m_data[0]; } - private: - uint8_t m_data[16] = { }; - }; +private: + uint8_t m_data[16] = {}; +}; } // namespace base diff --git a/base/uuid_osx.mm b/base/uuid_osx.mm index 1b4b36b60..ed98fb429 100644 --- a/base/uuid_osx.mm +++ b/base/uuid_osx.mm @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/uuid.h" diff --git a/base/uuid_tests.cpp b/base/uuid_tests.cpp index 56c95f689..3de462f40 100644 --- a/base/uuid_tests.cpp +++ b/base/uuid_tests.cpp @@ -13,7 +13,7 @@ using namespace base; TEST(Uuid, Empty) { Uuid uuid; - for (int i=0; i<16; ++i) { + for (int i = 0; i < 16; ++i) { EXPECT_EQ(0, uuid[i]); } } @@ -23,11 +23,11 @@ TEST(Uuid, Generate) constexpr int N = 1024; Uuid uuids[N]; - for (int i=0; i(std::string((const char*)buf.data())); #if LAF_BASE_TRACE_UUID - if (buf[buf.size()-1] == '\n') - buf[buf.size()-1] = 0; + if (buf[buf.size() - 1] == '\n') + buf[buf.size() - 1] = 0; printf("convert_to = \"%s\"\n" "random/uuid = \"%s\"\n", - base::convert_to(uuid).c_str(), buf.data()); + base::convert_to(uuid).c_str(), + buf.data()); #endif } return uuid; diff --git a/base/uuid_win.cpp b/base/uuid_win.cpp index 5d843e6f4..155e52700 100644 --- a/base/uuid_win.cpp +++ b/base/uuid_win.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/uuid.h" @@ -34,14 +34,16 @@ Uuid Uuid::Generate() bytes[5] = guid.Data2 & 0xff; bytes[6] = (guid.Data3 >> 8) & 0xff; bytes[7] = guid.Data3 & 0xff; - std::memcpy(bytes+8, guid.Data4, 8); + std::memcpy(bytes + 8, guid.Data4, 8); #if LAF_BASE_TRACE_UUID LPOLESTR wstr; if (StringFromCLSID(guid, &wstr) == S_OK) { std::string str = base::string_to_lower(base::to_utf8(wstr)); - if (!str.empty() && str.front() == '{') str.erase(0, 1); - if (!str.empty() && str.back() == '}') str.erase(str.size()-1, 1); + if (!str.empty() && str.front() == '{') + str.erase(0, 1); + if (!str.empty() && str.back() == '}') + str.erase(str.size() - 1, 1); printf("convert_to = \"%s\"\n" "UuidToStringA = \"%s\"\n", base::convert_to(uuid).c_str(), diff --git a/base/vector2d.h b/base/vector2d.h index e519a3821..841f49673 100644 --- a/base/vector2d.h +++ b/base/vector2d.h @@ -12,68 +12,86 @@ namespace base { - template - class Vector2d { - public: - T x, y; - - Vector2d() { - x = y = 0.0; - } - - Vector2d(const T& u, const T& v) { - x = u; y = v; - } - - Vector2d(const Vector2d& v) { - x = v.x; y = v.y; - } - - Vector2d operator-() const { return Vector2d(-x, -y); } - - Vector2d operator+(const Vector2d& v) const { return Vector2d(x+v.x, y+v.y); } - Vector2d operator-(const Vector2d& v) const { return Vector2d(x-v.x, y-v.y); } - T operator*(const Vector2d& v) const { return dotProduct(v); } - Vector2d operator*(const T& f) const { return Vector2d(x*f, y*f); } - Vector2d operator/(const T& f) const { return Vector2d(x/f, y/f); } - - Vector2d& operator= (const Vector2d& v) { x=v.x; y=v.y; return *this; } - Vector2d& operator+=(const Vector2d& v) { x+=v.x; y+=v.y; return *this; } - Vector2d& operator-=(const Vector2d& v) { x-=v.x; y-=v.y; return *this; } - Vector2d& operator*=(const T& f) { x*=f; y*=f; return *this; } - Vector2d& operator/=(const T& f) { x/=f; y/=f; return *this; } - - T magnitude() const { - return std::sqrt(x*x + y*y); - } - - T dotProduct(const Vector2d& v) const { - return x*v.x + y*v.y; - } - - Vector2d projectOn(const Vector2d& v) const { - return v * (this->dotProduct(v) / std::pow(v.magnitude(), 2)); - } - - T angle() const { - return std::atan2(y, x); - } - - Vector2d normalize() const { - return Vector2d(*this) / magnitude(); - } - - Vector2d getNormal() const { - return Vector2d(y, -x); - } - - }; +template +class Vector2d { +public: + T x, y; + + Vector2d() { x = y = 0.0; } + + Vector2d(const T& u, const T& v) + { + x = u; + y = v; + } + + Vector2d(const Vector2d& v) + { + x = v.x; + y = v.y; + } + + Vector2d operator-() const { return Vector2d(-x, -y); } + + Vector2d operator+(const Vector2d& v) const { return Vector2d(x + v.x, y + v.y); } + Vector2d operator-(const Vector2d& v) const { return Vector2d(x - v.x, y - v.y); } + T operator*(const Vector2d& v) const { return dotProduct(v); } + Vector2d operator*(const T& f) const { return Vector2d(x * f, y * f); } + Vector2d operator/(const T& f) const { return Vector2d(x / f, y / f); } + + Vector2d& operator=(const Vector2d& v) + { + x = v.x; + y = v.y; + return *this; + } + Vector2d& operator+=(const Vector2d& v) + { + x += v.x; + y += v.y; + return *this; + } + Vector2d& operator-=(const Vector2d& v) + { + x -= v.x; + y -= v.y; + return *this; + } + Vector2d& operator*=(const T& f) + { + x *= f; + y *= f; + return *this; + } + Vector2d& operator/=(const T& f) + { + x /= f; + y /= f; + return *this; + } + + T magnitude() const { return std::sqrt(x * x + y * y); } + + T dotProduct(const Vector2d& v) const { return x * v.x + y * v.y; } + + Vector2d projectOn(const Vector2d& v) const + { + return v * (this->dotProduct(v) / std::pow(v.magnitude(), 2)); + } + + T angle() const { return std::atan2(y, x); } + + Vector2d normalize() const { return Vector2d(*this) / magnitude(); } + + Vector2d getNormal() const { return Vector2d(y, -x); } +}; } // namespace base template -base::Vector2d operator*(const T& f, const base::Vector2d& v) { - return base::Vector2d(v.x*f, v.y*f); +base::Vector2d operator*(const T& f, const base::Vector2d& v) +{ + return base::Vector2d(v.x * f, v.y * f); } #endif // BASE_VECTOR2D_H_INCLUDED diff --git a/base/version.cpp b/base/version.cpp index d7426a10b..da3ea87c2 100644 --- a/base/version.cpp +++ b/base/version.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/version.h" @@ -27,14 +27,13 @@ Version::Version(const std::string& from) std::string::size_type j = 0; std::string::size_type k = from.find('-', 0); - while ((j != std::string::npos) && - (k == std::string::npos || j < k)) { + while ((j != std::string::npos) && (k == std::string::npos || j < k)) { j = from.find('.', i); std::string number; if (j != std::string::npos) { number = from.substr(i, j - i); - i = j+1; + i = j + 1; } else { if (from.size() == i) // Empty string @@ -58,9 +57,8 @@ Version::Version(const std::string& from) m_prereleaseLabel = from.substr(k0); } - while (!m_prereleaseLabel.empty() && - m_prereleaseLabel[m_prereleaseLabel.size()-1] == '.') - m_prereleaseLabel.erase(m_prereleaseLabel.size()-1); + while (!m_prereleaseLabel.empty() && m_prereleaseLabel[m_prereleaseLabel.size() - 1] == '.') + m_prereleaseLabel.erase(m_prereleaseLabel.size() - 1); } Version::Version(int major, int minor, int patch, int build) @@ -76,16 +74,17 @@ Version::Version(int major, int minor, int patch, int build) bool Version::operator<(const Version& other) const { - Numbers::const_iterator - it1 = m_numbers.begin(), end1 = m_numbers.end(), - it2 = other.m_numbers.begin(), end2 = other.m_numbers.end(); + Numbers::const_iterator it1 = m_numbers.begin(), end1 = m_numbers.end(), + it2 = other.m_numbers.begin(), end2 = other.m_numbers.end(); while (it1 != end1 || it2 != end2) { - int number1 = (it1 != end1 ? *it1++: 0); - int number2 = (it2 != end2 ? *it2++: 0); + int number1 = (it1 != end1 ? *it1++ : 0); + int number2 = (it2 != end2 ? *it2++ : 0); - if (number1 < number2) return true; - if (number1 > number2) return false; + if (number1 < number2) + return true; + if (number1 > number2) + return false; } if (m_prereleaseLabel.empty()) @@ -94,15 +93,16 @@ bool Version::operator<(const Version& other) const return true; int res = m_prereleaseLabel.compare(other.m_prereleaseLabel); - if (res < 0) return true; - if (res > 0) return false; + if (res < 0) + return true; + if (res > 0) + return false; return (m_prereleaseNumber < other.m_prereleaseNumber); } bool Version::operator==(const Version& other) const { - return (m_numbers == other.m_numbers && - m_prereleaseLabel == other.m_prereleaseLabel); + return (m_numbers == other.m_numbers && m_prereleaseLabel == other.m_prereleaseLabel); } std::string Version::str() const diff --git a/base/version.h b/base/version.h index 0e7f4ae9b..c7b0db863 100644 --- a/base/version.h +++ b/base/version.h @@ -14,36 +14,36 @@ namespace base { - class Version { - public: - typedef std::vector Numbers; +class Version { +public: + typedef std::vector Numbers; - Version(); - explicit Version(const std::string& from); - Version(int major, int minor, int patch, int build); + Version(); + explicit Version(const std::string& from); + Version(int major, int minor, int patch, int build); - int major() const { return (m_numbers.size() > 0 ? m_numbers[0]: 0); } - int minor() const { return (m_numbers.size() > 1 ? m_numbers[1]: 0); } - int patch() const { return (m_numbers.size() > 2 ? m_numbers[2]: 0); } - int build() const { return (m_numbers.size() > 3 ? m_numbers[3]: 0); } + int major() const { return (m_numbers.size() > 0 ? m_numbers[0] : 0); } + int minor() const { return (m_numbers.size() > 1 ? m_numbers[1] : 0); } + int patch() const { return (m_numbers.size() > 2 ? m_numbers[2] : 0); } + int build() const { return (m_numbers.size() > 3 ? m_numbers[3] : 0); } - bool operator<(const Version& other) const; - bool operator==(const Version& other) const; - bool operator!=(const Version& other) const { return !operator==(other); } + bool operator<(const Version& other) const; + bool operator==(const Version& other) const; + bool operator!=(const Version& other) const { return !operator==(other); } - bool empty() const { return m_numbers.empty(); } - const Numbers& numbers() const { return m_numbers; } - const std::string& prereleaseLabel() const { return m_prereleaseLabel; } - const int prereleaseNumber() const { return m_prereleaseNumber; } + bool empty() const { return m_numbers.empty(); } + const Numbers& numbers() const { return m_numbers; } + const std::string& prereleaseLabel() const { return m_prereleaseLabel; } + const int prereleaseNumber() const { return m_prereleaseNumber; } - std::string str() const; + std::string str() const; - private: - Numbers m_numbers; - std::string m_prereleaseLabel; // alpha, beta, dev, rc (empty if it's official release) - int m_prereleaseNumber = 0; - }; +private: + Numbers m_numbers; + std::string m_prereleaseLabel; // alpha, beta, dev, rc (empty if it's official release) + int m_prereleaseNumber = 0; +}; -} +} // namespace base #endif diff --git a/base/version_tests.cpp b/base/version_tests.cpp index 61049f940..bc39efa67 100644 --- a/base/version_tests.cpp +++ b/base/version_tests.cpp @@ -7,19 +7,20 @@ #include -#include "base/version.h" #include "base/convert_to.h" +#include "base/version.h" using namespace base; namespace base { - std::ostream& operator<<(std::ostream& os, const Version& ver) { - return os << ver.str(); - } - +std::ostream& operator<<(std::ostream& os, const Version& ver) +{ + return os << ver.str(); } +} // namespace base + TEST(Version, Ctor) { EXPECT_EQ("1", Version("1").str()); diff --git a/base/win/comptr.h b/base/win/comptr.h index eb3aba504..42bc45273 100644 --- a/base/win/comptr.h +++ b/base/win/comptr.h @@ -17,69 +17,69 @@ namespace base { - template - class ComPtr { - public: - ComPtr() { } - - ComPtr(const ComPtr& p) : m_ptr(p.m_ptr) { +template +class ComPtr { +public: + ComPtr() {} + + ComPtr(const ComPtr& p) : m_ptr(p.m_ptr) + { + if (m_ptr) + m_ptr->AddRef(); + } + + ComPtr(ComPtr&& tmp) { std::swap(m_ptr, tmp.m_ptr); } + + explicit ComPtr(T* p) : m_ptr(p) + { + if (m_ptr) + m_ptr->AddRef(); + } + + ~ComPtr() { reset(); } + + T** operator&() { return &m_ptr; } + T* operator->() { return m_ptr; } + operator bool() const { return m_ptr != nullptr; } + + // Add new reference using operator=() + ComPtr& operator=(const ComPtr& p) + { + if (this != &p) { if (m_ptr) - m_ptr->AddRef(); - } - - ComPtr(ComPtr&& tmp) { - std::swap(m_ptr, tmp.m_ptr); - } - - explicit ComPtr(T* p) : m_ptr(p) { + m_ptr->Release(); + m_ptr = p.m_ptr; if (m_ptr) m_ptr->AddRef(); } - - ~ComPtr() { - reset(); - } - - T** operator&() { return &m_ptr; } - T* operator->() { return m_ptr; } - operator bool() const { return m_ptr != nullptr; } - - // Add new reference using operator=() - ComPtr& operator=(const ComPtr& p) { - if (this != &p) { - if (m_ptr) - m_ptr->Release(); - m_ptr = p.m_ptr; - if (m_ptr) - m_ptr->AddRef(); - } - return *this; - } - - ComPtr& operator=(ComPtr&& p) noexcept { - std::swap(m_ptr, p.m_ptr); - return *this; - } - - ComPtr& operator=(std::nullptr_t) { - reset(); - return *this; - } - - T* get() { - return m_ptr; - } - - void reset() { - if (m_ptr) { - m_ptr->Release(); - m_ptr = nullptr; - } + return *this; + } + + ComPtr& operator=(ComPtr&& p) noexcept + { + std::swap(m_ptr, p.m_ptr); + return *this; + } + + ComPtr& operator=(std::nullptr_t) + { + reset(); + return *this; + } + + T* get() { return m_ptr; } + + void reset() + { + if (m_ptr) { + m_ptr->Release(); + m_ptr = nullptr; } + } - private: - T* m_ptr = nullptr; - }; +private: + T* m_ptr = nullptr; +}; } // namespace base diff --git a/base/win/registry.cpp b/base/win/registry.cpp index f8b5f3a9b..7871e0658 100644 --- a/base/win/registry.cpp +++ b/base/win/registry.cpp @@ -1,210 +1,228 @@ -// LAF Base Library -// Copyright (c) 2023 Igara Studio S.A. -// Copyright (c) 2017 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "base/win/registry.h" - -#include "base/string.h" -#include "base/win/win32_exception.h" - -#include -#include - -namespace base { - -namespace { - -REGSAM to_regsam(const hkey::access a) -{ - switch (a) { - case hkey::access::read: return KEY_READ; - case hkey::access::write: return KEY_READ | KEY_WRITE; - } - return KEY_ALL_ACCESS; -} - -} // anonymous namespace - -hkey hkey::classes_root() { return hkey(HKEY_CLASSES_ROOT); } -hkey hkey::current_config() { return hkey(HKEY_CURRENT_CONFIG); } -hkey hkey::current_user() { return hkey(HKEY_CURRENT_USER); } -hkey hkey::local_machine() { return hkey(HKEY_LOCAL_MACHINE); } -hkey hkey::users() { return hkey(HKEY_USERS); } - -hkey::hkey(HKEY hkey) - : m_hkey(hkey) -{ -} - -hkey::hkey(hkey&& key) - : m_hkey(nullptr) -{ - std::swap(m_hkey, key.m_hkey); -} - -hkey::~hkey() -{ - close(); -} - -hkey& hkey::operator=(hkey&& key) -{ - close(); - std::swap(m_hkey, key.m_hkey); - return *this; -} - -hkey hkey::open(const std::string& subkey, const access a) -{ - if (!m_hkey) - return hkey(nullptr); - - HKEY openKey = nullptr; - LONG result = RegOpenKeyExW(m_hkey, from_utf8(subkey).c_str(), - 0, to_regsam(a), &openKey); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error opening registry key"); - - return hkey(openKey); -} - -hkey hkey::create(const std::string& subkey) -{ - if (!m_hkey) - return nullptr; - - HKEY newKey = nullptr; - LONG result = RegCreateKeyExW(m_hkey, from_utf8(subkey).c_str(), - 0, nullptr, - REG_OPTION_NON_VOLATILE, - KEY_READ | KEY_WRITE, - nullptr, &newKey, nullptr); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error creating registry key"); - - return hkey(newKey); -} - -void hkey::close() -{ - if (m_hkey) { - // If m_key is a predefined HKEY like HKEY_CLASSES_ROOT, etc. this - // does nothing anyway. - RegCloseKey(m_hkey); - m_hkey = nullptr; - } -} - -bool hkey::exists(const std::string& name) -{ - std::wstring wname = from_utf8(name); - LONG result = RegQueryValueExW(m_hkey, wname.c_str(), - nullptr, nullptr, nullptr, nullptr); - return (result == ERROR_SUCCESS); -} - -std::string hkey::string(const std::string& name) -{ - if (!m_hkey) - return std::string(); - - std::wstring wname = from_utf8(name); - - DWORD type = 0, reqSize = 0; - LONG result = RegQueryValueExW(m_hkey, wname.c_str(), nullptr, - (LPDWORD)&type, nullptr, - (LPDWORD)&reqSize); - - // Value name not found in this key - if (result == ERROR_FILE_NOT_FOUND) - return std::string(); - - if (result != ERROR_SUCCESS) - throw Win32Exception("Error getting registry value size"); - - if (reqSize == 0 || type != REG_SZ) - return std::string(); - - std::vector buf(reqSize / sizeof(wchar_t) + 1); - result = RegQueryValueExW(m_hkey, wname.c_str(), nullptr, - nullptr, (LPBYTE)&buf[0], - (LPDWORD)&reqSize); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error getting registry value"); - - buf[buf.size()-1] = 0; - - return to_utf8(&buf[0]); -} - -void hkey::string(const std::string& name, const std::string& value) -{ - if (!m_hkey) - return; - - std::wstring wvalue = from_utf8(value); - LONG result = RegSetValueExW(m_hkey, from_utf8(name).c_str(), - 0, REG_SZ, - (LPBYTE)wvalue.c_str(), - (DWORD)(wvalue.size()+1)*sizeof(wchar_t)); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error setting registry value"); -} - -DWORD hkey::dword(const std::string& name) -{ - if (!m_hkey) - return 0; - - DWORD - type = 0, - dword = 0, - size = sizeof(DWORD); - LONG result = RegQueryValueExW(m_hkey, from_utf8(name).c_str(), nullptr, - (LPDWORD)&type, (LPBYTE)&dword, - (LPDWORD)&size); - - // Value name not found in this key - if (result == ERROR_FILE_NOT_FOUND) - return 0; - - if (result != ERROR_SUCCESS) - throw Win32Exception("Error getting registry value"); - - if (type != REG_DWORD) - return 0; - - return dword; -} - -void hkey::dword(const std::string& name, const DWORD value) -{ - if (!m_hkey) - return; - - LONG result = RegSetValueExW(m_hkey, from_utf8(name).c_str(), - 0, REG_DWORD, - (LPBYTE)&value, - (DWORD)sizeof(DWORD)); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error setting registry value"); -} - -void hkey::delete_tree(const std::string& subkey) -{ - if (!m_hkey) - return; - - LONG result = RegDeleteTreeW(m_hkey, from_utf8(subkey).c_str()); - if (result != ERROR_SUCCESS) - throw Win32Exception("Error deleting registry key"); -} - -} // namespace base +// LAF Base Library +// Copyright (c) 2023 Igara Studio S.A. +// Copyright (c) 2017 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#ifdef HAVE_CONFIG_H + #include "config.h" +#endif + +#include "base/win/registry.h" + +#include "base/string.h" +#include "base/win/win32_exception.h" + +#include +#include + +namespace base { + +namespace { + +REGSAM to_regsam(const hkey::access a) +{ + switch (a) { + case hkey::access::read: return KEY_READ; + case hkey::access::write: return KEY_READ | KEY_WRITE; + } + return KEY_ALL_ACCESS; +} + +} // anonymous namespace + +hkey hkey::classes_root() +{ + return hkey(HKEY_CLASSES_ROOT); +} +hkey hkey::current_config() +{ + return hkey(HKEY_CURRENT_CONFIG); +} +hkey hkey::current_user() +{ + return hkey(HKEY_CURRENT_USER); +} +hkey hkey::local_machine() +{ + return hkey(HKEY_LOCAL_MACHINE); +} +hkey hkey::users() +{ + return hkey(HKEY_USERS); +} + +hkey::hkey(HKEY hkey) : m_hkey(hkey) +{ +} + +hkey::hkey(hkey&& key) : m_hkey(nullptr) +{ + std::swap(m_hkey, key.m_hkey); +} + +hkey::~hkey() +{ + close(); +} + +hkey& hkey::operator=(hkey&& key) +{ + close(); + std::swap(m_hkey, key.m_hkey); + return *this; +} + +hkey hkey::open(const std::string& subkey, const access a) +{ + if (!m_hkey) + return hkey(nullptr); + + HKEY openKey = nullptr; + LONG result = RegOpenKeyExW(m_hkey, from_utf8(subkey).c_str(), 0, to_regsam(a), &openKey); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error opening registry key"); + + return hkey(openKey); +} + +hkey hkey::create(const std::string& subkey) +{ + if (!m_hkey) + return nullptr; + + HKEY newKey = nullptr; + LONG result = RegCreateKeyExW(m_hkey, + from_utf8(subkey).c_str(), + 0, + nullptr, + REG_OPTION_NON_VOLATILE, + KEY_READ | KEY_WRITE, + nullptr, + &newKey, + nullptr); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error creating registry key"); + + return hkey(newKey); +} + +void hkey::close() +{ + if (m_hkey) { + // If m_key is a predefined HKEY like HKEY_CLASSES_ROOT, etc. this + // does nothing anyway. + RegCloseKey(m_hkey); + m_hkey = nullptr; + } +} + +bool hkey::exists(const std::string& name) +{ + std::wstring wname = from_utf8(name); + LONG result = RegQueryValueExW(m_hkey, wname.c_str(), nullptr, nullptr, nullptr, nullptr); + return (result == ERROR_SUCCESS); +} + +std::string hkey::string(const std::string& name) +{ + if (!m_hkey) + return std::string(); + + std::wstring wname = from_utf8(name); + + DWORD type = 0, reqSize = 0; + LONG result = + RegQueryValueExW(m_hkey, wname.c_str(), nullptr, (LPDWORD)&type, nullptr, (LPDWORD)&reqSize); + + // Value name not found in this key + if (result == ERROR_FILE_NOT_FOUND) + return std::string(); + + if (result != ERROR_SUCCESS) + throw Win32Exception("Error getting registry value size"); + + if (reqSize == 0 || type != REG_SZ) + return std::string(); + + std::vector buf(reqSize / sizeof(wchar_t) + 1); + result = + RegQueryValueExW(m_hkey, wname.c_str(), nullptr, nullptr, (LPBYTE)&buf[0], (LPDWORD)&reqSize); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error getting registry value"); + + buf[buf.size() - 1] = 0; + + return to_utf8(&buf[0]); +} + +void hkey::string(const std::string& name, const std::string& value) +{ + if (!m_hkey) + return; + + std::wstring wvalue = from_utf8(value); + LONG result = RegSetValueExW(m_hkey, + from_utf8(name).c_str(), + 0, + REG_SZ, + (LPBYTE)wvalue.c_str(), + (DWORD)(wvalue.size() + 1) * sizeof(wchar_t)); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error setting registry value"); +} + +DWORD hkey::dword(const std::string& name) +{ + if (!m_hkey) + return 0; + + DWORD + type = 0, dword = 0, size = sizeof(DWORD); + LONG result = RegQueryValueExW(m_hkey, + from_utf8(name).c_str(), + nullptr, + (LPDWORD)&type, + (LPBYTE)&dword, + (LPDWORD)&size); + + // Value name not found in this key + if (result == ERROR_FILE_NOT_FOUND) + return 0; + + if (result != ERROR_SUCCESS) + throw Win32Exception("Error getting registry value"); + + if (type != REG_DWORD) + return 0; + + return dword; +} + +void hkey::dword(const std::string& name, const DWORD value) +{ + if (!m_hkey) + return; + + LONG result = RegSetValueExW(m_hkey, + from_utf8(name).c_str(), + 0, + REG_DWORD, + (LPBYTE)&value, + (DWORD)sizeof(DWORD)); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error setting registry value"); +} + +void hkey::delete_tree(const std::string& subkey) +{ + if (!m_hkey) + return; + + LONG result = RegDeleteTreeW(m_hkey, from_utf8(subkey).c_str()); + if (result != ERROR_SUCCESS) + throw Win32Exception("Error deleting registry key"); +} + +} // namespace base diff --git a/base/win/registry.h b/base/win/registry.h index 16eb52af6..c7c371bd9 100644 --- a/base/win/registry.h +++ b/base/win/registry.h @@ -1,67 +1,67 @@ -// LAF Base Library -// Copyright (c) 2021-2023 Igara Studio S.A. -// Copyright (c) 2017 David Capello -// -// This file is released under the terms of the MIT license. -// Read LICENSE.txt for more information. - -#ifndef BASE_WIN_REGISTRY_H_INCLUDED -#define BASE_WIN_REGISTRY_H_INCLUDED - -#if !LAF_WINDOWS - #error This header file can be used only on Windows platform -#endif - -#include "base/disable_copying.h" - -#include -#include - -namespace base { - -class hkey { -public: - enum access { - read = 1, - write = 2, - }; - - static hkey classes_root(); - static hkey current_config(); - static hkey current_user(); - static hkey local_machine(); - static hkey users(); - - hkey(HKEY hkey); - hkey(hkey&& key); - ~hkey(); - - hkey& operator=(hkey&& key); - - HKEY handle() const { return m_hkey; } - - hkey open(const std::string& subkey, const access a); - hkey create(const std::string& subkey); - void close(); - - bool exists(const std::string& name); - - std::string string(const std::string& name); - void string(const std::string& name, const std::string& value); - - DWORD dword(const std::string& name); - void dword(const std::string& name, const DWORD value); - - // Deletes keys in the given subkey, if subkey == "", all children - // keys are deleted but this hkey isn't (the root is kept). - void delete_tree(const std::string& subkey); - -private: - HKEY m_hkey; - - DISABLE_COPYING(hkey); -}; - -} // namespace base - -#endif +// LAF Base Library +// Copyright (c) 2021-2023 Igara Studio S.A. +// Copyright (c) 2017 David Capello +// +// This file is released under the terms of the MIT license. +// Read LICENSE.txt for more information. + +#ifndef BASE_WIN_REGISTRY_H_INCLUDED +#define BASE_WIN_REGISTRY_H_INCLUDED + +#if !LAF_WINDOWS + #error This header file can be used only on Windows platform +#endif + +#include "base/disable_copying.h" + +#include +#include + +namespace base { + +class hkey { +public: + enum access { + read = 1, + write = 2, + }; + + static hkey classes_root(); + static hkey current_config(); + static hkey current_user(); + static hkey local_machine(); + static hkey users(); + + hkey(HKEY hkey); + hkey(hkey&& key); + ~hkey(); + + hkey& operator=(hkey&& key); + + HKEY handle() const { return m_hkey; } + + hkey open(const std::string& subkey, const access a); + hkey create(const std::string& subkey); + void close(); + + bool exists(const std::string& name); + + std::string string(const std::string& name); + void string(const std::string& name, const std::string& value); + + DWORD dword(const std::string& name); + void dword(const std::string& name, const DWORD value); + + // Deletes keys in the given subkey, if subkey == "", all children + // keys are deleted but this hkey isn't (the root is kept). + void delete_tree(const std::string& subkey); + +private: + HKEY m_hkey; + + DISABLE_COPYING(hkey); +}; + +} // namespace base + +#endif diff --git a/base/win/registry_tests.cpp b/base/win/registry_tests.cpp index d9cdb92d3..93188689d 100644 --- a/base/win/registry_tests.cpp +++ b/base/win/registry_tests.cpp @@ -17,8 +17,7 @@ TEST(Registry, OpenKey) try { hkey k = hkey::classes_root(); k = k.open(".txt", hkey::read); - EXPECT_TRUE(k.string("") == "txtfile" || - k.string("") == "txtfilelegacy"); + EXPECT_TRUE(k.string("") == "txtfile" || k.string("") == "txtfilelegacy"); EXPECT_EQ("text/plain", k.string("Content Type")); } catch (Win32Exception& ex) { @@ -50,8 +49,7 @@ TEST(Registry, CreateKey) // We cannot use k.delete_tree("") because it does delete the // whole tree, but leaves the root key untouched. - hkey::current_user() - .delete_tree("Software\\Classes\\.laf-base-test-extension"); + hkey::current_user().delete_tree("Software\\Classes\\.laf-base-test-extension"); } catch (Win32Exception& ex) { printf("Win32Exception: %s\nError Code: %d\n", ex.what(), ex.errorCode()); diff --git a/base/win/ver_query_values.cpp b/base/win/ver_query_values.cpp index 0cce889d0..71df1a71a 100644 --- a/base/win/ver_query_values.cpp +++ b/base/win/ver_query_values.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/win/ver_query_values.h" @@ -25,20 +25,10 @@ struct LANGCODEPAGE { WORD codepage; }; -static const char* fields[] = { - "Comments", - "CompanyName", - "FileDescription", - "FileVersion", - "InternalName", - "LegalCopyright", - "LegalTrademarks", - "OriginalFilename", - "PrivateBuild", - "ProductName", - "ProductVersion", - "SpecialBuild" -}; +static const char* fields[] = { "Comments", "CompanyName", "FileDescription", + "FileVersion", "InternalName", "LegalCopyright", + "LegalTrademarks", "OriginalFilename", "PrivateBuild", + "ProductName", "ProductVersion", "SpecialBuild" }; std::map ver_query_values(dll lib) { @@ -61,10 +51,7 @@ std::map ver_query_values(const wchar_t* filename) LANGCODEPAGE* pages = nullptr; UINT npages = 0; - VerQueryValueW(&data[0], - L"\\VarFileInfo\\Translation", - (LPVOID*)&pages, - &npages); + VerQueryValueW(&data[0], L"\\VarFileInfo\\Translation", (LPVOID*)&pages, &npages); // 41 chars max, e.g. // @@ -72,10 +59,7 @@ std::map ver_query_values(const wchar_t* filename) // std::vector buf(48); - for (const LANGCODEPAGE - *p=pages, - *end=pages + npages/sizeof(LANGCODEPAGE); - p!=end; ++p) { + for (const LANGCODEPAGE *p = pages, *end = pages + npages / sizeof(LANGCODEPAGE); p != end; ++p) { if ((p->language == 0x0409 || // US English p->language == 0x0809) && // UK English (p->codepage == 1200 || // Unicode @@ -85,23 +69,21 @@ std::map ver_query_values(const wchar_t* filename) if (result.find(field) != result.end()) continue; - std::snprintf(&buf[0], buf.size(), + std::snprintf(&buf[0], + buf.size(), "\\StringFileInfo\\%04x%04x\\%s", - p->language, p->codepage, field); + p->language, + p->codepage, + field); wchar_t* fieldBuf = nullptr; UINT fieldLen = 0; - if (VerQueryValueW( - &data[0], - from_utf8(std::string(&buf[0])).c_str(), - (LPVOID*)&fieldBuf, - &fieldLen) && - fieldBuf && - fieldLen) { - result[field] = - to_utf8( - std::wstring( - std::wstring_view(fieldBuf, fieldLen))); + if (VerQueryValueW(&data[0], + from_utf8(std::string(&buf[0])).c_str(), + (LPVOID*)&fieldBuf, + &fieldLen) && + fieldBuf && fieldLen) { + result[field] = to_utf8(std::wstring(std::wstring_view(fieldBuf, fieldLen))); } } } diff --git a/base/win/win32_exception.cpp b/base/win/win32_exception.cpp index 431a7017a..83e5ee980 100644 --- a/base/win/win32_exception.cpp +++ b/base/win/win32_exception.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/win/win32_exception.h" @@ -21,15 +21,14 @@ Win32Exception::Win32Exception(const std::string& msg) throw() , m_errorCode(GetLastError()) { LPVOID buf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | // TODO Try to use a TLS buffer - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - m_errorCode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR)&buf, - 0, NULL); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | // TODO Try to use a TLS buffer + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + m_errorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPWSTR)&buf, + 0, + NULL); setMessage((msg + "\n" + to_utf8((LPWSTR)buf)).c_str()); LocalFree(buf); diff --git a/base/win/win32_exception.h b/base/win/win32_exception.h index 7176a843a..7985e82c5 100644 --- a/base/win/win32_exception.h +++ b/base/win/win32_exception.h @@ -14,17 +14,17 @@ namespace base { - class Win32Exception : public Exception { - public: - Win32Exception(const std::string& msg) throw(); - virtual ~Win32Exception() throw(); +class Win32Exception : public Exception { +public: + Win32Exception(const std::string& msg) throw(); + virtual ~Win32Exception() throw(); - DWORD errorCode() const { return m_errorCode; } + DWORD errorCode() const { return m_errorCode; } - private: - DWORD m_errorCode; - }; +private: + DWORD m_errorCode; +}; -} +} // namespace base #endif diff --git a/examples/allevents.cpp b/examples/allevents.cpp index 40878a72e..a90914a77 100644 --- a/examples/allevents.cpp +++ b/examples/allevents.cpp @@ -16,8 +16,8 @@ class LogWindow { public: - LogWindow(os::System* system) - : m_window(system->makeWindow(800, 600)) { + LogWindow(os::System* system) : m_window(system->makeWindow(800, 600)) + { m_window->setTitle("All Events"); recalcMaxLines(); @@ -25,35 +25,30 @@ class LogWindow { logLine("-- Events Log --"); } - bool processEvent(const os::Event& ev) { + bool processEvent(const os::Event& ev) + { switch (ev.type()) { - case os::Event::CloseApp: - case os::Event::CloseWindow: - return false; + case os::Event::CloseWindow: return false; case os::Event::ResizeWindow: - logLine("ResizeWindow size=%d,%d", - m_window->width(), - m_window->height()); + logLine("ResizeWindow size=%d,%d", m_window->width(), m_window->height()); recalcMaxLines(); break; case os::Event::DropFiles: - logLine("DropFiles pos=%d,%d files={", - ev.position().x, - ev.position().y); + logLine("DropFiles pos=%d,%d files={", ev.position().x, ev.position().y); for (const auto& file : ev.files()) { logLine(" \"%s\"", file.c_str()); } logLine("}"); break; - case os::Event::MouseEnter: logMouseEvent(ev, "MouseEnter"); break; - case os::Event::MouseLeave: logMouseEvent(ev, "MouseLeave"); break; - case os::Event::MouseMove: logMouseEvent(ev, "MouseMove"); break; - case os::Event::MouseDown: logMouseEvent(ev, "MouseDown"); break; - case os::Event::MouseUp: logMouseEvent(ev, "MouseUp"); break; + case os::Event::MouseEnter: logMouseEvent(ev, "MouseEnter"); break; + case os::Event::MouseLeave: logMouseEvent(ev, "MouseLeave"); break; + case os::Event::MouseMove: logMouseEvent(ev, "MouseMove"); break; + case os::Event::MouseDown: logMouseEvent(ev, "MouseDown"); break; + case os::Event::MouseUp: logMouseEvent(ev, "MouseUp"); break; case os::Event::MouseDoubleClick: logMouseEvent(ev, "MouseDoubleClick"); break; case os::Event::MouseWheel: @@ -61,7 +56,7 @@ class LogWindow { logLine("MouseWheel pos=%d,%d %s=%d,%d%s", ev.position().x, ev.position().y, - ev.preciseWheel() ? " preciseWheel": "wheel", + ev.preciseWheel() ? " preciseWheel" : "wheel", ev.wheelDelta().x, ev.wheelDelta().y, modifiersToString(ev.modifiers()).c_str()); @@ -82,7 +77,7 @@ class LogWindow { case os::Event::KeyUp: { wchar_t wideUnicode[2] = { ev.unicodeChar(), 0 }; logLine("%s repeat=%d scancode=%d unicode=%d (%s)%s", - (ev.type() == os::Event::KeyDown ? "KeyDown": "KeyUp"), + (ev.type() == os::Event::KeyDown ? "KeyDown" : "KeyUp"), ev.repeat(), ev.scancode(), ev.unicodeChar(), @@ -92,9 +87,8 @@ class LogWindow { } case os::Event::TouchMagnify: - logLine("TouchMagnify %.4g", - ev.magnification()); - m_brushSize += 32*ev.magnification(); + logLine("TouchMagnify %.4g", ev.magnification()); + m_brushSize += 32 * ev.magnification(); m_brushSize = std::clamp(m_brushSize, 1.0, 500.0); break; @@ -105,7 +99,8 @@ class LogWindow { return true; } - void flush() { + void flush() + { if (m_oldLogSize != m_textLog.size()) { int newlines = m_textLog.size() - m_oldLogSize; while (m_textLog.size() > m_maxlines) @@ -118,11 +113,10 @@ class LogWindow { } private: - void recalcMaxLines() { - m_maxlines = (m_window->height() - m_lineHeight) / m_lineHeight; - } + void recalcMaxLines() { m_maxlines = (m_window->height() - m_lineHeight) / m_lineHeight; } - void scrollAndDrawLog(const int newlines) { + void scrollAndDrawLog(const int newlines) + { os::Surface* surface = m_window->surface(); os::SurfaceLock lock(surface); const gfx::Rect rc = surface->bounds(); @@ -134,26 +128,25 @@ class LogWindow { // Scroll old lines int i; if (m_textLog.size() >= m_maxlines) { - int h = m_lineHeight*newlines; + int h = m_lineHeight * newlines; surface->scrollTo(rc, 0, -h); - surface->drawRect(gfx::Rect(rc.x, rc.y, rc.w, rc.h-h), p); + surface->drawRect(gfx::Rect(rc.x, rc.y, rc.w, rc.h - h), p); p.color(gfx::rgba(0, 0, 0)); - surface->drawRect(gfx::Rect(rc.x, rc.y+rc.h-h, rc.w, h), p); + surface->drawRect(gfx::Rect(rc.x, rc.y + rc.h - h, rc.w, h), p); - i = (m_textLog.size()-newlines); + i = (m_textLog.size() - newlines); } // First lines without scroll else { i = m_oldLogSize; - surface->drawRect(gfx::Rect(rc.x, rc.y, rc.w, i*m_lineHeight), p); + surface->drawRect(gfx::Rect(rc.x, rc.y, rc.w, i * m_lineHeight), p); } os::Paint paint; paint.color(gfx::rgba(255, 255, 255)); - for (; isetVisible(true); } - void logMouseEvent(const os::Event& ev, const char* eventName) { + void logMouseEvent(const os::Event& ev, const char* eventName) + { const os::Event::MouseButton mb = ev.button(); const os::PointerType pt = ev.pointerType(); @@ -176,21 +170,24 @@ class LogWindow { eventName, ev.position().x, ev.position().y, - (mb == os::Event::LeftButton ? " LeftButton": - mb == os::Event::RightButton ? " RightButton": - mb == os::Event::MiddleButton ? " MiddleButton": - mb == os::Event::X1Button ? " X1Button": - mb == os::Event::X2Button ? " X2Button": ""), - (pt == os::PointerType::Mouse ? " Mouse": - pt == os::PointerType::Touchpad ? " Touchpad": - pt == os::PointerType::Touch ? " Touch": - pt == os::PointerType::Pen ? " Pen": - pt == os::PointerType::Cursor ? " Cursor": - pt == os::PointerType::Eraser ? " Eraser": ""), + (mb == os::Event::LeftButton ? " LeftButton" : + mb == os::Event::RightButton ? " RightButton" : + mb == os::Event::MiddleButton ? " MiddleButton" : + mb == os::Event::X1Button ? " X1Button" : + mb == os::Event::X2Button ? " X2Button" : + ""), + (pt == os::PointerType::Mouse ? " Mouse" : + pt == os::PointerType::Touchpad ? " Touchpad" : + pt == os::PointerType::Touch ? " Touch" : + pt == os::PointerType::Pen ? " Pen" : + pt == os::PointerType::Cursor ? " Cursor" : + pt == os::PointerType::Eraser ? " Eraser" : + ""), modifiersToString(ev.modifiers()).c_str()); } - void logLine(const char* str, ...) { + void logLine(const char* str, ...) + { va_list ap; va_start(ap, str); char buf[4096]; @@ -200,14 +197,21 @@ class LogWindow { m_textLog.push_back(buf); } - static std::string modifiersToString(os::KeyModifiers mods) { + static std::string modifiersToString(os::KeyModifiers mods) + { std::string s; - if (mods & os::kKeyShiftModifier) s += " Shift"; - if (mods & os::kKeyCtrlModifier ) s += " Ctrl"; - if (mods & os::kKeyAltModifier ) s += " Alt"; - if (mods & os::kKeyCmdModifier ) s += " Command"; - if (mods & os::kKeySpaceModifier) s += " Space"; - if (mods & os::kKeyWinModifier ) s += " Win"; + if (mods & os::kKeyShiftModifier) + s += " Shift"; + if (mods & os::kKeyCtrlModifier) + s += " Ctrl"; + if (mods & os::kKeyAltModifier) + s += " Alt"; + if (mods & os::kKeyCmdModifier) + s += " Command"; + if (mods & os::kKeySpaceModifier) + s += " Space"; + if (mods & os::kKeyWinModifier) + s += " Win"; return s; } diff --git a/examples/base64.cpp b/examples/base64.cpp index 03d988958..161aced81 100644 --- a/examples/base64.cpp +++ b/examples/base64.cpp @@ -19,7 +19,7 @@ int app_main(int argc, char* argv[]) std::string fn; bool decode = false; - for (int i=1; isurface(); os::SurfaceLock lock(surface); @@ -49,21 +50,24 @@ void draw_window(os::Window* window, p.color(gfx::rgba(255, 255, 255)); const wchar_t* lines[] = { L"English", - L"Русский язык", // Russian - L"汉语", // Simplified Chinese - L"日本語", // Japanese - L"한국어", // Korean - L"العَرَبِيَّة‎" }; // Arabic + L"Русский язык", // Russian + L"汉语", // Simplified Chinese + L"日本語", // Japanese + L"한국어", // Korean + L"العَرَبِيَّة‎" }; // Arabic MyDrawTextDelegate delegate(mousePos); gfx::Point pos(0, 0); for (auto line : lines) { std::string s = base::to_utf8(line); - os::draw_text( - backSurface.get(), font.get(), s, - gfx::rgba(255, 255, 255), gfx::ColorNone, - pos.x, pos.y, - &delegate); + os::draw_text(backSurface.get(), + font.get(), + s, + gfx::rgba(255, 255, 255), + gfx::ColorNone, + pos.x, + pos.y, + &delegate); pos.y += font->height() + 4; } @@ -115,16 +119,11 @@ int app_main(int argc, char* argv[]) queue->getEvent(ev); switch (ev.type()) { - - case os::Event::CloseWindow: - running = false; - break; + case os::Event::CloseWindow: running = false; break; case os::Event::KeyDown: switch (ev.scancode()) { - case os::kKeyEsc: - running = false; - break; + case os::kKeyEsc: running = false; break; case os::kKey1: case os::kKey2: case os::kKey3: @@ -144,9 +143,7 @@ int app_main(int argc, char* argv[]) } break; - case os::Event::ResizeWindow: - redraw = true; - break; + case os::Event::ResizeWindow: redraw = true; break; case os::Event::MouseEnter: case os::Event::MouseMove: diff --git a/examples/custom_window.cpp b/examples/custom_window.cpp index 0d24bcf16..dd055726e 100644 --- a/examples/custom_window.cpp +++ b/examples/custom_window.cpp @@ -20,8 +20,7 @@ const gfx::Color kContentHigh = gfx::rgba(50, 55, 45); const gfx::Color kContentText = gfx::rgba(105, 115, 85); const gfx::Color kContentEdge = gfx::rgba(200, 200, 100); -Hit hit_test(os::Window* window, - const gfx::Point& pos) +Hit hit_test(os::Window* window, const gfx::Point& pos) { // For a full screen window, we are always in the content area if (window->isFullscreen()) @@ -40,22 +39,30 @@ Hit hit_test(os::Window* window, // macOS cannot start the resizing actions (just the window movement) os::instance()->hasCapability(os::Capabilities::CanStartWindowResize)) { if (pos.y < kResizeBorder) { - if (pos.x < kResizeBorder) return Hit::TopLeft; - if (pos.x > rc.x2()-kResizeBorder) return Hit::TopRight; + if (pos.x < kResizeBorder) + return Hit::TopLeft; + if (pos.x > rc.x2() - kResizeBorder) + return Hit::TopRight; return Hit::Top; } - if (pos.y > rc.y2()-kResizeBorder) { - if (pos.x < kResizeBorder) return Hit::BottomLeft; - if (pos.x > rc.x2()-kResizeBorder) return Hit::BottomRight; + if (pos.y > rc.y2() - kResizeBorder) { + if (pos.x < kResizeBorder) + return Hit::BottomLeft; + if (pos.x > rc.x2() - kResizeBorder) + return Hit::BottomRight; return Hit::Bottom; } - if (pos.x < rc.w/2) return Hit::Left; + if (pos.x < rc.w / 2) + return Hit::Left; return Hit::Right; } if (pos.y <= kTitleBarSize) { - if (pos.x > rc.x2()-kButtonSize) return Hit::CloseButton; - if (pos.x > rc.x2()-kButtonSize*2) return Hit::MaximizeButton; - if (pos.x > rc.x2()-kButtonSize*3) return Hit::MinimizeButton; + if (pos.x > rc.x2() - kButtonSize) + return Hit::CloseButton; + if (pos.x > rc.x2() - kButtonSize * 2) + return Hit::MaximizeButton; + if (pos.x > rc.x2() - kButtonSize * 3) + return Hit::MinimizeButton; return Hit::TitleBar; } return Hit::Content; @@ -66,7 +73,7 @@ void draw_button(os::Surface* surface, int x, Hit button, const Hit hit) os::Paint p; gfx::Rect box(x, 0, kButtonSize, kButtonSize); - p.color(hit == button ? kTitleBarHigh: kTitleBarBase); + p.color(hit == button ? kTitleBarHigh : kTitleBarBase); p.style(os::Paint::Fill); surface->drawRect(box, p); @@ -80,13 +87,9 @@ void draw_button(os::Surface* surface, int x, Hit button, const Hit hit) p.strokeWidth(1.5f); p.antialias(true); switch (button) { - case Hit::MinimizeButton: - surface->drawRect(gfx::Rect(box.x, box.y2()-2, box.w, 1), p); - break; - case Hit::MaximizeButton: - surface->drawRect(gfx::Rect(box), p); - break; - case Hit::CloseButton: { + case Hit::MinimizeButton: surface->drawRect(gfx::Rect(box.x, box.y2() - 2, box.w, 1), p); break; + case Hit::MaximizeButton: surface->drawRect(gfx::Rect(box), p); break; + case Hit::CloseButton: { gfx::Path path; path.moveTo(box.x, box.y); path.lineTo(box.x2(), box.y2()); @@ -95,8 +98,7 @@ void draw_button(os::Surface* surface, int x, Hit button, const Hit hit) surface->drawPath(path, p); break; } - default: - break; + default: break; } } @@ -113,19 +115,18 @@ void draw_window(os::Window* window, const Hit hit) if (!window->isFullscreen()) { rc2.h = kTitleBarSize; - p.color(hit == Hit::TitleBar ? kTitleBarHigh: kTitleBarBase); - surface->drawRect(gfx::Rect(rc2).inflate(-kButtonSize*3, 0), p); + p.color(hit == Hit::TitleBar ? kTitleBarHigh : kTitleBarBase); + surface->drawRect(gfx::Rect(rc2).inflate(-kButtonSize * 3, 0), p); - rc2.y += kTitleBarSize/2 - 10; + rc2.y += kTitleBarSize / 2 - 10; p.color(kTitleBarText); - os::draw_text(surface, nullptr, "Custom Window", - rc2.center(), &p, os::TextAlign::Center); + os::draw_text(surface, nullptr, "Custom Window", rc2.center(), &p, os::TextAlign::Center); // Draw buttons - draw_button(surface, rc.x2()-kButtonSize, Hit::CloseButton, hit); - draw_button(surface, rc.x2()-kButtonSize*2, Hit::MaximizeButton, hit); - draw_button(surface, rc.x2()-kButtonSize*3, Hit::MinimizeButton, hit); + draw_button(surface, rc.x2() - kButtonSize, Hit::CloseButton, hit); + draw_button(surface, rc.x2() - kButtonSize * 2, Hit::MaximizeButton, hit); + draw_button(surface, rc.x2() - kButtonSize * 3, Hit::MinimizeButton, hit); // Client area rc2 = rc; @@ -134,7 +135,7 @@ void draw_window(os::Window* window, const Hit hit) } // Draw client area - p.color(hit == Hit::Content ? kContentHigh: kContentBase); + p.color(hit == Hit::Content ? kContentHigh : kContentBase); surface->drawRect(rc2, p); p.style(os::Paint::Style::Stroke); @@ -143,14 +144,17 @@ void draw_window(os::Window* window, const Hit hit) p.style(os::Paint::Style::Fill); p.color(kContentText); - os::draw_text(surface, nullptr, "Content Rect", - rc2.center(), &p, os::TextAlign::Center); + os::draw_text(surface, nullptr, "Content Rect", rc2.center(), &p, os::TextAlign::Center); if (window->isFullscreen()) { auto pos = rc2.center(); pos.y += 24; - os::draw_text(surface, nullptr, "(F key or F11 to exit full screen)", - pos, &p, os::TextAlign::Center); + os::draw_text(surface, + nullptr, + "(F key or F11 to exit full screen)", + pos, + &p, + os::TextAlign::Center); } if (window->isVisible()) @@ -159,9 +163,7 @@ void draw_window(os::Window* window, const Hit hit) window->setVisible(true); } -bool update_hit(os::Window* window, - const os::Event& ev, - Hit& hit) +bool update_hit(os::Window* window, const os::Event& ev, Hit& hit) { Hit newHit = hit_test(window, ev.position()); if (newHit != hit) { @@ -185,29 +187,26 @@ os::WindowRef create_window() return window; } -void handle_mouse_move(os::Window* window, - const Hit hit) +void handle_mouse_move(os::Window* window, const Hit hit) { os::NativeCursor cursor = os::NativeCursor::Arrow; switch (hit) { - case Hit::Content: cursor = os::NativeCursor::Arrow; break; - case Hit::TitleBar: cursor = os::NativeCursor::Move; break; + case Hit::Content: cursor = os::NativeCursor::Arrow; break; + case Hit::TitleBar: cursor = os::NativeCursor::Move; break; case Hit::TopLeft: cursor = os::NativeCursor::SizeNW; break; - case Hit::Top: cursor = os::NativeCursor::SizeN; break; + case Hit::Top: cursor = os::NativeCursor::SizeN; break; case Hit::TopRight: cursor = os::NativeCursor::SizeNE; break; - case Hit::Left: cursor = os::NativeCursor::SizeW; break; - case Hit::Right: cursor = os::NativeCursor::SizeE; break; + case Hit::Left: cursor = os::NativeCursor::SizeW; break; + case Hit::Right: cursor = os::NativeCursor::SizeE; break; case Hit::BottomLeft: cursor = os::NativeCursor::SizeSW; break; - case Hit::Bottom: cursor = os::NativeCursor::SizeS; break; + case Hit::Bottom: cursor = os::NativeCursor::SizeS; break; case Hit::BottomRight: cursor = os::NativeCursor::SizeSE; break; - default: break; + default: break; } window->setCursor(cursor); } -bool handle_mouse_down(os::Window* window, - const os::Event& ev, - const Hit hit) +bool handle_mouse_down(os::Window* window, const os::Event& ev, const Hit hit) { os::NativeCursor cursor = os::NativeCursor::Arrow; os::WindowAction action = os::WindowAction::Move; @@ -215,12 +214,12 @@ bool handle_mouse_down(os::Window* window, case Hit::Content: return true; case Hit::TitleBar: action = os::WindowAction::Move; break; case Hit::TopLeft: action = os::WindowAction::ResizeFromTopLeft; break; - case Hit::Top: action = os::WindowAction::ResizeFromTop; break; + case Hit::Top: action = os::WindowAction::ResizeFromTop; break; case Hit::TopRight: action = os::WindowAction::ResizeFromTopRight; break; - case Hit::Left: action = os::WindowAction::ResizeFromLeft; break; - case Hit::Right: action = os::WindowAction::ResizeFromRight; break; + case Hit::Left: action = os::WindowAction::ResizeFromLeft; break; + case Hit::Right: action = os::WindowAction::ResizeFromRight; break; case Hit::BottomLeft: action = os::WindowAction::ResizeFromBottomLeft; break; - case Hit::Bottom: action = os::WindowAction::ResizeFromBottom; break; + case Hit::Bottom: action = os::WindowAction::ResizeFromBottom; break; case Hit::BottomRight: action = os::WindowAction::ResizeFromBottomRight; break; case Hit::MinimizeButton: window->minimize(); return true; case Hit::MaximizeButton: window->maximize(); return true; @@ -257,23 +256,15 @@ int app_main(int argc, char* argv[]) queue->getEvent(ev); switch (ev.type()) { - case os::Event::CloseApp: - case os::Event::CloseWindow: - running = false; - break; + case os::Event::CloseWindow: running = false; break; case os::Event::KeyDown: switch (ev.scancode()) { - case os::kKeyEsc: - running = false; - break; + case os::kKeyEsc: running = false; break; case os::kKeyF: - case os::kKeyF11: - window->setFullscreen(!window->isFullscreen()); - break; - default: - break; + case os::kKeyF11: window->setFullscreen(!window->isFullscreen()); break; + default: break; } break; @@ -289,12 +280,9 @@ int app_main(int argc, char* argv[]) running = false; break; - case os::Event::MouseLeave: - redraw = update_hit(window.get(), ev, hit); - break; + case os::Event::MouseLeave: redraw = update_hit(window.get(), ev, hit); break; - default: - break; + default: break; } } diff --git a/examples/drag_and_drop.cpp b/examples/drag_and_drop.cpp index a6cac2528..8c3f54356 100644 --- a/examples/drag_and_drop.cpp +++ b/examples/drag_and_drop.cpp @@ -27,7 +27,8 @@ static void redraw_window(os::Window* window); class DragTarget : public os::DragTarget { public: - void dragEnter(os::DragEvent& ev) override { + void dragEnter(os::DragEvent& ev) override + { if (!windowData.dropZone.contains(ev.position()) || !ev.sourceSupports(os::DropOperation::Copy)) { ev.dropResult(os::DropOperation::None); @@ -43,20 +44,23 @@ class DragTarget : public os::DragTarget { redraw_window(ev.target()); } - void dragLeave(os::DragEvent& ev) override { + void dragLeave(os::DragEvent& ev) override + { windowData.dragEnter = false; windowData.dragLeave = true; windowData.dragPosition = ev.position(); redraw_window(ev.target()); } - void drag(os::DragEvent& ev) override { + void drag(os::DragEvent& ev) override + { ++windowData.drag; windowData.dragPosition = ev.position(); redraw_window(ev.target()); } - void drop(os::DragEvent& ev) override { + void drop(os::DragEvent& ev) override + { windowData.dragEnter = false; windowData.dragLeave = false; windowData.dragPosition = { 0, 0 }; @@ -98,7 +102,11 @@ static void redraw_window(os::Window* window) char buf[2049]; int y = 12; - std::snprintf(buf, sizeof(buf), "Drag Position = [%d, %d]", windowData.dragPosition.x, windowData.dragPosition.y); + std::snprintf(buf, + sizeof(buf), + "Drag Position = [%d, %d]", + windowData.dragPosition.x, + windowData.dragPosition.y); os::draw_text(s, nullptr, buf, gfx::Point(0, y), &paint); y += 12; std::snprintf(buf, sizeof(buf), "Drag Enter = %s", windowData.dragEnter ? "true" : "false"); @@ -155,7 +163,12 @@ static void redraw_window(os::Window* window) paint.color(textColor); paint.style(os::Paint::Style::Fill); - os::draw_text(s, nullptr, "Drop here!", windowData.dropZone.center(), &paint, os::TextAlign::Center); + os::draw_text(s, + nullptr, + "Drop here!", + windowData.dropZone.center(), + &paint, + os::TextAlign::Center); if (window->isVisible()) window->invalidateRegion(gfx::Region(rc)); @@ -169,7 +182,7 @@ static os::WindowRef create_window(os::DragTarget& dragTarget) os::WindowSpec spec; spec.titled(true); spec.position(os::WindowSpec::Position::Frame); - spec.frame(screen->workarea()/2); + spec.frame(screen->workarea() / 2); spec.screen(screen); spec.scale(2); @@ -178,7 +191,7 @@ static os::WindowRef create_window(os::DragTarget& dragTarget) newWindow->setTitle("Drag & Drop"); newWindow->setDragTarget(&dragTarget); - windowData.dropZone = gfx::Rect(spec.frame().w-64-12, 12, 64, 64); + windowData.dropZone = gfx::Rect(spec.frame().w - 64 - 12, 12, 64, 64); redraw_window(newWindow.get()); return newWindow; } @@ -203,23 +216,16 @@ int app_main(int argc, char* argv[]) queue->getEvent(ev); switch (ev.type()) { - case os::Event::KeyDown: switch (ev.scancode()) { - case os::kKeyEsc: - running = false; - break; + case os::kKeyEsc: running = false; break; } break; case os::Event::CloseApp: - case os::Event::CloseWindow: - running = false; - break; + case os::Event::CloseWindow: running = false; break; - case os::Event::ResizeWindow: - redraw_window(ev.window().get()); - break; + case os::Event::ResizeWindow: redraw_window(ev.window().get()); break; default: // Do nothing diff --git a/examples/floating_window.cpp b/examples/floating_window.cpp index 5aed1d014..3deb73a65 100644 --- a/examples/floating_window.cpp +++ b/examples/floating_window.cpp @@ -8,9 +8,8 @@ class CustomWindow { public: - void create(const std::string& title, - int w, int h, - os::Window* parent = nullptr) { + void create(const std::string& title, int w, int h, os::Window* parent = nullptr) + { os::WindowSpec spec; if (parent) { @@ -19,7 +18,7 @@ class CustomWindow { spec.minimizable(false); gfx::Rect rc = parent->frame(); - spec.frame(gfx::Rect(rc.x2()-w/2, rc.y+rc.h/2-h/2, w, h)); + spec.frame(gfx::Rect(rc.x2() - w / 2, rc.y + rc.h / 2 - h / 2, w, h)); spec.position(os::WindowSpec::Position::Frame); } else { @@ -34,19 +33,14 @@ class CustomWindow { redraw(); } - void close() { - m_nativeWindow = nullptr; - } + void close() { m_nativeWindow = nullptr; } - void focus() { - m_nativeWindow->activate(); - } + void focus() { m_nativeWindow->activate(); } - bool isVisible() const { - return (m_nativeWindow && m_nativeWindow->isVisible()); - } + bool isVisible() const { return (m_nativeWindow && m_nativeWindow->isVisible()); } - void redraw() { + void redraw() + { auto rc = m_nativeWindow->surface()->bounds(); onRedraw(m_nativeWindow->surface(), rc); @@ -56,37 +50,30 @@ class CustomWindow { m_nativeWindow->setVisible(true); } - virtual bool isFloating() const { - return false; - } + virtual bool isFloating() const { return false; } - virtual bool handleEvent(os::Event& ev) { + virtual bool handleEvent(os::Event& ev) + { switch (ev.type()) { + case os::Event::CloseWindow: return false; - case os::Event::CloseWindow: - return false; - - case os::Event::ResizeWindow: - redraw(); - break; + case os::Event::ResizeWindow: redraw(); break; case os::Event::KeyDown: if (ev.scancode() == os::kKeyEsc) return false; - else if (ev.scancode() == os::kKeyEnter || - ev.scancode() == os::kKeyEnterPad) + else if (ev.scancode() == os::kKeyEnter || ev.scancode() == os::kKeyEnterPad) onEnterKey(); break; - default: - break; + default: break; } return true; } protected: - virtual void onRedraw(os::Surface* surface, const gfx::Rect& rc) { } - virtual void onEnterKey() { } + virtual void onRedraw(os::Surface* surface, const gfx::Rect& rc) {} + virtual void onEnterKey() {} os::WindowRef nativeWindow() const { return m_nativeWindow; } @@ -96,38 +83,37 @@ class CustomWindow { class FloatingWindow : public CustomWindow { public: - void recreate(os::Window* parent) { - create("Floating", 200, 200, parent); - } + void recreate(os::Window* parent) { create("Floating", 200, 200, parent); } - bool isFloating() const override { - return true; - } + bool isFloating() const override { return true; } private: - void onRedraw(os::Surface* surface, const gfx::Rect& rc) override { + void onRedraw(os::Surface* surface, const gfx::Rect& rc) override + { os::Paint paint; paint.color(gfx::rgba(200, 150, 150)); surface->drawRect(rc, paint); } - bool handleEvent(os::Event& ev) override { + bool handleEvent(os::Event& ev) override + { if (!CustomWindow::handleEvent(ev)) close(); return true; } - }; class MainWindow : public CustomWindow { public: - MainWindow() { + MainWindow() + { create("Main", 500, 400); createFloating(); } private: - void onRedraw(os::Surface* surface, const gfx::Rect& rc) override { + void onRedraw(os::Surface* surface, const gfx::Rect& rc) override + { os::Paint p; p.color(gfx::rgba(150, 150, 200)); surface->drawRect(rc, p); @@ -135,15 +121,19 @@ class MainWindow : public CustomWindow { p.color(gfx::rgba(50, 50, 100)); gfx::Point pos = rc.center(); - os::draw_text(surface, nullptr, "Press ENTER key to hide/show the floating window", - pos, &p, os::TextAlign::Center); + os::draw_text(surface, + nullptr, + "Press ENTER key to hide/show the floating window", + pos, + &p, + os::TextAlign::Center); pos.y += 24; - os::draw_text(surface, nullptr, "Press ESC to quit", - pos, &p, os::TextAlign::Center); + os::draw_text(surface, nullptr, "Press ESC to quit", pos, &p, os::TextAlign::Center); } - void onEnterKey() override { + void onEnterKey() override + { if (m_floating.isVisible()) m_floating.close(); else { @@ -151,7 +141,8 @@ class MainWindow : public CustomWindow { } } - void createFloating() { + void createFloating() + { m_floating.recreate(nativeWindow().get()); // Focus the main window (so the floating window is not focused by @@ -166,10 +157,9 @@ int app_main(int argc, char* argv[]) { auto system = os::make_system(); system->setAppMode(os::AppMode::GUI); - system->handleWindowResize = - [](os::Window* window){ - window->userData()->redraw(); - }; + system->handleWindowResize = [](os::Window* window) { + window->userData()->redraw(); + }; MainWindow mainWindow; diff --git a/examples/hello_laf.cpp b/examples/hello_laf.cpp index b938c0eb1..52e615f3c 100644 --- a/examples/hello_laf.cpp +++ b/examples/hello_laf.cpp @@ -17,16 +17,22 @@ void draw_window(os::Window* window) p.style(os::Paint::Fill); surface->drawRect(rc, p); - p.color(gfx::rgba(255, 0, 0)); surface->drawLine(0 , 0, rc.w, rc.h, p); - p.color(gfx::rgba(0, 128, 0)); surface->drawLine(rc.w/2, 0, rc.w/2, rc.h, p); - p.color(gfx::rgba(0, 0, 255)); surface->drawLine(rc.w , 0, 0, rc.h, p); + p.color(gfx::rgba(255, 0, 0)); + surface->drawLine(0, 0, rc.w, rc.h, p); + p.color(gfx::rgba(0, 128, 0)); + surface->drawLine(rc.w / 2, 0, rc.w / 2, rc.h, p); + p.color(gfx::rgba(0, 0, 255)); + surface->drawLine(rc.w, 0, 0, rc.h, p); p.color(gfx::rgba(255, 255, 255)); - os::draw_text(surface, nullptr, "Hello World", rc.center(), - &p, os::TextAlign::Center); + os::draw_text(surface, nullptr, "Hello World", rc.center(), &p, os::TextAlign::Center); if (window->gpuAcceleration()) - os::draw_text(surface, nullptr, "(GPU)", rc.center()+gfx::Point(0, 24), - &p, os::TextAlign::Center); + os::draw_text(surface, + nullptr, + "(GPU)", + rc.center() + gfx::Point(0, 24), + &p, + os::TextAlign::Center); // Invalidates the whole window to show it on the screen. if (window->isVisible()) @@ -83,17 +89,12 @@ int app_main(int argc, char* argv[]) queue->getEvent(ev); switch (ev.type()) { - case os::Event::CloseApp: - case os::Event::CloseWindow: - running = false; - break; + case os::Event::CloseWindow: running = false; break; case os::Event::KeyDown: switch (ev.scancode()) { - case os::kKeyEsc: - running = false; - break; + case os::kKeyEsc: running = false; break; case os::kKeyG: window->setGpuAcceleration(!window->gpuAcceleration()); @@ -116,9 +117,7 @@ int app_main(int argc, char* argv[]) break; case os::kKeyF: - case os::kKeyF11: - window->setFullscreen(!window->isFullscreen()); - break; + case os::kKeyF11: window->setFullscreen(!window->isFullscreen()); break; default: // Do nothing @@ -126,9 +125,7 @@ int app_main(int argc, char* argv[]) } break; - case os::Event::ResizeWindow: - redraw = true; - break; + case os::Event::ResizeWindow: redraw = true; break; default: // Do nothing diff --git a/examples/listfonts.cpp b/examples/listfonts.cpp index 2b5fc2ff1..ae4f8cf11 100644 --- a/examples/listfonts.cpp +++ b/examples/listfonts.cpp @@ -12,16 +12,16 @@ static const char* to_str(os::FontStyle::Weight weight) { switch (weight) { - case os::FontStyle::Weight::Invisible: return "Invisible"; - case os::FontStyle::Weight::Thin: return "Thin"; + case os::FontStyle::Weight::Invisible: return "Invisible"; + case os::FontStyle::Weight::Thin: return "Thin"; case os::FontStyle::Weight::ExtraLight: return "ExtraLight"; - case os::FontStyle::Weight::Light: return "Light"; - case os::FontStyle::Weight::Normal: return "Normal"; - case os::FontStyle::Weight::Medium: return "Medium"; - case os::FontStyle::Weight::SemiBold: return "SemiBold"; - case os::FontStyle::Weight::Bold: return "Bold"; - case os::FontStyle::Weight::ExtraBold: return "ExtraBold"; - case os::FontStyle::Weight::Black: return "Black"; + case os::FontStyle::Weight::Light: return "Light"; + case os::FontStyle::Weight::Normal: return "Normal"; + case os::FontStyle::Weight::Medium: return "Medium"; + case os::FontStyle::Weight::SemiBold: return "SemiBold"; + case os::FontStyle::Weight::Bold: return "Bold"; + case os::FontStyle::Weight::ExtraBold: return "ExtraBold"; + case os::FontStyle::Weight::Black: return "Black"; case os::FontStyle::Weight::ExtraBlack: return "ExtraBlack"; } return ""; @@ -32,13 +32,13 @@ static const char* to_str(os::FontStyle::Width width) switch (width) { case os::FontStyle::Width::UltraCondensed: return "UltraCondensed"; case os::FontStyle::Width::ExtraCondensed: return "ExtraCondensed"; - case os::FontStyle::Width::Condensed: return "Condensed"; - case os::FontStyle::Width::SemiCondensed: return "SemiCondensed"; - case os::FontStyle::Width::Normal: return "Normal"; - case os::FontStyle::Width::SemiExpanded: return "SemiExpanded"; - case os::FontStyle::Width::Expanded: return "Expanded"; - case os::FontStyle::Width::ExtraExpanded: return "ExtraExpanded"; - case os::FontStyle::Width::UltraExpanded: return "UltraExpanded"; + case os::FontStyle::Width::Condensed: return "Condensed"; + case os::FontStyle::Width::SemiCondensed: return "SemiCondensed"; + case os::FontStyle::Width::Normal: return "Normal"; + case os::FontStyle::Width::SemiExpanded: return "SemiExpanded"; + case os::FontStyle::Width::Expanded: return "Expanded"; + case os::FontStyle::Width::ExtraExpanded: return "ExtraExpanded"; + case os::FontStyle::Width::UltraExpanded: return "UltraExpanded"; } return ""; } @@ -47,7 +47,7 @@ static const char* to_str(os::FontStyle::Slant slant) { switch (slant) { case os::FontStyle::Slant::Upright: return "Upright"; - case os::FontStyle::Slant::Italic: return "Italic"; + case os::FontStyle::Slant::Italic: return "Italic"; case os::FontStyle::Slant::Oblique: return "Oblique"; } return ""; @@ -55,7 +55,7 @@ static const char* to_str(os::FontStyle::Slant slant) static void print_set(const std::string& name, os::FontStyleSet* set) { - for (int j=0; jcount(); ++j) { + for (int j = 0; j < set->count(); ++j) { os::FontStyle style; std::string styleName; set->getStyle(j, style, styleName); @@ -79,7 +79,7 @@ int app_main(int argc, char* argv[]) } if (argc > 1) { - for (int i=1; imatchFamily(name); @@ -93,7 +93,7 @@ int app_main(int argc, char* argv[]) // Print all font families else { const int n = fm->countFamilies(); - for (int i=0; ifamilyName(i); std::printf("%s\n", name.c_str()); diff --git a/examples/listscreens.cpp b/examples/listscreens.cpp index 93ae1aecc..97c541f06 100644 --- a/examples/listscreens.cpp +++ b/examples/listscreens.cpp @@ -21,9 +21,16 @@ int app_main(int argc, char* argv[]) auto rc = screen->bounds(); auto wa = screen->workarea(); std::printf("%sscreen=%d bounds=(%d %d %d %d) workarea=(%d %d %d %d)\n", - screen->isMainScreen() ? "main ": "", - i++, rc.x, rc.y, rc.w, rc.h, - wa.x, wa.y, wa.w, wa.h); + screen->isMainScreen() ? "main " : "", + i++, + rc.x, + rc.y, + rc.w, + rc.h, + wa.x, + wa.y, + wa.w, + wa.h); } return 0; } diff --git a/examples/multiple_windows.cpp b/examples/multiple_windows.cpp index b56f6034a..4663efb36 100644 --- a/examples/multiple_windows.cpp +++ b/examples/multiple_windows.cpp @@ -40,14 +40,12 @@ static void redraw_window(os::Window* window) int y = 12; gfx::Rect rc = window->frame(); - std::snprintf(buf, sizeof(buf), - "Frame = (%d %d %d %d)", rc.x, rc.y, rc.w, rc.h); + std::snprintf(buf, sizeof(buf), "Frame = (%d %d %d %d)", rc.x, rc.y, rc.w, rc.h); os::draw_text(s, nullptr, buf, gfx::Point(0, y), &paint); y += 12; rc = window->contentRect(); - std::snprintf(buf, sizeof(buf), - "Content Rect = (%d %d %d %d)", rc.x, rc.y, rc.w, rc.h); + std::snprintf(buf, sizeof(buf), "Content Rect = (%d %d %d %d)", rc.x, rc.y, rc.w, rc.h); os::draw_text(s, nullptr, buf, gfx::Point(0, y), &paint); y += 12; @@ -60,8 +58,7 @@ static void redraw_window(os::Window* window) s->drawRect(window->bounds(), paint); } -static os::WindowRef add_window(const std::string& title, - const os::WindowSpec& spec) +static os::WindowRef add_window(const std::string& title, const os::WindowSpec& spec) { os::WindowRef newWindow = os::instance()->makeWindow(spec); newWindow->setCursor(os::NativeCursor::Arrow); @@ -76,15 +73,13 @@ static os::WindowRef add_window(const std::string& title, static void check_show_all_windows() { // If all windows are hidden, show then again - auto hidden = std::count_if(windows.begin(), windows.end(), - [](os::WindowRef window){ - return !window->isVisible(); - }); + auto hidden = std::count_if(windows.begin(), windows.end(), [](os::WindowRef window) { + return !window->isVisible(); + }); if (hidden == windows.size()) { - std::for_each(windows.begin(), windows.end(), - [](os::WindowRef window){ - window->setVisible(true); - }); + std::for_each(windows.begin(), windows.end(), [](os::WindowRef window) { + window->setVisible(true); + }); } } @@ -122,8 +117,8 @@ int app_main(int argc, char* argv[]) for (auto& p : pos) { os::WindowSpec s = spec; gfx::Rect frame = s.frame(); - frame.x += frame.w*p.x; - frame.y += frame.h*p.y; + frame.x += frame.w * p.x; + frame.y += frame.h * p.y; frame.w /= 2; frame.h /= 2; s.frame(frame); @@ -140,14 +135,11 @@ int app_main(int argc, char* argv[]) queue->getEvent(ev); switch (ev.type()) { - case os::Event::CloseApp: windows.clear(); // Close all windows break; - case os::Event::CloseWindow: - destroy_window(ev.window()); - break; + case os::Event::CloseWindow: destroy_window(ev.window()); break; case os::Event::ResizeWindow: redraw_window(ev.window().get()); @@ -156,21 +148,15 @@ int app_main(int argc, char* argv[]) case os::Event::KeyDown: switch (ev.scancode()) { + case os::kKeyQ: windows.clear(); break; - case os::kKeyQ: - windows.clear(); - break; - - case os::kKeyEsc: - destroy_window(ev.window()); - break; + case os::kKeyEsc: destroy_window(ev.window()); break; // Switch between Arrow/Move cursor in this specific window case os::kKeyA: - ev.window()->setCursor( - ev.window()->nativeCursor() == os::NativeCursor::Arrow ? - os::NativeCursor::Move: - os::NativeCursor::Arrow); + ev.window()->setCursor(ev.window()->nativeCursor() == os::NativeCursor::Arrow ? + os::NativeCursor::Move : + os::NativeCursor::Arrow); break; case os::kKeyH: @@ -216,14 +202,14 @@ int app_main(int argc, char* argv[]) case os::kKeyLeft: case os::kKeyUp: case os::kKeyRight: - case os::kKeyDown: { + case os::kKeyDown: { gfx::Rect rc = ev.window()->frame(); switch (ev.scancode()) { case os::kKeyLeft: rc.x -= rc.w; break; case os::kKeyUp: rc.y -= rc.h; break; case os::kKeyRight: rc.x += rc.w; break; case os::kKeyDown: rc.y += rc.h; break; - default: break; + default: break; } ev.window()->setFrame(rc); @@ -234,8 +220,7 @@ int app_main(int argc, char* argv[]) break; } - default: - break; + default: break; } break; diff --git a/examples/panviewport.cpp b/examples/panviewport.cpp index 8d37f04ed..80bcff4b4 100644 --- a/examples/panviewport.cpp +++ b/examples/panviewport.cpp @@ -20,29 +20,26 @@ class PanWindow { : m_window(system->makeWindow(800, 600)) , m_scroll(0.0, 0.0) , m_zoom(1.0) - , m_hasCapture(false) { + , m_hasCapture(false) + { m_window->setCursor(os::NativeCursor::Arrow); m_window->setTitle("Pan Viewport"); repaint(); m_window->setVisible(true); } - bool processEvent(const os::Event& ev) { + bool processEvent(const os::Event& ev) + { switch (ev.type()) { + case os::Event::CloseWindow: return false; - case os::Event::CloseWindow: - return false; + case os::Event::ResizeWindow: repaint(); break; - case os::Event::ResizeWindow: - repaint(); - break; - - case os::Event::MouseEnter: break; - case os::Event::MouseLeave: break; + case os::Event::MouseEnter: break; + case os::Event::MouseLeave: break; case os::Event::MouseMove: if (m_hasCapture) { - m_scroll = m_captureScroll - + gfx::PointF(ev.position() - m_capturePos); + m_scroll = m_captureScroll + gfx::PointF(ev.position() - m_capturePos); repaint(); } break; @@ -75,34 +72,32 @@ class PanWindow { case os::Event::MouseWheel: if (ev.modifiers() & os::kKeyCtrlModifier) { int z = (ev.wheelDelta().x + ev.wheelDelta().y); - setZoom(gfx::PointF(ev.position()), - m_zoom - z/10.0); + setZoom(gfx::PointF(ev.position()), m_zoom - z / 10.0); } else if (ev.preciseWheel()) { // TODO we have plans to change the sign of wheelDelta() when preciseWheel() is true m_scroll += gfx::PointF(-ev.wheelDelta()); } else { - m_scroll += gfx::PointF(-ev.wheelDelta().x*m_window->width()/32, - -ev.wheelDelta().y*m_window->height()/32); + m_scroll += gfx::PointF(-ev.wheelDelta().x * m_window->width() / 32, + -ev.wheelDelta().y * m_window->height() / 32); } repaint(); break; case os::Event::TouchMagnify: - setZoom(gfx::PointF(ev.position()), - m_zoom + m_zoom * ev.magnification()); + setZoom(gfx::PointF(ev.position()), m_zoom + m_zoom * ev.magnification()); break; case os::Event::KeyDown: if (ev.scancode() == os::kKeyEsc) return false; // Toggle full-screen - else if (// F11 for Windows/Linux - (ev.scancode() == os::kKeyF11) || - // Ctrl+Command+F for macOS - (ev.scancode() == os::kKeyF && - ev.modifiers() == (os::kKeyCmdModifier | os::kKeyCtrlModifier))) { + else if ( // F11 for Windows/Linux + (ev.scancode() == os::kKeyF11) || + // Ctrl+Command+F for macOS + (ev.scancode() == os::kKeyF && + ev.modifiers() == (os::kKeyCmdModifier | os::kKeyCtrlModifier))) { m_window->setFullscreen(!m_window->isFullscreen()); } break; @@ -114,7 +109,8 @@ class PanWindow { return true; } - void repaint() { + void repaint() + { os::Surface* surface = m_window->surface(); os::SurfaceLock lock(surface); const gfx::Rect rc(surface->bounds()); @@ -135,20 +131,22 @@ class PanWindow { rc2.offset(m_scroll); surface->drawRect(rc2, p); - for (int i=1; i<8; ++i) { + for (int i = 1; i < 8; ++i) { int v = i * rc2.w / 8; - surface->drawLine(int(rc2.x + v), int(rc2.y), - int(rc2.x + v), int(rc2.y + rc2.h), p); + surface->drawLine(int(rc2.x + v), int(rc2.y), int(rc2.x + v), int(rc2.y + rc2.h), p); v = i * rc2.h / 8; - surface->drawLine(int(rc2.x), int(rc2.y + v), - int(rc2.x + rc2.w), int(rc2.y + v), p); + surface->drawLine(int(rc2.x), int(rc2.y + v), int(rc2.x + rc2.w), int(rc2.y + v), p); } } { std::vector buf(256); - std::snprintf(buf.data(), buf.size(), - "Scroll=%.2f %.2f Zoom=%.2f", m_scroll.x, m_scroll.y, m_zoom); + std::snprintf(buf.data(), + buf.size(), + "Scroll=%.2f %.2f Zoom=%.2f", + m_scroll.x, + m_scroll.y, + m_zoom); p.style(os::Paint::Fill); os::draw_text(surface, nullptr, &buf[0], gfx::Point(12, 12), &p); } @@ -158,7 +156,8 @@ class PanWindow { } private: - void setZoom(const gfx::PointF& mousePos, double newZoom) { + void setZoom(const gfx::PointF& mousePos, double newZoom) + { double oldZoom = m_zoom; m_zoom = std::clamp(newZoom, 0.01, 10.0); @@ -178,10 +177,7 @@ class PanWindow { repaint(); } - gfx::Point center() const { - return gfx::Point(m_window->width()/2, - m_window->height()/2); - } + gfx::Point center() const { return gfx::Point(m_window->width() / 2, m_window->height() / 2); } os::WindowRef m_window; gfx::PointF m_scroll; @@ -200,9 +196,7 @@ int app_main(int argc, char* argv[]) PanWindow window(system.get()); - system->handleWindowResize = [&window](os::Window* win){ - window.repaint(); - }; + system->handleWindowResize = [&window](os::Window* win) { window.repaint(); }; system->finishLaunching(); system->activateApp(); diff --git a/examples/shader.cpp b/examples/shader.cpp index 56193cd57..13b5c98b7 100644 --- a/examples/shader.cpp +++ b/examples/shader.cpp @@ -51,7 +51,8 @@ half4 main(vec2 fragcoord) { class ShaderWindow { public: ShaderWindow(os::System* system) - : m_builder(SkRuntimeEffect::MakeForShader(SkString(shaderCode)).effect) { + : m_builder(SkRuntimeEffect::MakeForShader(SkString(shaderCode)).effect) + { m_window = system->makeWindow(256, 256); m_window->setCursor(os::NativeCursor::Arrow); m_window->setTitle("Shader"); @@ -60,15 +61,12 @@ class ShaderWindow { m_window->setVisible(true); } - bool processEvent(const os::Event& ev) { + bool processEvent(const os::Event& ev) + { switch (ev.type()) { + case os::Event::CloseWindow: return false; - case os::Event::CloseWindow: - return false; - - case os::Event::ResizeWindow: - repaint(); - break; + case os::Event::ResizeWindow: repaint(); break; case os::Event::KeyDown: if (ev.scancode() == os::kKeyEsc) @@ -85,7 +83,8 @@ class ShaderWindow { return true; } - void repaint() { + void repaint() + { os::Surface* surface = m_window->surface(); os::SurfaceLock lock(surface); @@ -95,8 +94,7 @@ class ShaderWindow { if (m_window->gpuAcceleration()) { os::Paint p; p.color(gfx::rgba(0, 0, 0)); - os::draw_text(surface, nullptr, "GPU", gfx::Point(12, 12), - &p, os::TextAlign::Center); + os::draw_text(surface, nullptr, "GPU", gfx::Point(12, 12), &p, os::TextAlign::Center); } m_window->invalidate(); @@ -104,13 +102,11 @@ class ShaderWindow { } private: - - void skiaPaint(SkCanvas* canvas) { + void skiaPaint(SkCanvas* canvas) + { SkImageInfo ii = canvas->imageInfo(); - m_builder.uniform("iResolution") = SkV3{float(ii.width()), - float(ii.height()), 0.0f}; - m_builder.uniform("iTime") = - float((base::current_tick() - startTick) / 1000.0f); + m_builder.uniform("iResolution") = SkV3{ float(ii.width()), float(ii.height()), 0.0f }; + m_builder.uniform("iTime") = float((base::current_tick() - startTick) / 1000.0f); SkPaint p; p.setShader(m_builder.makeShader()); @@ -128,9 +124,7 @@ int app_main(int argc, char* argv[]) ShaderWindow window(system.get()); - system->handleWindowResize = [&window](os::Window* win){ - window.repaint(); - }; + system->handleWindowResize = [&window](os::Window* win) { window.repaint(); }; system->finishLaunching(); system->activateApp(); @@ -145,8 +139,7 @@ int app_main(int argc, char* argv[]) os::Event ev; ASSERT(paintDelay >= 0.0); - const double waitSecs = - (base::current_tick() - t) / 1000.0 * 60.0 + paintDelay; + const double waitSecs = (base::current_tick() - t) / 1000.0 * 60.0 + paintDelay; queue->getEvent(ev, waitSecs); if (!window.processEvent(ev)) diff --git a/examples/show_platform.cpp b/examples/show_platform.cpp index 3c17f2512..fadbbeafb 100644 --- a/examples/show_platform.cpp +++ b/examples/show_platform.cpp @@ -10,22 +10,17 @@ int app_main(int argc, char* argv[]) { - base::Platform p = base::get_platform(); + base::Platform p = base::get_platform(); switch (p.os) { #if LAF_WINDOWS case base::Platform::OS::Windows: - std::printf( - "Windows v%s%s%s", - p.osVer.str().c_str(), - p.isWow64 ? " WoW64": "", - (p.wineVer ? (std::string(" WINE v") + p.wineVer).c_str(): "")); + std::printf("Windows v%s%s%s", + p.osVer.str().c_str(), + p.isWow64 ? " WoW64" : "", + (p.wineVer ? (std::string(" WINE v") + p.wineVer).c_str() : "")); break; #endif - case base::Platform::OS::macOS: - std::printf( - "macOS v%s", - p.osVer.str().c_str()); - break; + case base::Platform::OS::macOS: std::printf("macOS v%s", p.osVer.str().c_str()); break; #if LAF_LINUX case base::Platform::OS::Linux: std::printf("Linux %s", p.distroName.c_str()); @@ -35,15 +30,9 @@ int app_main(int argc, char* argv[]) #endif } switch (p.arch) { - case base::Platform::Arch::x86: - std::printf(" (x86)"); - break; - case base::Platform::Arch::x64: - std::printf(" (x64)"); - break; - case base::Platform::Arch::arm64: - std::printf(" (arm64)"); - break; + case base::Platform::Arch::x86: std::printf(" (x86)"); break; + case base::Platform::Arch::x64: std::printf(" (x64)"); break; + case base::Platform::Arch::arm64: std::printf(" (arm64)"); break; } std::printf("\n"); return 0; diff --git a/ft/algorithm.h b/ft/algorithm.h index 133476bab..b76a31398 100644 --- a/ft/algorithm.h +++ b/ft/algorithm.h @@ -17,150 +17,143 @@ namespace ft { - template - class DefaultShaper { - public: - using Glyph = typename FaceFT::Glyph; - - DefaultShaper(FaceFT& face, - const std::string& str) - : m_face(face) - , m_begin(str.begin()) - , m_decode(str) { - } +template +class DefaultShaper { +public: + using Glyph = typename FaceFT::Glyph; + + DefaultShaper(FaceFT& face, const std::string& str) + : m_face(face) + , m_begin(str.begin()) + , m_decode(str) + { + } - int next() { - m_pos = m_decode.pos(); - return (m_char = m_decode.next()); - } + int next() + { + m_pos = m_decode.pos(); + return (m_char = m_decode.next()); + } - int unicodeChar() const { - return m_char; - } + int unicodeChar() const { return m_char; } - int charIndex() const { - return m_pos - m_begin; - } + int charIndex() const { return m_pos - m_begin; } - unsigned int glyphIndex() { - return m_face.cache().getGlyphIndex(m_face, unicodeChar()); - } + unsigned int glyphIndex() { return m_face.cache().getGlyphIndex(m_face, unicodeChar()); } - void glyphOffsetXY(Glyph* glyph) { - // Do nothing - } + void glyphOffsetXY(Glyph* glyph) + { + // Do nothing + } - void glyphAdvanceXY(const Glyph* glyph, double& x, double& y) { - x += glyph->ft_glyph->advance.x / double(1 << 16); - y += glyph->ft_glyph->advance.y / double(1 << 16); - } + void glyphAdvanceXY(const Glyph* glyph, double& x, double& y) + { + x += glyph->ft_glyph->advance.x / double(1 << 16); + y += glyph->ft_glyph->advance.y / double(1 << 16); + } - private: - FaceFT& m_face; - std::string::const_iterator m_begin; - std::string::const_iterator m_pos; - base::utf8_decode m_decode; - int m_char = 0; - }; - - template > - class ForEachGlyph { - public: - typedef typename FaceFT::Glyph Glyph; - - ForEachGlyph(FaceFT& face, const std::string& str) - : m_face(face) - , m_shaper(face, str) - , m_glyph(nullptr) - , m_useKerning(FT_HAS_KERNING(((FT_Face)face)) ? true: false) - , m_prevGlyph(0) - , m_x(0.0), m_y(0.0) { - } +private: + FaceFT& m_face; + std::string::const_iterator m_begin; + std::string::const_iterator m_pos; + base::utf8_decode m_decode; + int m_char = 0; +}; + +template> +class ForEachGlyph { +public: + typedef typename FaceFT::Glyph Glyph; + + ForEachGlyph(FaceFT& face, const std::string& str) + : m_face(face) + , m_shaper(face, str) + , m_glyph(nullptr) + , m_useKerning(FT_HAS_KERNING(((FT_Face)face)) ? true : false) + , m_prevGlyph(0) + , m_x(0.0) + , m_y(0.0) + { + } - ~ForEachGlyph() { - unloadGlyph(); - } + ~ForEachGlyph() { unloadGlyph(); } - int unicodeChar() { return m_shaper.unicodeChar(); } - int charIndex() { return m_shaper.charIndex(); } + int unicodeChar() { return m_shaper.unicodeChar(); } + int charIndex() { return m_shaper.charIndex(); } - const Glyph* glyph() const { return m_glyph; } + const Glyph* glyph() const { return m_glyph; } - int next() { - if (m_glyph) - m_prevGlyph = m_shaper.glyphIndex(); + int next() + { + if (m_glyph) + m_prevGlyph = m_shaper.glyphIndex(); - if (int chr = m_shaper.next()) { - prepareGlyph(); - return chr; - } - return 0; + if (int chr = m_shaper.next()) { + prepareGlyph(); + return chr; } + return 0; + } + +private: + void prepareGlyph() + { + FT_UInt glyphIndex = m_shaper.glyphIndex(); + double initialX = m_x; - private: - void prepareGlyph() { - FT_UInt glyphIndex = m_shaper.glyphIndex(); - double initialX = m_x; - - if (m_useKerning && m_prevGlyph && glyphIndex) { - FT_Vector kerning; - FT_Get_Kerning(m_face, m_prevGlyph, glyphIndex, - FT_KERNING_DEFAULT, &kerning); - m_x += kerning.x / 64.0; - } - - unloadGlyph(); - - // Load new glyph - m_glyph = m_face.cache().loadGlyph(m_face, glyphIndex, m_face.antialias()); - if (m_glyph) { - m_glyph->bitmap = &FT_BitmapGlyph(m_glyph->ft_glyph)->bitmap; - m_glyph->x = m_x - + m_glyph->bearingX; - m_glyph->y = m_y - + m_face.height() - + m_face.descender() // descender is negative - - m_glyph->bearingY; - - m_shaper.glyphOffsetXY(m_glyph); - m_shaper.glyphAdvanceXY(m_glyph, m_x, m_y); - - m_glyph->startX = initialX; - m_glyph->endX = m_x; - } + if (m_useKerning && m_prevGlyph && glyphIndex) { + FT_Vector kerning; + FT_Get_Kerning(m_face, m_prevGlyph, glyphIndex, FT_KERNING_DEFAULT, &kerning); + m_x += kerning.x / 64.0; } - void unloadGlyph() { - if (m_glyph) { - m_face.cache().doneGlyph(m_glyph); - m_glyph = nullptr; - } + unloadGlyph(); + + // Load new glyph + m_glyph = m_face.cache().loadGlyph(m_face, glyphIndex, m_face.antialias()); + if (m_glyph) { + m_glyph->bitmap = &FT_BitmapGlyph(m_glyph->ft_glyph)->bitmap; + m_glyph->x = m_x + m_glyph->bearingX; + m_glyph->y = m_y + m_face.height() + m_face.descender() // descender is negative + - m_glyph->bearingY; + + m_shaper.glyphOffsetXY(m_glyph); + m_shaper.glyphAdvanceXY(m_glyph, m_x, m_y); + + m_glyph->startX = initialX; + m_glyph->endX = m_x; } + } - private: - FaceFT& m_face; - Shaper m_shaper; - Glyph* m_glyph; - bool m_useKerning; - FT_UInt m_prevGlyph; - double m_x, m_y; - }; - - template - gfx::Rect calc_text_bounds(FaceFT& face, const std::string& str) { - gfx::Rect bounds(0, 0, 0, 0); - ForEachGlyph feg(face, str); - while (feg.next()) { - if (auto glyph = feg.glyph()) - bounds |= gfx::Rect(int(glyph->x), - int(glyph->y), - glyph->bitmap->width, - glyph->bitmap->rows); + void unloadGlyph() + { + if (m_glyph) { + m_face.cache().doneGlyph(m_glyph); + m_glyph = nullptr; } - return bounds; } +private: + FaceFT& m_face; + Shaper m_shaper; + Glyph* m_glyph; + bool m_useKerning; + FT_UInt m_prevGlyph; + double m_x, m_y; +}; + +template +gfx::Rect calc_text_bounds(FaceFT& face, const std::string& str) +{ + gfx::Rect bounds(0, 0, 0, 0); + ForEachGlyph feg(face, str); + while (feg.next()) { + if (auto glyph = feg.glyph()) + bounds |= gfx::Rect(int(glyph->x), int(glyph->y), glyph->bitmap->width, glyph->bitmap->rows); + } + return bounds; +} + } // namespace ft #endif diff --git a/ft/face.h b/ft/face.h index 2e9b6bc3a..069268f37 100644 --- a/ft/face.h +++ b/ft/face.h @@ -17,188 +17,192 @@ namespace ft { - struct Glyph { - FT_UInt glyph_index; - FT_Glyph ft_glyph; - FT_Bitmap* bitmap; - double startX; - double endX; - double bearingX; - double bearingY; - double x; - double y; - }; - - template - class FaceFT { - public: - typedef ft::Glyph Glyph; - - FaceFT(FT_Face face) : m_face(face) { - } - - ~FaceFT() { - if (m_face) - FT_Done_Face(m_face); - } - - operator FT_Face() { return m_face; } - FT_Face operator->() { return m_face; } - - bool isValid() const { - return (m_face != nullptr); - } - - bool antialias() const { - return m_antialias; - } - - void setAntialias(bool antialias) { - m_antialias = antialias; - m_cache.invalidate(); - } - - void setSize(int size) { - FT_Set_Pixel_Sizes(m_face, size, size); - m_cache.invalidate(); - } - - double height() const { - FT_Size_Metrics* metrics = &m_face->size->metrics; - double em_size = 1.0 * m_face->units_per_EM; - double y_scale = metrics->y_ppem / em_size; - return int(m_face->height * y_scale) - 1; - } - - double ascender() const { - FT_Size_Metrics* metrics = &m_face->size->metrics; - double em_size = 1.0 * m_face->units_per_EM; - double y_scale = metrics->y_ppem / em_size; - return int(m_face->ascender * y_scale); - } - - double descender() const { - FT_Size_Metrics* metrics = &m_face->size->metrics; - double em_size = 1.0 * m_face->units_per_EM; - double y_scale = metrics->y_ppem / em_size; - return int(m_face->descender * y_scale); - } - - bool hasCodePoint(int codepoint) const { - if (m_face) { - codepoint = FT_Get_Char_Index(m_face, codepoint); - return (codepoint != 0); - } - return false; - } - - Cache& cache() { return m_cache; } - - protected: - FT_Face m_face; - bool m_antialias; - Cache m_cache; - - private: - DISABLE_COPYING(FaceFT); - }; - - class NoCache { - public: - void invalidate() { - // Do nothing - } - - FT_UInt getGlyphIndex(FT_Face face, int charCode) { - return FT_Get_Char_Index(face, charCode); - } - - Glyph* loadGlyph(FT_Face face, FT_UInt glyphIndex, bool antialias) { - FT_Error err = FT_Load_Glyph( - face, glyphIndex, - FT_LOAD_RENDER | +struct Glyph { + FT_UInt glyph_index; + FT_Glyph ft_glyph; + FT_Bitmap* bitmap; + double startX; + double endX; + double bearingX; + double bearingY; + double x; + double y; +}; + +template +class FaceFT { +public: + typedef ft::Glyph Glyph; + + FaceFT(FT_Face face) : m_face(face) {} + + ~FaceFT() + { + if (m_face) + FT_Done_Face(m_face); + } + + operator FT_Face() { return m_face; } + FT_Face operator->() { return m_face; } + + bool isValid() const { return (m_face != nullptr); } + + bool antialias() const { return m_antialias; } + + void setAntialias(bool antialias) + { + m_antialias = antialias; + m_cache.invalidate(); + } + + void setSize(int size) + { + FT_Set_Pixel_Sizes(m_face, size, size); + m_cache.invalidate(); + } + + double height() const + { + FT_Size_Metrics* metrics = &m_face->size->metrics; + double em_size = 1.0 * m_face->units_per_EM; + double y_scale = metrics->y_ppem / em_size; + return int(m_face->height * y_scale) - 1; + } + + double ascender() const + { + FT_Size_Metrics* metrics = &m_face->size->metrics; + double em_size = 1.0 * m_face->units_per_EM; + double y_scale = metrics->y_ppem / em_size; + return int(m_face->ascender * y_scale); + } + + double descender() const + { + FT_Size_Metrics* metrics = &m_face->size->metrics; + double em_size = 1.0 * m_face->units_per_EM; + double y_scale = metrics->y_ppem / em_size; + return int(m_face->descender * y_scale); + } + + bool hasCodePoint(int codepoint) const + { + if (m_face) { + codepoint = FT_Get_Char_Index(m_face, codepoint); + return (codepoint != 0); + } + return false; + } + + Cache& cache() { return m_cache; } + +protected: + FT_Face m_face; + bool m_antialias; + Cache m_cache; + +private: + DISABLE_COPYING(FaceFT); +}; + +class NoCache { +public: + void invalidate() + { + // Do nothing + } + + FT_UInt getGlyphIndex(FT_Face face, int charCode) { return FT_Get_Char_Index(face, charCode); } + + Glyph* loadGlyph(FT_Face face, FT_UInt glyphIndex, bool antialias) + { + FT_Error err = FT_Load_Glyph( + face, + glyphIndex, + FT_LOAD_RENDER | // TODO Check if we can render correctly th embedded bitmaps // in the future removing FT_LOAD_NO_BITMAP for fonts // like Calibri, Cambria, Monaco, etc. - (antialias ? FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_BITMAP: - FT_LOAD_TARGET_MONO)); - if (err) - return nullptr; + (antialias ? FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_BITMAP : FT_LOAD_TARGET_MONO)); + if (err) + return nullptr; - FT_Glyph ft_glyph; - err = FT_Get_Glyph(face->glyph, &ft_glyph); - if (err) + FT_Glyph ft_glyph; + err = FT_Get_Glyph(face->glyph, &ft_glyph); + if (err) + return nullptr; + + if (ft_glyph->format != FT_GLYPH_FORMAT_BITMAP) { + err = FT_Glyph_To_Bitmap(&ft_glyph, FT_RENDER_MODE_NORMAL, 0, 1); + if (!err) { + FT_Done_Glyph(ft_glyph); return nullptr; - - if (ft_glyph->format != FT_GLYPH_FORMAT_BITMAP) { - err = FT_Glyph_To_Bitmap(&ft_glyph, FT_RENDER_MODE_NORMAL, 0, 1); - if (!err) { - FT_Done_Glyph(ft_glyph); - return nullptr; - } } - - m_glyph.ft_glyph = ft_glyph; - m_glyph.bearingX = face->glyph->metrics.horiBearingX / 64.0; - m_glyph.bearingY = face->glyph->metrics.horiBearingY / 64.0; - - return &m_glyph; } - void doneGlyph(Glyph* glyph) { - ASSERT(glyph); - FT_Done_Glyph(glyph->ft_glyph); - } + m_glyph.ft_glyph = ft_glyph; + m_glyph.bearingX = face->glyph->metrics.horiBearingX / 64.0; + m_glyph.bearingY = face->glyph->metrics.horiBearingY / 64.0; - private: - Glyph m_glyph; - }; + return &m_glyph; + } - class SimpleCache : public NoCache { - public: - ~SimpleCache() { - invalidate(); - } + void doneGlyph(Glyph* glyph) + { + ASSERT(glyph); + FT_Done_Glyph(glyph->ft_glyph); + } - void invalidate() { - for (auto& it : m_glyphMap) { - FT_Done_Glyph(it.second->ft_glyph); - delete it.second; - } +private: + Glyph m_glyph; +}; + +class SimpleCache : public NoCache { +public: + ~SimpleCache() { invalidate(); } - m_glyphMap.clear(); + void invalidate() + { + for (auto& it : m_glyphMap) { + FT_Done_Glyph(it.second->ft_glyph); + delete it.second; } - Glyph* loadGlyph(FT_Face face, FT_UInt glyphIndex, bool antialias) { - auto it = m_glyphMap.find(glyphIndex); - if (it != m_glyphMap.end()) - return it->second; + m_glyphMap.clear(); + } - Glyph* glyph = NoCache::loadGlyph(face, glyphIndex, antialias); - if (!glyph) - return nullptr; + Glyph* loadGlyph(FT_Face face, FT_UInt glyphIndex, bool antialias) + { + auto it = m_glyphMap.find(glyphIndex); + if (it != m_glyphMap.end()) + return it->second; - FT_Glyph new_ft_glyph = nullptr; - FT_Glyph_Copy(glyph->ft_glyph, &new_ft_glyph); - if (!new_ft_glyph) - return nullptr; + Glyph* glyph = NoCache::loadGlyph(face, glyphIndex, antialias); + if (!glyph) + return nullptr; - Glyph* newGlyph = new Glyph(*glyph); - newGlyph->ft_glyph = new_ft_glyph; + FT_Glyph new_ft_glyph = nullptr; + FT_Glyph_Copy(glyph->ft_glyph, &new_ft_glyph); + if (!new_ft_glyph) + return nullptr; - m_glyphMap[glyphIndex] = newGlyph; - FT_Done_Glyph(glyph->ft_glyph); + Glyph* newGlyph = new Glyph(*glyph); + newGlyph->ft_glyph = new_ft_glyph; - return newGlyph; - } + m_glyphMap[glyphIndex] = newGlyph; + FT_Done_Glyph(glyph->ft_glyph); - void doneGlyph(Glyph* glyph) { - // Do nothing - } + return newGlyph; + } + + void doneGlyph(Glyph* glyph) + { + // Do nothing + } - private: - std::map m_glyphMap; - }; +private: + std::map m_glyphMap; +}; } // namespace ft diff --git a/ft/hb_face.h b/ft/hb_face.h index bd11cc052..558bc8180 100644 --- a/ft/hb_face.h +++ b/ft/hb_face.h @@ -12,29 +12,32 @@ #include "base/string.h" #include "ft/face.h" -#include #include +#include namespace ft { - template - class HBFace : public FaceFT { - public: - HBFace(FT_Face face) : FaceFT(face) { - m_font = (face ? hb_ft_font_create((FT_Face)face, nullptr): nullptr); - } +template +class HBFace : public FaceFT { +public: + HBFace(FT_Face face) : FaceFT(face) + { + m_font = (face ? hb_ft_font_create((FT_Face)face, nullptr) : nullptr); + } - ~HBFace() { - if (m_font) hb_font_destroy(m_font); - } + ~HBFace() + { + if (m_font) + hb_font_destroy(m_font); + } - hb_font_t* font() const { return m_font; } + hb_font_t* font() const { return m_font; } - private: - hb_font_t* m_font; - }; +private: + hb_font_t* m_font; +}; - typedef HBFace > Face; +typedef HBFace> Face; } // namespace ft diff --git a/ft/hb_shaper.h b/ft/hb_shaper.h index b4c025e0f..08e852268 100644 --- a/ft/hb_shaper.h +++ b/ft/hb_shaper.h @@ -16,111 +16,108 @@ namespace ft { - template - class HBShaper { - public: - - HBShaper(HBFace& face, const std::string& str) - : m_face(face) { - base::utf8_decode decode(str); - if (decode.is_end()) - return; - - hb_buffer_t* buf = hb_buffer_create(); - hb_buffer_t* chrBuf = hb_buffer_create(); - hb_script_t script = HB_SCRIPT_UNKNOWN; - - const auto begin = str.begin(); - while (true) { - const auto pos = decode.pos(); - const int chr = decode.next(); - if (!chr) - break; - - // Get the script of the next character in *it - hb_buffer_set_content_type(chrBuf, HB_BUFFER_CONTENT_TYPE_UNICODE); - hb_buffer_add(chrBuf, chr, 0); - hb_buffer_guess_segment_properties(chrBuf); - hb_script_t newScript = hb_buffer_get_script(chrBuf); - hb_buffer_reset(chrBuf); - - if (newScript && script != newScript) { - addBuffer(buf, script); - hb_buffer_reset(buf); - script = newScript; - } - - hb_buffer_add(buf, chr, pos - begin); +template +class HBShaper { +public: + HBShaper(HBFace& face, const std::string& str) : m_face(face) + { + base::utf8_decode decode(str); + if (decode.is_end()) + return; + + hb_buffer_t* buf = hb_buffer_create(); + hb_buffer_t* chrBuf = hb_buffer_create(); + hb_script_t script = HB_SCRIPT_UNKNOWN; + + const auto begin = str.begin(); + while (true) { + const auto pos = decode.pos(); + const int chr = decode.next(); + if (!chr) + break; + + // Get the script of the next character in *it + hb_buffer_set_content_type(chrBuf, HB_BUFFER_CONTENT_TYPE_UNICODE); + hb_buffer_add(chrBuf, chr, 0); + hb_buffer_guess_segment_properties(chrBuf); + hb_script_t newScript = hb_buffer_get_script(chrBuf); + hb_buffer_reset(chrBuf); + + if (newScript && script != newScript) { + addBuffer(buf, script); + hb_buffer_reset(buf); + script = newScript; } - addBuffer(buf, script); - hb_buffer_destroy(buf); - hb_buffer_destroy(chrBuf); + hb_buffer_add(buf, chr, pos - begin); } + addBuffer(buf, script); - int next() { - if (++m_index < m_glyphCount) - return m_glyphInfo[m_index].codepoint; - return 0; - } + hb_buffer_destroy(buf); + hb_buffer_destroy(chrBuf); + } - int unicodeChar() const { + int next() + { + if (++m_index < m_glyphCount) return m_glyphInfo[m_index].codepoint; - } + return 0; + } - int charIndex() const { - return m_glyphInfo[m_index].cluster; - } + int unicodeChar() const { return m_glyphInfo[m_index].codepoint; } - unsigned int glyphIndex() const { - return m_glyphInfo[m_index].codepoint; - } + int charIndex() const { return m_glyphInfo[m_index].cluster; } - void glyphOffsetXY(Glyph* glyph) { - glyph->x += m_glyphPos[m_index].x_offset / 64.0; - glyph->y += m_glyphPos[m_index].y_offset / 64.0; - } + unsigned int glyphIndex() const { return m_glyphInfo[m_index].codepoint; } - void glyphAdvanceXY(const Glyph* glyph, double& x, double& y) { - x += m_glyphPos[m_index].x_advance / 64.0; - y += m_glyphPos[m_index].y_advance / 64.0; - } + void glyphOffsetXY(Glyph* glyph) + { + glyph->x += m_glyphPos[m_index].x_offset / 64.0; + glyph->y += m_glyphPos[m_index].y_offset / 64.0; + } + + void glyphAdvanceXY(const Glyph* glyph, double& x, double& y) + { + x += m_glyphPos[m_index].x_advance / 64.0; + y += m_glyphPos[m_index].y_advance / 64.0; + } - private: - void addBuffer(hb_buffer_t* buf, hb_script_t script) { - if (hb_buffer_get_length(buf) == 0) - return; +private: + void addBuffer(hb_buffer_t* buf, hb_script_t script) + { + if (hb_buffer_get_length(buf) == 0) + return; - // Just in case we're compiling with an old harfbuzz version + // Just in case we're compiling with an old harfbuzz version #ifdef HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS - hb_buffer_set_cluster_level(buf, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS); + hb_buffer_set_cluster_level(buf, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS); #endif - hb_buffer_set_content_type(buf, HB_BUFFER_CONTENT_TYPE_UNICODE); - hb_buffer_set_script(buf, script); - hb_buffer_set_direction(buf, hb_script_get_horizontal_direction(script)); - - hb_shape(m_face.font(), buf, nullptr, 0); - - unsigned int count; - auto info = hb_buffer_get_glyph_infos(buf, &count); - auto pos = hb_buffer_get_glyph_positions(buf, &count); - - m_glyphCount += count; - const unsigned int start = m_glyphInfo.size(); - m_glyphInfo.resize(m_glyphCount); - m_glyphPos.resize(m_glyphCount); - for (unsigned int i=0; i m_glyphInfo; - std::vector m_glyphPos; - int m_glyphCount = 0; - int m_index = -1; - }; + } + + HBFace& m_face; + std::vector m_glyphInfo; + std::vector m_glyphPos; + int m_glyphCount = 0; + int m_index = -1; +}; } // namespace ft diff --git a/ft/lib.cpp b/ft/lib.cpp index 2d73acb03..512789bb2 100644 --- a/ft/lib.cpp +++ b/ft/lib.cpp @@ -14,8 +14,7 @@ namespace ft { -Lib::Lib() - : m_ft(nullptr) +Lib::Lib() : m_ft(nullptr) { FT_Init_FreeType(&m_ft); } diff --git a/ft/lib.h b/ft/lib.h index fa9fa94b7..35ff5a40b 100644 --- a/ft/lib.h +++ b/ft/lib.h @@ -15,20 +15,20 @@ namespace ft { - class Lib { - public: - Lib(); - ~Lib(); +class Lib { +public: + Lib(); + ~Lib(); - operator FT_Library() { return m_ft; } + operator FT_Library() { return m_ft; } - FT_Face open(const std::string& filename); + FT_Face open(const std::string& filename); - private: - FT_Library m_ft; +private: + FT_Library m_ft; - DISABLE_COPYING(Lib); - }; + DISABLE_COPYING(Lib); +}; } // namespace ft diff --git a/ft/stream.cpp b/ft/stream.cpp index 09da4ae72..b8d3ee2c1 100644 --- a/ft/stream.cpp +++ b/ft/stream.cpp @@ -7,8 +7,8 @@ #include "ft/stream.h" -#include "base/file_handle.h" #include "base/debug.h" +#include "base/file_handle.h" #include @@ -41,7 +41,7 @@ FT_Stream open_stream(const std::string& utf8Filename) { FT_Stream stream = nullptr; stream = (FT_Stream)malloc(sizeof(*stream)); - if(!stream) + if (!stream) return nullptr; memset(stream, 0, sizeof(*stream)); diff --git a/gfx/border.h b/gfx/border.h index c1c36750a..30f68ab00 100644 --- a/gfx/border.h +++ b/gfx/border.h @@ -15,28 +15,24 @@ template class SizeT; template -class BorderT -{ +class BorderT { public: - BorderT() : - m_left(0), - m_top(0), - m_right(0), - m_bottom(0) { - } + BorderT() : m_left(0), m_top(0), m_right(0), m_bottom(0) {} - BorderT(const T& left, const T& top, const T& right, const T& bottom) : - m_left(left), - m_top(top), - m_right(right), - m_bottom(bottom) { + BorderT(const T& left, const T& top, const T& right, const T& bottom) + : m_left(left) + , m_top(top) + , m_right(right) + , m_bottom(bottom) + { } - explicit BorderT(const T& allSides) : - m_left(allSides), - m_top(allSides), - m_right(allSides), - m_bottom(allSides) { + explicit BorderT(const T& allSides) + : m_left(allSides) + , m_top(allSides) + , m_right(allSides) + , m_bottom(allSides) + { } T left() const { return m_left; }; @@ -52,11 +48,10 @@ class BorderT void right(const T& right) { m_right = right; } void bottom(const T& bottom) { m_bottom = bottom; } - SizeT size() const { - return SizeT(m_left + m_right, m_top + m_bottom); - } + SizeT size() const { return SizeT(m_left + m_right, m_top + m_bottom); } - const BorderT& operator+=(const BorderT& br) { + const BorderT& operator+=(const BorderT& br) + { m_left += br.m_left; m_top += br.m_top; m_right += br.m_right; @@ -64,7 +59,8 @@ class BorderT return *this; } - const BorderT& operator-=(const BorderT& br) { + const BorderT& operator-=(const BorderT& br) + { m_left -= br.m_left; m_top -= br.m_top; m_right -= br.m_right; @@ -72,7 +68,8 @@ class BorderT return *this; } - const BorderT& operator*=(const BorderT& br) { + const BorderT& operator*=(const BorderT& br) + { m_left *= br.m_left; m_top *= br.m_top; m_right *= br.m_right; @@ -80,7 +77,8 @@ class BorderT return *this; } - const BorderT& operator/=(const BorderT& br) { + const BorderT& operator/=(const BorderT& br) + { m_left /= br.m_left; m_top /= br.m_top; m_right /= br.m_right; @@ -88,7 +86,8 @@ class BorderT return *this; } - const BorderT& operator+=(const T& value) { + const BorderT& operator+=(const T& value) + { m_left += value; m_top += value; m_right += value; @@ -96,7 +95,8 @@ class BorderT return *this; } - const BorderT& operator-=(const T& value) { + const BorderT& operator-=(const T& value) + { m_left -= value; m_top -= value; m_right -= value; @@ -104,7 +104,8 @@ class BorderT return *this; } - const BorderT& operator*=(const T& value) { + const BorderT& operator*=(const T& value) + { m_left *= value; m_top *= value; m_right *= value; @@ -112,7 +113,8 @@ class BorderT return *this; } - const BorderT& operator/=(const T& value) { + const BorderT& operator/=(const T& value) + { m_left /= value; m_top /= value; m_right /= value; @@ -120,76 +122,70 @@ class BorderT return *this; } - BorderT operator+(const BorderT& br) const { + BorderT operator+(const BorderT& br) const + { return BorderT(m_left + br.left(), m_top + br.top(), m_right + br.right(), m_bottom + br.bottom()); } - BorderT operator-(const BorderT& br) const { + BorderT operator-(const BorderT& br) const + { return BorderT(m_left - br.left(), m_top - br.top(), m_right - br.right(), m_bottom - br.bottom()); } - BorderT operator*(const BorderT& br) const { + BorderT operator*(const BorderT& br) const + { return BorderT(m_left * br.left(), m_top * br.top(), m_right * br.right(), m_bottom * br.bottom()); } - BorderT operator/(const BorderT& br) const { + BorderT operator/(const BorderT& br) const + { return BorderT(m_left / br.left(), m_top / br.top(), m_right / br.right(), m_bottom / br.bottom()); } - BorderT operator+(const T& value) const { - return BorderT(m_left + value, - m_top + value, - m_right + value, - m_bottom + value); + BorderT operator+(const T& value) const + { + return BorderT(m_left + value, m_top + value, m_right + value, m_bottom + value); } - BorderT operator-(const T& value) const { - return BorderT(m_left - value, - m_top - value, - m_right - value, - m_bottom - value); + BorderT operator-(const T& value) const + { + return BorderT(m_left - value, m_top - value, m_right - value, m_bottom - value); } - BorderT operator*(const T& value) const { - return BorderT(m_left * value, - m_top * value, - m_right * value, - m_bottom * value); + BorderT operator*(const T& value) const + { + return BorderT(m_left * value, m_top * value, m_right * value, m_bottom * value); } - BorderT operator/(const T& value) const { - return BorderT(m_left / value, - m_top / value, - m_right / value, - m_bottom / value); + BorderT operator/(const T& value) const + { + return BorderT(m_left / value, m_top / value, m_right / value, m_bottom / value); } - BorderT operator-() const { - return BorderT(-m_left, -m_top, -m_right, -m_bottom); - } + BorderT operator-() const { return BorderT(-m_left, -m_top, -m_right, -m_bottom); } - bool operator==(const BorderT& br) const { - return - m_left == br.m_left && m_top == br.m_top && - m_right == br.m_right && m_bottom == br.m_bottom; + bool operator==(const BorderT& br) const + { + return m_left == br.m_left && m_top == br.m_top && m_right == br.m_right && + m_bottom == br.m_bottom; } - bool operator!=(const BorderT& br) const { - return - m_left != br.m_left || m_top != br.m_top || - m_right != br.m_right || m_bottom != br.m_bottom; + bool operator!=(const BorderT& br) const + { + return m_left != br.m_left || m_top != br.m_top || m_right != br.m_right || + m_bottom != br.m_bottom; } private: @@ -204,7 +200,7 @@ typedef BorderT Border; } // namespace gfx #ifdef _DEBUG -#include "gfx/border_io.h" + #include "gfx/border_io.h" #endif #endif diff --git a/gfx/border_io.h b/gfx/border_io.h index b6398b334..641b84de6 100644 --- a/gfx/border_io.h +++ b/gfx/border_io.h @@ -13,38 +13,34 @@ namespace gfx { - template - inline std::ostream& operator<<(std::ostream& os, const BorderT& border) { - return os << "(" - << border.left() << ", " - << border.top() << ", " - << border.right() << ", " - << border.bottom() << ")"; - } - - template - inline std::istream& operator>>(std::istream& in, BorderT& border) { - while (in && in.get() != '(') - ; - - if (!in) - return in; - - T l, t, r, b; - char chr; - in >> l >> chr - >> t >> chr - >> r >> chr - >> b >> chr; - - border.left(l); - border.top(t); - border.right(r); - border.bottom(b); +template +inline std::ostream& operator<<(std::ostream& os, const BorderT& border) +{ + return os << "(" << border.left() << ", " << border.top() << ", " << border.right() << ", " + << border.bottom() << ")"; +} + +template +inline std::istream& operator>>(std::istream& in, BorderT& border) +{ + while (in && in.get() != '(') + ; + if (!in) return in; - } + T l, t, r, b; + char chr; + in >> l >> chr >> t >> chr >> r >> chr >> b >> chr; + + border.left(l); + border.top(t); + border.right(r); + border.bottom(b); + + return in; } +} // namespace gfx + #endif diff --git a/gfx/clip.h b/gfx/clip.h index 2f0a7b4d4..0a0a5b8e9 100644 --- a/gfx/clip.h +++ b/gfx/clip.h @@ -15,179 +15,171 @@ namespace gfx { - // Imagine you want to copy the following rectangle - // - // size.w - // +---------+ - // | | size.h - // +---------+ - // - // from a "source image" to a "destination image", from "src" - // location to the "dst" location: - // - // "source image" "destination image" - // +--------------+ +---------------------+ - // src.xy | | | dst.xy | - // +---------+ | | +---------+ - // | | | ---> | | | - // +---------+ | | +---------+ - // | | | | - // +--------------+ +---------------------+ - // - // There are two restrictions: - // - // 1) You cannot read from the "source image" outside its bounds, and - // 2) you cannot write into the "destination image" outside its bounds. - // - // This Clip class helps to determine the only valid region to - // read/write between these two images. The initial Clip values can - // be outside these bounds, but the Clip::clip() function determines - // the valid region. - // - // So in our example, if the "source image" has a dimension of - // "avail_src_w/h" and the "destination image" a dimension of - // "avail_dst_w/h", after calling Clip::clip() we get these modified - // Clip fields: - // - // "source image" "destination image" - // +--------------+ +---------------------+ - // src.xy | | dst.xy | - // .....+---+. | | .....+---+. - // .....| |. | ---> | .....| |. - // .....+---+. | | .....+---+. - // | | | | - // +--------------+ +---------------------+ - // - // The dotted areas (...) are invalid image regions that cannot be - // read/written. The "dst", "src", and "size" fields of the Clip - // instance are adjusted to be inside both images. - // - // Clip::clip() returns false in case there is no valid area to - // copy. - template - class ClipT { - public: - PointT dst; - PointT src; - SizeT size; - - ClipT() - : dst(0, 0) - , src(0, 0) - , size(0, 0) { - } - - ClipT(T w, T h) - : dst(0, 0) - , src(0, 0) - , size(w, h) { - } - - explicit ClipT(const SizeT& sz) - : dst(0, 0) - , src(0, 0) - , size(sz) { +// Imagine you want to copy the following rectangle +// +// size.w +// +---------+ +// | | size.h +// +---------+ +// +// from a "source image" to a "destination image", from "src" +// location to the "dst" location: +// +// "source image" "destination image" +// +--------------+ +---------------------+ +// src.xy | | | dst.xy | +// +---------+ | | +---------+ +// | | | ---> | | | +// +---------+ | | +---------+ +// | | | | +// +--------------+ +---------------------+ +// +// There are two restrictions: +// +// 1) You cannot read from the "source image" outside its bounds, and +// 2) you cannot write into the "destination image" outside its bounds. +// +// This Clip class helps to determine the only valid region to +// read/write between these two images. The initial Clip values can +// be outside these bounds, but the Clip::clip() function determines +// the valid region. +// +// So in our example, if the "source image" has a dimension of +// "avail_src_w/h" and the "destination image" a dimension of +// "avail_dst_w/h", after calling Clip::clip() we get these modified +// Clip fields: +// +// "source image" "destination image" +// +--------------+ +---------------------+ +// src.xy | | dst.xy | +// .....+---+. | | .....+---+. +// .....| |. | ---> | .....| |. +// .....+---+. | | .....+---+. +// | | | | +// +--------------+ +---------------------+ +// +// The dotted areas (...) are invalid image regions that cannot be +// read/written. The "dst", "src", and "size" fields of the Clip +// instance are adjusted to be inside both images. +// +// Clip::clip() returns false in case there is no valid area to +// copy. +template +class ClipT { +public: + PointT dst; + PointT src; + SizeT size; + + ClipT() : dst(0, 0), src(0, 0), size(0, 0) {} + + ClipT(T w, T h) : dst(0, 0), src(0, 0), size(w, h) {} + + explicit ClipT(const SizeT& sz) : dst(0, 0), src(0, 0), size(sz) {} + + ClipT(T dst_x, T dst_y, T src_x, T src_y, T w, T h) + : dst(dst_x, dst_y) + , src(src_x, src_y) + , size(w, h) + { + } + + ClipT(T dst_x, T dst_y, const RectT& srcBounds) + : dst(dst_x, dst_y) + , src(srcBounds.x, srcBounds.y) + , size(srcBounds.w, srcBounds.h) + { + } + + ClipT(const PointT& dst, const PointT& src, const SizeT& size) + : dst(dst) + , src(src) + , size(size) + { + } + + ClipT(const PointT& dst, const RectT& srcBounds) + : dst(dst) + , src(srcBounds.x, srcBounds.y) + , size(srcBounds.w, srcBounds.h) + { + } + + ClipT(const RectT& bounds) + : dst(bounds.x, bounds.y) + , src(bounds.x, bounds.y) + , size(bounds.w, bounds.h) + { + } + + template + ClipT(const ClipT& other) : dst(other.dst) + , src(other.src) + , size(other.size) + { + } + + RectT dstBounds() const { return RectT(dst, size); } + RectT srcBounds() const { return RectT(src, size); } + + bool operator==(const ClipT& other) const + { + return (dst == other.dst && src == other.src && size == other.size); + } + + bool clip( + // Available area + T avail_dst_w, + T avail_dst_h, + T avail_src_w, + T avail_src_h) + { + // Clip srcBounds + + if (src.x < T(0)) { + size.w += src.x; + dst.x -= src.x; + src.x = T(0); } - ClipT(T dst_x, T dst_y, T src_x, T src_y, T w, T h) - : dst(dst_x, dst_y) - , src(src_x, src_y) - , size(w, h) { + if (src.y < T(0)) { + size.h += src.y; + dst.y -= src.y; + src.y = T(0); } - ClipT(T dst_x, T dst_y, const RectT& srcBounds) - : dst(dst_x, dst_y) - , src(srcBounds.x, srcBounds.y) - , size(srcBounds.w, srcBounds.h) { - } + if (src.x + size.w > avail_src_w) + size.w -= src.x + size.w - avail_src_w; - ClipT(const PointT& dst, const PointT& src, const SizeT& size) - : dst(dst) - , src(src) - , size(size) { - } + if (src.y + size.h > avail_src_h) + size.h -= src.y + size.h - avail_src_h; - ClipT(const PointT& dst, const RectT& srcBounds) - : dst(dst) - , src(srcBounds.x, srcBounds.y) - , size(srcBounds.w, srcBounds.h) { - } + // Clip dstBounds - ClipT(const RectT& bounds) - : dst(bounds.x, bounds.y) - , src(bounds.x, bounds.y) - , size(bounds.w, bounds.h) { + if (dst.x < T(0)) { + size.w += dst.x; + src.x -= dst.x; + dst.x = T(0); } - template - ClipT(const ClipT& other) - : dst(other.dst) - , src(other.src) - , size(other.size) { + if (dst.y < T(0)) { + size.h += dst.y; + src.y -= dst.y; + dst.y = T(0); } - RectT dstBounds() const { return RectT(dst, size); } - RectT srcBounds() const { return RectT(src, size); } + if (dst.x + size.w > avail_dst_w) + size.w -= dst.x + size.w - avail_dst_w; - bool operator==(const ClipT& other) const { - return (dst == other.dst && - src == other.src && - size == other.size); - } - - bool clip( - // Available area - T avail_dst_w, - T avail_dst_h, - T avail_src_w, - T avail_src_h) { - // Clip srcBounds - - if (src.x < T(0)) { - size.w += src.x; - dst.x -= src.x; - src.x = T(0); - } - - if (src.y < T(0)) { - size.h += src.y; - dst.y -= src.y; - src.y = T(0); - } - - if (src.x + size.w > avail_src_w) - size.w -= src.x + size.w - avail_src_w; - - if (src.y + size.h > avail_src_h) - size.h -= src.y + size.h - avail_src_h; - - // Clip dstBounds - - if (dst.x < T(0)) { - size.w += dst.x; - src.x -= dst.x; - dst.x = T(0); - } - - if (dst.y < T(0)) { - size.h += dst.y; - src.y -= dst.y; - dst.y = T(0); - } - - if (dst.x + size.w > avail_dst_w) - size.w -= dst.x + size.w - avail_dst_w; - - if (dst.y + size.h > avail_dst_h) - size.h -= dst.y + size.h - avail_dst_h; - - return (size.w > T(0) && size.h > T(0)); - } + if (dst.y + size.h > avail_dst_h) + size.h -= dst.y + size.h - avail_dst_h; - }; + return (size.w > T(0) && size.h > T(0)); + } +}; - typedef ClipT Clip; - typedef ClipT ClipF; +typedef ClipT Clip; +typedef ClipT ClipF; } // namespace gfx diff --git a/gfx/clip_tests.cpp b/gfx/clip_tests.cpp index d08a3241d..271b1071c 100644 --- a/gfx/clip_tests.cpp +++ b/gfx/clip_tests.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -18,16 +18,11 @@ namespace gfx { inline std::ostream& operator<<(std::ostream& os, const Clip& area) { - return os << "(" - << area.dst.x << ", " - << area.dst.y << ", " - << area.src.x << ", " - << area.src.y << ", " - << area.size.w << ", " - << area.size.h << ")"; + return os << "(" << area.dst.x << ", " << area.dst.y << ", " << area.src.x << ", " << area.src.y + << ", " << area.size.w << ", " << area.size.h << ")"; } -} +} // namespace gfx TEST(ScaledClip, WithoutClip) { diff --git a/gfx/color.h b/gfx/color.h index 857384514..ddd4d6ef2 100644 --- a/gfx/color.h +++ b/gfx/color.h @@ -13,40 +13,57 @@ namespace gfx { - using Color = uint32_t; - using ColorComponent = uint8_t; +using Color = uint32_t; +using ColorComponent = uint8_t; - static constexpr uint32_t ColorRShift = 0; - static constexpr uint32_t ColorGShift = 8; - static constexpr uint32_t ColorBShift = 16; - static constexpr uint32_t ColorAShift = 24; +static constexpr uint32_t ColorRShift = 0; +static constexpr uint32_t ColorGShift = 8; +static constexpr uint32_t ColorBShift = 16; +static constexpr uint32_t ColorAShift = 24; - static constexpr uint32_t ColorRMask = 0x000000ff; - static constexpr uint32_t ColorGMask = 0x0000ff00; - static constexpr uint32_t ColorBMask = 0x00ff0000; - static constexpr uint32_t ColorAMask = 0xff000000; - static constexpr uint32_t ColorRGBMask = 0x00ffffff; +static constexpr uint32_t ColorRMask = 0x000000ff; +static constexpr uint32_t ColorGMask = 0x0000ff00; +static constexpr uint32_t ColorBMask = 0x00ff0000; +static constexpr uint32_t ColorAMask = 0xff000000; +static constexpr uint32_t ColorRGBMask = 0x00ffffff; - static constexpr Color ColorNone = Color(0); +static constexpr Color ColorNone = Color(0); - inline constexpr Color rgba(ColorComponent r, ColorComponent g, ColorComponent b, ColorComponent a = 255) { - return Color((r << ColorRShift) | - (g << ColorGShift) | - (b << ColorBShift) | - (a << ColorAShift)); - } +inline constexpr Color rgba(ColorComponent r, + ColorComponent g, + ColorComponent b, + ColorComponent a = 255) +{ + return Color((r << ColorRShift) | (g << ColorGShift) | (b << ColorBShift) | (a << ColorAShift)); +} - inline constexpr ColorComponent getr(Color c) { return (c >> ColorRShift) & 0xff; } - inline constexpr ColorComponent getg(Color c) { return (c >> ColorGShift) & 0xff; } - inline constexpr ColorComponent getb(Color c) { return (c >> ColorBShift) & 0xff; } - inline constexpr ColorComponent geta(Color c) { return (c >> ColorAShift) & 0xff; } +inline constexpr ColorComponent getr(Color c) +{ + return (c >> ColorRShift) & 0xff; +} +inline constexpr ColorComponent getg(Color c) +{ + return (c >> ColorGShift) & 0xff; +} +inline constexpr ColorComponent getb(Color c) +{ + return (c >> ColorBShift) & 0xff; +} +inline constexpr ColorComponent geta(Color c) +{ + return (c >> ColorAShift) & 0xff; +} - inline constexpr Color seta(Color c, ColorComponent a) { - return (c & ColorRGBMask) | (a << ColorAShift); - } +inline constexpr Color seta(Color c, ColorComponent a) +{ + return (c & ColorRGBMask) | (a << ColorAShift); +} - inline constexpr bool is_transparent(Color c) { return geta(c) == 0; } +inline constexpr bool is_transparent(Color c) +{ + return geta(c) == 0; +} } // namespace gfx -#endif // GFX_COLOR_H_INCLUDED +#endif // GFX_COLOR_H_INCLUDED diff --git a/gfx/color_space.cpp b/gfx/color_space.cpp index effd726eb..2b4495583 100644 --- a/gfx/color_space.cpp +++ b/gfx/color_space.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/color_space.h" @@ -22,10 +22,10 @@ ColorSpace::ColorSpace(const Type type, const Flag flags, const float gamma, std::vector&& data) - : m_type(type), - m_flags(flags), - m_gamma(gamma), - m_data(std::move(data)) + : m_type(type) + , m_flags(flags) + , m_gamma(gamma) + , m_data(std::move(data)) { } @@ -54,8 +54,7 @@ ColorSpaceRef ColorSpace::MakeSRGBWithGamma(float gamma) } // static -ColorSpaceRef ColorSpace::MakeRGB(const ColorSpaceTransferFn& fn, - const ColorSpacePrimaries& p) +ColorSpaceRef ColorSpace::MakeRGB(const ColorSpaceTransferFn& fn, const ColorSpacePrimaries& p) { std::vector data(sizeof(ColorSpaceTransferFn) + sizeof(ColorSpacePrimaries)); std::copy(((const uint8_t*)&fn), @@ -64,8 +63,7 @@ ColorSpaceRef ColorSpace::MakeRGB(const ColorSpaceTransferFn& fn, std::copy(((const uint8_t*)&p), ((const uint8_t*)&p) + sizeof(ColorSpacePrimaries), data.begin() + sizeof(ColorSpaceTransferFn)); - return base::make_ref( - RGB, Flag(HasTransferFn | HasPrimaries), 1.0, std::move(data)); + return base::make_ref(RGB, Flag(HasTransferFn | HasPrimaries), 1.0, std::move(data)); } // static @@ -82,9 +80,7 @@ ColorSpaceRef ColorSpace::MakeRGBWithSRGBGamut(const ColorSpaceTransferFn& fn) ColorSpaceRef ColorSpace::MakeRGBWithSRGBGamma(const ColorSpacePrimaries& p) { std::vector data(sizeof(ColorSpacePrimaries)); - std::copy(((const uint8_t*)&p), - ((const uint8_t*)&p) + sizeof(ColorSpacePrimaries), - data.begin()); + std::copy(((const uint8_t*)&p), ((const uint8_t*)&p) + sizeof(ColorSpacePrimaries), data.begin()); return base::make_ref(sRGB, HasPrimaries, 1.0, std::move(data)); } @@ -92,8 +88,7 @@ ColorSpaceRef ColorSpace::MakeRGBWithSRGBGamma(const ColorSpacePrimaries& p) ColorSpaceRef ColorSpace::MakeICC(const void* data, size_t n) { std::vector newData(n); - std::copy(((const uint8_t*)data), - ((const uint8_t*)data)+n, newData.begin()); + std::copy(((const uint8_t*)data), ((const uint8_t*)data) + n, newData.begin()); return base::make_ref(ICC, HasICC, 1.0, std::move(newData)); } @@ -104,7 +99,8 @@ ColorSpaceRef ColorSpace::MakeICC(std::vector&& data) } // Based on code in skia/src/core/SkICC.cpp by Google Inc. -static bool nearly_equal(float x, float y) { +static bool nearly_equal(float x, float y) +{ // A note on why I chose this tolerance: transfer_fn_almost_equal() uses a // tolerance of 0.001, which doesn't seem to be enough to distinguish // between similar transfer functions, for example: gamma2.2 and sRGB. @@ -116,27 +112,18 @@ static bool nearly_equal(float x, float y) { return fabsf(x - y) <= kTolerance; } -static bool nearly_equal(const ColorSpaceTransferFn& u, - const ColorSpaceTransferFn& v) { - return nearly_equal(u.g, v.g) - && nearly_equal(u.a, v.a) - && nearly_equal(u.b, v.b) - && nearly_equal(u.c, v.c) - && nearly_equal(u.d, v.d) - && nearly_equal(u.e, v.e) - && nearly_equal(u.f, v.f); +static bool nearly_equal(const ColorSpaceTransferFn& u, const ColorSpaceTransferFn& v) +{ + return nearly_equal(u.g, v.g) && nearly_equal(u.a, v.a) && nearly_equal(u.b, v.b) && + nearly_equal(u.c, v.c) && nearly_equal(u.d, v.d) && nearly_equal(u.e, v.e) && + nearly_equal(u.f, v.f); } -static bool nearly_equal(const ColorSpacePrimaries& u, - const ColorSpacePrimaries& v) { - return nearly_equal(u.wx, v.wx) - && nearly_equal(u.wy, v.wy) - && nearly_equal(u.rx, v.ry) - && nearly_equal(u.ry, v.ry) - && nearly_equal(u.gx, v.gy) - && nearly_equal(u.gy, v.gy) - && nearly_equal(u.bx, v.by) - && nearly_equal(u.by, v.by); +static bool nearly_equal(const ColorSpacePrimaries& u, const ColorSpacePrimaries& v) +{ + return nearly_equal(u.wx, v.wx) && nearly_equal(u.wy, v.wy) && nearly_equal(u.rx, v.ry) && + nearly_equal(u.ry, v.ry) && nearly_equal(u.gx, v.gy) && nearly_equal(u.gy, v.gy) && + nearly_equal(u.bx, v.by) && nearly_equal(u.by, v.by); } bool ColorSpace::nearlyEqual(const ColorSpace& that) const @@ -145,8 +132,7 @@ bool ColorSpace::nearlyEqual(const ColorSpace& that) const return false; if (m_type == None) return true; - if (m_type == sRGB || - m_type == RGB) { + if (m_type == sRGB || m_type == RGB) { // Gamma if (has(HasGamma) && that.has(HasGamma)) { if (!nearly_equal(gamma(), that.gamma())) diff --git a/gfx/color_space.h b/gfx/color_space.h index fe315d899..73b2ae25f 100644 --- a/gfx/color_space.h +++ b/gfx/color_space.h @@ -20,110 +20,106 @@ namespace gfx { - class ColorSpace; - using ColorSpaceRef = base::Ref; - - // Gamut white point and primaries as in Skia's SkColorSpacePrimaries. - struct ColorSpacePrimaries { - float rx, ry, gx, gy, bx, by; // Red/Green/Blue XY - float wx, wy; // White point XY - }; - - // Transfer coefficients as in Skia's skcms_TransferFunction, to - // transform from a curved space to linear: - // - // LinearVal = C*InputVal + F , for 0.0f <= InputVal < D - // LinearVal = (A*InputVal + B)^G + E, for D <= InputVal <= 1.0f - // - struct ColorSpaceTransferFn { - float g, a, b, c, d, e, f; - }; - - class ColorSpace : public base::RefCountT { - public: - enum Type { None, - sRGB, - RGB, - ICC }; - - enum Flag { NoFlags = 0, - HasGamma = 1, - HasTransferFn = 2, - HasPrimaries = 4, - HasICC = 8 }; - - ColorSpace(Type type, - Flag flags = NoFlags, - float gamma = 1.0, - std::vector&& rawData = std::vector()); - - static ColorSpaceRef MakeNone(); // Use display color space - static ColorSpaceRef MakeSRGB(); - static ColorSpaceRef MakeLinearSRGB(); - static ColorSpaceRef MakeSRGBWithGamma(float gamma); - static ColorSpaceRef MakeRGB(const ColorSpaceTransferFn& fn, - const ColorSpacePrimaries& p); - static ColorSpaceRef MakeRGBWithSRGBGamut(const ColorSpaceTransferFn& fn); - static ColorSpaceRef MakeRGBWithSRGBGamma(const ColorSpacePrimaries& p); - static ColorSpaceRef MakeICC(const void* data, size_t n); - static ColorSpaceRef MakeICC(std::vector&& data); - - Type type() const { return m_type; } - Flag flags() const { return m_flags; } - - const std::string& name() const { return m_name; } - void setName(const std::string& name) { m_name = name; } - - float gamma() const { return m_gamma; } - - bool hasGamma() const { return has(HasGamma); } - bool hasTransferFn() const { return has(HasTransferFn); } - bool hasPrimaries() const { return has(HasPrimaries); } - - size_t iccSize() const { - if (has(HasICC)) - return m_data.size(); - return 0; - } +class ColorSpace; +using ColorSpaceRef = base::Ref; - const void* iccData() const { - if (has(HasICC)) - return m_data.data(); - return nullptr; - } +// Gamut white point and primaries as in Skia's SkColorSpacePrimaries. +struct ColorSpacePrimaries { + float rx, ry, gx, gy, bx, by; // Red/Green/Blue XY + float wx, wy; // White point XY +}; - const ColorSpaceTransferFn* transferFn() const { +// Transfer coefficients as in Skia's skcms_TransferFunction, to +// transform from a curved space to linear: +// +// LinearVal = C*InputVal + F , for 0.0f <= InputVal < D +// LinearVal = (A*InputVal + B)^G + E, for D <= InputVal <= 1.0f +// +struct ColorSpaceTransferFn { + float g, a, b, c, d, e, f; +}; + +class ColorSpace : public base::RefCountT { +public: + enum Type { None, sRGB, RGB, ICC }; + + enum Flag { NoFlags = 0, HasGamma = 1, HasTransferFn = 2, HasPrimaries = 4, HasICC = 8 }; + + ColorSpace(Type type, + Flag flags = NoFlags, + float gamma = 1.0, + std::vector&& rawData = std::vector()); + + static ColorSpaceRef MakeNone(); // Use display color space + static ColorSpaceRef MakeSRGB(); + static ColorSpaceRef MakeLinearSRGB(); + static ColorSpaceRef MakeSRGBWithGamma(float gamma); + static ColorSpaceRef MakeRGB(const ColorSpaceTransferFn& fn, const ColorSpacePrimaries& p); + static ColorSpaceRef MakeRGBWithSRGBGamut(const ColorSpaceTransferFn& fn); + static ColorSpaceRef MakeRGBWithSRGBGamma(const ColorSpacePrimaries& p); + static ColorSpaceRef MakeICC(const void* data, size_t n); + static ColorSpaceRef MakeICC(std::vector&& data); + + Type type() const { return m_type; } + Flag flags() const { return m_flags; } + + const std::string& name() const { return m_name; } + void setName(const std::string& name) { m_name = name; } + + float gamma() const { return m_gamma; } + + bool hasGamma() const { return has(HasGamma); } + bool hasTransferFn() const { return has(HasTransferFn); } + bool hasPrimaries() const { return has(HasPrimaries); } + + size_t iccSize() const + { + if (has(HasICC)) + return m_data.size(); + return 0; + } + + const void* iccData() const + { + if (has(HasICC)) + return m_data.data(); + return nullptr; + } + + const ColorSpaceTransferFn* transferFn() const + { + if (has(HasTransferFn)) + return (const ColorSpaceTransferFn*)m_data.data(); + return nullptr; + } + + const ColorSpacePrimaries* primaries() const + { + if (has(HasPrimaries)) { if (has(HasTransferFn)) - return (const ColorSpaceTransferFn*)m_data.data(); - return nullptr; - } - - const ColorSpacePrimaries* primaries() const { - if (has(HasPrimaries)) { - if (has(HasTransferFn)) - return (const ColorSpacePrimaries*)&m_data[sizeof(ColorSpaceTransferFn)]; - return (const ColorSpacePrimaries*)m_data.data(); - } - return nullptr; + return (const ColorSpacePrimaries*)&m_data[sizeof(ColorSpaceTransferFn)]; + return (const ColorSpacePrimaries*)m_data.data(); } - - bool operator==(const ColorSpace& that) const = delete; - bool operator!=(const ColorSpace& that) const = delete; - bool nearlyEqual(const ColorSpace& that) const; - - // This data can be used - const std::vector& rawData() const { return m_data; } - - private: - bool has(const Flag flag) const { return (m_flags & int(flag)) == int(flag); } - - Type m_type; - Flag m_flags; - std::string m_name; - float m_gamma = 1.0f; - // ColorSpacePrimaries + ColorSpaceTransferFn or raw ICC profile data - std::vector m_data; - }; + return nullptr; + } + + bool operator==(const ColorSpace& that) const = delete; + bool operator!=(const ColorSpace& that) const = delete; + bool nearlyEqual(const ColorSpace& that) const; + + // This data can be used + const std::vector& rawData() const { return m_data; } + +private: + bool has(const Flag flag) const { return (m_flags & int(flag)) == int(flag); } + + Type m_type; + Flag m_flags; + std::string m_name; + float m_gamma = 1.0f; + // ColorSpacePrimaries + ColorSpaceTransferFn or raw ICC profile data + std::vector m_data; +}; } // namespace gfx diff --git a/gfx/fwd.h b/gfx/fwd.h index 3a05f6493..c5ed4031c 100644 --- a/gfx/fwd.h +++ b/gfx/fwd.h @@ -10,11 +10,16 @@ namespace gfx { -template class BorderT; -template class ClipT; -template class PointT; -template class RectT; -template class SizeT; +template +class BorderT; +template +class ClipT; +template +class PointT; +template +class RectT; +template +class SizeT; typedef BorderT Border; typedef ClipT Clip; diff --git a/gfx/hsl.cpp b/gfx/hsl.cpp index d4d1d2d20..d4a808142 100644 --- a/gfx/hsl.cpp +++ b/gfx/hsl.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/hsl.h" @@ -23,7 +23,8 @@ Hsl::Hsl(double hue, double saturation, double lightness) : m_hue(hue) , m_saturation(std::clamp(saturation, 0.0, 1.0)) , m_lightness(std::clamp(lightness, 0.0, 1.0)) -{ } +{ +} Hsl::Hsl(const Rgb& rgb) { @@ -40,9 +41,9 @@ Hsl::Hsl(const Rgb& rgb) s = 0.0; } else { - const double r = double(rgb.red()) / 255.0; + const double r = double(rgb.red()) / 255.0; const double g = double(rgb.green()) / 255.0; - const double b = double(rgb.blue()) / 255.0; + const double b = double(rgb.blue()) / 255.0; if (M == rgb.red()) { hue_prime = (g - b) / chroma; @@ -59,7 +60,7 @@ Hsl::Hsl(const Rgb& rgb) } h = hue_prime * 60.0; - s = chroma / (1-std::fabs(2.0*l-1.0)); + s = chroma / (1 - std::fabs(2.0 * l - 1.0)); } m_hue = h; @@ -74,12 +75,12 @@ int Hsl::hueInt() const int Hsl::saturationInt() const { - return int(std::floor(m_saturation*100.0 + 0.5)); + return int(std::floor(m_saturation * 100.0 + 0.5)); } int Hsl::lightnessInt() const { - return int(std::floor(m_lightness*100.0 + 0.5)); + return int(std::floor(m_lightness * 100.0 + 0.5)); } } // namespace gfx diff --git a/gfx/hsl.h b/gfx/hsl.h index 55b7eb80d..e63a87560 100644 --- a/gfx/hsl.h +++ b/gfx/hsl.h @@ -18,11 +18,7 @@ class Rgb; class Hsl { public: - Hsl() - : m_hue(0.0) - , m_saturation(0.0) - , m_lightness(0.0) - { } + Hsl() : m_hue(0.0), m_saturation(0.0), m_lightness(0.0) {} Hsl(double hue, double saturation, double lightness); @@ -30,7 +26,8 @@ class Hsl { : m_hue(hsl.hue()) , m_saturation(hsl.saturation()) , m_lightness(hsl.lightness()) - { } + { + } // RGB to HSL conversion explicit Hsl(const Rgb& rgb); @@ -49,29 +46,25 @@ class Hsl { int saturationInt() const; int lightnessInt() const; - void hue(double hue) { - while (hue < 0.0) hue += 360.0; + void hue(double hue) + { + while (hue < 0.0) + hue += 360.0; m_hue = std::fmod(hue, 360.0); } - void saturation(double saturation) { - m_saturation = std::clamp(saturation, 0.0, 1.0); - } + void saturation(double saturation) { m_saturation = std::clamp(saturation, 0.0, 1.0); } - void lightness(double lightness) { - m_lightness = std::clamp(lightness, 0.0, 1.0); - } + void lightness(double lightness) { m_lightness = std::clamp(lightness, 0.0, 1.0); } // The comparison is done through the integer value of each component. - bool operator==(const Hsl& other) const { - return (hueInt() == other.hueInt() && - saturationInt() == other.saturationInt() && + bool operator==(const Hsl& other) const + { + return (hueInt() == other.hueInt() && saturationInt() == other.saturationInt() && lightnessInt() == other.lightnessInt()); } - bool operator!=(const Hsl& other) const { - return !operator==(other); - } + bool operator!=(const Hsl& other) const { return !operator==(other); } private: double m_hue; diff --git a/gfx/hsl_tests.cpp b/gfx/hsl_tests.cpp index 7a7753d68..f63b9d8ad 100644 --- a/gfx/hsl_tests.cpp +++ b/gfx/hsl_tests.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -18,19 +18,15 @@ using namespace std; namespace gfx { - ostream& operator<<(ostream& os, const Hsl& hsl) - { - return os << "(" - << hsl.hueInt() << ", " - << hsl.saturationInt() << ", " - << hsl.lightnessInt() << "); real: (" - << hsl.hue() << ", " - << hsl.saturation() << ", " - << hsl.lightness() << ")"; - } - +ostream& operator<<(ostream& os, const Hsl& hsl) +{ + return os << "(" << hsl.hueInt() << ", " << hsl.saturationInt() << ", " << hsl.lightnessInt() + << "); real: (" << hsl.hue() << ", " << hsl.saturation() << ", " << hsl.lightness() + << ")"; } +} // namespace gfx + TEST(Hsl, Ctor) { EXPECT_EQ(35.0, Hsl(35.0, 0.50, 0.75).hue()); @@ -44,19 +40,19 @@ TEST(Hsl, Ctor) TEST(Hsl, FromRgb) { - EXPECT_EQ(Hsl( 0.0, 0.00, 0.00), Hsl(Rgb( 0, 0, 0))); - EXPECT_EQ(Hsl( 0.0, 1.00, 0.01), Hsl(Rgb( 3, 0, 0))); - EXPECT_EQ(Hsl( 0.0, 1.00, 0.99), Hsl(Rgb(255, 250, 250))); - EXPECT_EQ(Hsl( 0.0, 0.66, 0.50), Hsl(Rgb(212, 43, 43))); - EXPECT_EQ(Hsl( 60.0, 1.00, 0.75), Hsl(Rgb(255, 255, 128))); - EXPECT_EQ(Hsl(120.0, 1.00, 0.50), Hsl(Rgb( 0, 255, 0))); - EXPECT_EQ(Hsl( 0.0, 0.00, 1.00), Hsl(Rgb(255, 255, 255))); - EXPECT_EQ(Hsl(180.0, 0.50, 0.50), Hsl(Rgb( 64, 191, 191))); + EXPECT_EQ(Hsl(0.0, 0.00, 0.00), Hsl(Rgb(0, 0, 0))); + EXPECT_EQ(Hsl(0.0, 1.00, 0.01), Hsl(Rgb(3, 0, 0))); + EXPECT_EQ(Hsl(0.0, 1.00, 0.99), Hsl(Rgb(255, 250, 250))); + EXPECT_EQ(Hsl(0.0, 0.66, 0.50), Hsl(Rgb(212, 43, 43))); + EXPECT_EQ(Hsl(60.0, 1.00, 0.75), Hsl(Rgb(255, 255, 128))); + EXPECT_EQ(Hsl(120.0, 1.00, 0.50), Hsl(Rgb(0, 255, 0))); + EXPECT_EQ(Hsl(0.0, 0.00, 1.00), Hsl(Rgb(255, 255, 255))); + EXPECT_EQ(Hsl(180.0, 0.50, 0.50), Hsl(Rgb(64, 191, 191))); EXPECT_EQ(Hsl(240.0, 0.50, 0.75), Hsl(Rgb(159, 159, 223))); - EXPECT_EQ(Hsl(240.0, 1.00, 0.25), Hsl(Rgb( 0, 0, 128))); + EXPECT_EQ(Hsl(240.0, 1.00, 0.25), Hsl(Rgb(0, 0, 128))); EXPECT_EQ(Hsl(300.0, 0.66, 0.75), Hsl(Rgb(233, 149, 233))); - EXPECT_EQ(Hsl( 0.0, 1.00, 0.66), Hsl(Rgb(255, 82, 82))); - EXPECT_EQ(Hsl( 0.0, 1.00, 0.67), Hsl(Rgb(255, 87, 87))); + EXPECT_EQ(Hsl(0.0, 1.00, 0.66), Hsl(Rgb(255, 82, 82))); + EXPECT_EQ(Hsl(0.0, 1.00, 0.67), Hsl(Rgb(255, 87, 87))); } int main(int argc, char** argv) diff --git a/gfx/hsv.cpp b/gfx/hsv.cpp index a14fbbd3f..cc8c48b60 100644 --- a/gfx/hsv.cpp +++ b/gfx/hsv.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/hsv.h" @@ -22,7 +22,8 @@ Hsv::Hsv(double hue, double saturation, double value) : m_hue(hue) , m_saturation(std::clamp(saturation, 0.0, 1.0)) , m_value(std::clamp(value, 0.0, 1.0)) -{ } +{ +} // Reference: http://en.wikipedia.org/wiki/HSL_and_HSV Hsv::Hsv(const Rgb& rgb) @@ -40,9 +41,9 @@ Hsv::Hsv(const Rgb& rgb) s = 0.0; } else { - const double r = double(rgb.red()) / 255.0; + const double r = double(rgb.red()) / 255.0; const double g = double(rgb.green()) / 255.0; - const double b = double(rgb.blue()) / 255.0; + const double b = double(rgb.blue()) / 255.0; if (M == rgb.red()) { hue_prime = (g - b) / chroma; @@ -74,12 +75,12 @@ int Hsv::hueInt() const int Hsv::saturationInt() const { - return int(std::floor(m_saturation*100.0 + 0.5)); + return int(std::floor(m_saturation * 100.0 + 0.5)); } int Hsv::valueInt() const { - return int(std::floor(m_value*100.0 + 0.5)); + return int(std::floor(m_value * 100.0 + 0.5)); } } // namespace gfx diff --git a/gfx/hsv.h b/gfx/hsv.h index 5a39d4eeb..b344bf7a8 100644 --- a/gfx/hsv.h +++ b/gfx/hsv.h @@ -18,19 +18,11 @@ class Rgb; class Hsv { public: - Hsv() - : m_hue(0.0) - , m_saturation(0.0) - , m_value(0.0) - { } + Hsv() : m_hue(0.0), m_saturation(0.0), m_value(0.0) {} Hsv(double hue, double saturation, double value); - Hsv(const Hsv& hsv) - : m_hue(hsv.hue()) - , m_saturation(hsv.saturation()) - , m_value(hsv.value()) - { } + Hsv(const Hsv& hsv) : m_hue(hsv.hue()), m_saturation(hsv.saturation()), m_value(hsv.value()) {} // RGB to HSV conversion explicit Hsv(const Rgb& rgb); @@ -49,29 +41,25 @@ class Hsv { int saturationInt() const; int valueInt() const; - void hue(double hue) { - while (hue < 0.0) hue += 360.0; + void hue(double hue) + { + while (hue < 0.0) + hue += 360.0; m_hue = std::fmod(hue, 360.0); } - void saturation(double saturation) { - m_saturation = std::clamp(saturation, 0.0, 1.0); - } + void saturation(double saturation) { m_saturation = std::clamp(saturation, 0.0, 1.0); } - void value(double value) { - m_value = std::clamp(value, 0.0, 1.0); - } + void value(double value) { m_value = std::clamp(value, 0.0, 1.0); } // The comparison is done through the integer value of each component. - bool operator==(const Hsv& other) const { - return (hueInt() == other.hueInt() && - saturationInt() == other.saturationInt() && + bool operator==(const Hsv& other) const + { + return (hueInt() == other.hueInt() && saturationInt() == other.saturationInt() && valueInt() == other.valueInt()); } - bool operator!=(const Hsv& other) const { - return !operator==(other); - } + bool operator!=(const Hsv& other) const { return !operator==(other); } private: double m_hue; diff --git a/gfx/hsv_tests.cpp b/gfx/hsv_tests.cpp index b09b156d8..8d66ca35a 100644 --- a/gfx/hsv_tests.cpp +++ b/gfx/hsv_tests.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -18,19 +18,14 @@ using namespace std; namespace gfx { - ostream& operator<<(ostream& os, const Hsv& hsv) - { - return os << "(" - << hsv.hueInt() << ", " - << hsv.saturationInt() << ", " - << hsv.valueInt() << "); real: (" - << hsv.hue() << ", " - << hsv.saturation() << ", " - << hsv.value() << ")"; - } - +ostream& operator<<(ostream& os, const Hsv& hsv) +{ + return os << "(" << hsv.hueInt() << ", " << hsv.saturationInt() << ", " << hsv.valueInt() + << "); real: (" << hsv.hue() << ", " << hsv.saturation() << ", " << hsv.value() << ")"; } +} // namespace gfx + TEST(Hsv, Ctor) { EXPECT_EQ(35.0, Hsv(35.0, 0.50, 0.75).hue()); @@ -44,19 +39,19 @@ TEST(Hsv, Ctor) TEST(Hsv, FromRgb) { - EXPECT_EQ(Hsv( 0.0, 0.00, 0.00), Hsv(Rgb( 0, 0, 0))); - EXPECT_EQ(Hsv( 0.0, 1.00, 0.01), Hsv(Rgb( 3, 0, 0))); - EXPECT_EQ(Hsv( 0.0, 1.00, 0.99), Hsv(Rgb(252, 0, 0))); - EXPECT_EQ(Hsv( 0.0, 1.00, 1.00), Hsv(Rgb(255, 0, 0))); - EXPECT_EQ(Hsv( 60.0, 1.00, 0.75), Hsv(Rgb(191, 191, 0))); - EXPECT_EQ(Hsv(120.0, 1.00, 0.50), Hsv(Rgb( 0, 128, 0))); - EXPECT_EQ(Hsv(120.0, 1.00, 1.00), Hsv(Rgb( 0, 255, 0))); + EXPECT_EQ(Hsv(0.0, 0.00, 0.00), Hsv(Rgb(0, 0, 0))); + EXPECT_EQ(Hsv(0.0, 1.00, 0.01), Hsv(Rgb(3, 0, 0))); + EXPECT_EQ(Hsv(0.0, 1.00, 0.99), Hsv(Rgb(252, 0, 0))); + EXPECT_EQ(Hsv(0.0, 1.00, 1.00), Hsv(Rgb(255, 0, 0))); + EXPECT_EQ(Hsv(60.0, 1.00, 0.75), Hsv(Rgb(191, 191, 0))); + EXPECT_EQ(Hsv(120.0, 1.00, 0.50), Hsv(Rgb(0, 128, 0))); + EXPECT_EQ(Hsv(120.0, 1.00, 1.00), Hsv(Rgb(0, 255, 0))); EXPECT_EQ(Hsv(180.0, 0.50, 1.00), Hsv(Rgb(128, 255, 255))); EXPECT_EQ(Hsv(240.0, 0.50, 1.00), Hsv(Rgb(128, 128, 255))); - EXPECT_EQ(Hsv(240.0, 1.00, 1.00), Hsv(Rgb( 0, 0, 255))); - EXPECT_EQ(Hsv(300.0, 0.66, 0.75), Hsv(Rgb(191, 64, 191))); - EXPECT_EQ(Hsv( 0.0, 1.00, 0.99), Hsv(Rgb(252, 0, 0))); - EXPECT_EQ(Hsv( 0.0, 1.00, 1.00), Hsv(Rgb(255, 0, 0))); + EXPECT_EQ(Hsv(240.0, 1.00, 1.00), Hsv(Rgb(0, 0, 255))); + EXPECT_EQ(Hsv(300.0, 0.66, 0.75), Hsv(Rgb(191, 64, 191))); + EXPECT_EQ(Hsv(0.0, 1.00, 0.99), Hsv(Rgb(252, 0, 0))); + EXPECT_EQ(Hsv(0.0, 1.00, 1.00), Hsv(Rgb(255, 0, 0))); } int main(int argc, char** argv) diff --git a/gfx/matrix_none.h b/gfx/matrix_none.h index 5f140f6b5..3ac912ad3 100644 --- a/gfx/matrix_none.h +++ b/gfx/matrix_none.h @@ -12,49 +12,56 @@ namespace gfx { - class Matrix { - public: - Matrix() { } - - static Matrix MakeScale(float sx, float sy) { return Matrix(); } - static Matrix MakeScale(float scale) { return Matrix(); } - static Matrix MakeTrans(float x, float y) { return Matrix(); } - static Matrix MakeAll(float scaleX, float skewX, float transX, - float skewY, float scaleY, float transY, - float pers0, float pers1, float pers2) { - return Matrix(); - } - - Matrix& reset() { return *this; } - bool isIdentity() const { return true; } - bool isScaleTranslate() const { return false; } - bool isTranslate() const { return false; } - - float getScaleX() const { return 1.0f; } - float getScaleY() const { return 1.0f; } - float getSkewY() const { return 0.0f; } - float getSkewX() const { return 0.0f; } - float getTranslateX() const { return 0.0f; } - float getTranslateY() const { return 0.0f; } - float getPerspX() const { return 0.0f; } - float getPerspY() const { return 0.0f; } - - Matrix& setIdentity() { return *this; } - Matrix& setTranslate(float dx, float dy) { return *this; } - void setScale(float sx, float sy, float px, float py) { } - void setScale(float sx, float sy) { } - void setRotate(float degrees, float px, float py) { } - void setRotate(float degrees) { } - void setScaleTranslate(float sx, float sy, float tx, float ty) { } - Matrix& preTranslate(float dx, float dy) { return *this; } - Matrix& postTranslate(float dx, float dy) { return *this; } - - Matrix& setConcat(const Matrix& a, const Matrix& b) { return *this; } - Matrix& preConcat(const Matrix& other) { return *this; } - Matrix& postConcat(const Matrix& other) { return *this; } - - RectF mapRect(const RectF& src) const { return RectF(); } - }; +class Matrix { +public: + Matrix() {} + + static Matrix MakeScale(float sx, float sy) { return Matrix(); } + static Matrix MakeScale(float scale) { return Matrix(); } + static Matrix MakeTrans(float x, float y) { return Matrix(); } + static Matrix MakeAll(float scaleX, + float skewX, + float transX, + float skewY, + float scaleY, + float transY, + float pers0, + float pers1, + float pers2) + { + return Matrix(); + } + + Matrix& reset() { return *this; } + bool isIdentity() const { return true; } + bool isScaleTranslate() const { return false; } + bool isTranslate() const { return false; } + + float getScaleX() const { return 1.0f; } + float getScaleY() const { return 1.0f; } + float getSkewY() const { return 0.0f; } + float getSkewX() const { return 0.0f; } + float getTranslateX() const { return 0.0f; } + float getTranslateY() const { return 0.0f; } + float getPerspX() const { return 0.0f; } + float getPerspY() const { return 0.0f; } + + Matrix& setIdentity() { return *this; } + Matrix& setTranslate(float dx, float dy) { return *this; } + void setScale(float sx, float sy, float px, float py) {} + void setScale(float sx, float sy) {} + void setRotate(float degrees, float px, float py) {} + void setRotate(float degrees) {} + void setScaleTranslate(float sx, float sy, float tx, float ty) {} + Matrix& preTranslate(float dx, float dy) { return *this; } + Matrix& postTranslate(float dx, float dy) { return *this; } + + Matrix& setConcat(const Matrix& a, const Matrix& b) { return *this; } + Matrix& preConcat(const Matrix& other) { return *this; } + Matrix& postConcat(const Matrix& other) { return *this; } + + RectF mapRect(const RectF& src) const { return RectF(); } +}; } // namespace gfx diff --git a/gfx/matrix_skia.h b/gfx/matrix_skia.h index 562beae14..b083e2eb5 100644 --- a/gfx/matrix_skia.h +++ b/gfx/matrix_skia.h @@ -15,118 +15,121 @@ namespace gfx { - // Simple wrapper for SkMatrix - class Matrix { - public: - constexpr Matrix() { } - constexpr Matrix(const SkMatrix& skMatrix) : m_skMatrix(skMatrix) { } - - static Matrix MakeScale(float sx, float sy) { - return Matrix(SkMatrix::Scale(sx, sy)); - } - - static Matrix MakeScale(float scale) { - return Matrix(SkMatrix::Scale(scale, scale)); - } - - static Matrix MakeTrans(float x, float y) { - return Matrix(SkMatrix::Translate(x, y)); - } - - static Matrix MakeAll(float scaleX, float skewX, float transX, - float skewY, float scaleY, float transY, - float pers0, float pers1, float pers2) { - return Matrix(SkMatrix::MakeAll(scaleX, skewX, transX, - skewY, scaleY, transY, - pers0, pers1, pers2)); - } - - Matrix& reset() { - m_skMatrix.reset(); - return *this; - } - - bool isIdentity() const { return m_skMatrix.isIdentity(); } - bool isScaleTranslate() const { return m_skMatrix.isScaleTranslate(); } - bool isTranslate() const { return m_skMatrix.isTranslate(); } - - float getScaleX() const { return m_skMatrix.getScaleX(); } - float getScaleY() const { return m_skMatrix.getScaleY(); } - float getSkewY() const { return m_skMatrix.getSkewY(); } - float getSkewX() const { return m_skMatrix.getSkewX(); } - float getTranslateX() const { return m_skMatrix.getTranslateX(); } - float getTranslateY() const { return m_skMatrix.getTranslateY(); } - float getPerspX() const { return m_skMatrix.getPerspX(); } - float getPerspY() const { return m_skMatrix.getPerspY(); } - - Matrix& setIdentity() { - m_skMatrix.setIdentity(); - return *this; - } - - Matrix& setTranslate(float dx, float dy) { - m_skMatrix.setTranslate(dx, dy); - return *this; - } - - void setScale(float sx, float sy, float px, float py) { - m_skMatrix.setScale(sx, sy, px, py); - } - - void setScale(float sx, float sy) { - m_skMatrix.setScale(sx, sy); - } - - void setRotate(float degrees, float px, float py) { - m_skMatrix.setRotate(degrees, px, py); - } - - void setRotate(float degrees) { - m_skMatrix.setRotate(degrees); - } - - void setScaleTranslate(float sx, float sy, float tx, float ty) { - m_skMatrix.setScaleTranslate(sx, sy, tx, ty); - } - - Matrix& preTranslate(float dx, float dy) { - m_skMatrix.preTranslate(dx, dy); - return *this; - } - - Matrix& postTranslate(float dx, float dy) { - m_skMatrix.postTranslate(dx, dy); - return *this; - } - - Matrix& setConcat(const Matrix& a, const Matrix& b) { - m_skMatrix.setConcat(a.m_skMatrix, b.m_skMatrix); - return *this; - } - - Matrix& preConcat(const Matrix& other) { - m_skMatrix.preConcat(other.m_skMatrix); - return *this; - } - - Matrix& postConcat(const Matrix& other) { - m_skMatrix.postConcat(other.m_skMatrix); - return *this; - } - - RectF mapRect(const RectF& src) const { - SkRect dst; - m_skMatrix.mapRect(&dst, SkRect::MakeXYWH(SkScalar(src.x), SkScalar(src.y), - SkScalar(src.w), SkScalar(src.h))); - return RectF(dst.x(), dst.y(), dst.width(), dst.height()); - } - - const SkMatrix& skMatrix() const { return m_skMatrix; } - SkMatrix& skMatrix() { return m_skMatrix; } - - private: - SkMatrix m_skMatrix; - }; +// Simple wrapper for SkMatrix +class Matrix { +public: + constexpr Matrix() {} + constexpr Matrix(const SkMatrix& skMatrix) : m_skMatrix(skMatrix) {} + + static Matrix MakeScale(float sx, float sy) { return Matrix(SkMatrix::Scale(sx, sy)); } + + static Matrix MakeScale(float scale) { return Matrix(SkMatrix::Scale(scale, scale)); } + + static Matrix MakeTrans(float x, float y) { return Matrix(SkMatrix::Translate(x, y)); } + + static Matrix MakeAll(float scaleX, + float skewX, + float transX, + float skewY, + float scaleY, + float transY, + float pers0, + float pers1, + float pers2) + { + return Matrix( + SkMatrix::MakeAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2)); + } + + Matrix& reset() + { + m_skMatrix.reset(); + return *this; + } + + bool isIdentity() const { return m_skMatrix.isIdentity(); } + bool isScaleTranslate() const { return m_skMatrix.isScaleTranslate(); } + bool isTranslate() const { return m_skMatrix.isTranslate(); } + + float getScaleX() const { return m_skMatrix.getScaleX(); } + float getScaleY() const { return m_skMatrix.getScaleY(); } + float getSkewY() const { return m_skMatrix.getSkewY(); } + float getSkewX() const { return m_skMatrix.getSkewX(); } + float getTranslateX() const { return m_skMatrix.getTranslateX(); } + float getTranslateY() const { return m_skMatrix.getTranslateY(); } + float getPerspX() const { return m_skMatrix.getPerspX(); } + float getPerspY() const { return m_skMatrix.getPerspY(); } + + Matrix& setIdentity() + { + m_skMatrix.setIdentity(); + return *this; + } + + Matrix& setTranslate(float dx, float dy) + { + m_skMatrix.setTranslate(dx, dy); + return *this; + } + + void setScale(float sx, float sy, float px, float py) { m_skMatrix.setScale(sx, sy, px, py); } + + void setScale(float sx, float sy) { m_skMatrix.setScale(sx, sy); } + + void setRotate(float degrees, float px, float py) { m_skMatrix.setRotate(degrees, px, py); } + + void setRotate(float degrees) { m_skMatrix.setRotate(degrees); } + + void setScaleTranslate(float sx, float sy, float tx, float ty) + { + m_skMatrix.setScaleTranslate(sx, sy, tx, ty); + } + + Matrix& preTranslate(float dx, float dy) + { + m_skMatrix.preTranslate(dx, dy); + return *this; + } + + Matrix& postTranslate(float dx, float dy) + { + m_skMatrix.postTranslate(dx, dy); + return *this; + } + + Matrix& setConcat(const Matrix& a, const Matrix& b) + { + m_skMatrix.setConcat(a.m_skMatrix, b.m_skMatrix); + return *this; + } + + Matrix& preConcat(const Matrix& other) + { + m_skMatrix.preConcat(other.m_skMatrix); + return *this; + } + + Matrix& postConcat(const Matrix& other) + { + m_skMatrix.postConcat(other.m_skMatrix); + return *this; + } + + RectF mapRect(const RectF& src) const + { + SkRect dst; + m_skMatrix.mapRect( + &dst, + SkRect::MakeXYWH(SkScalar(src.x), SkScalar(src.y), SkScalar(src.w), SkScalar(src.h))); + return RectF(dst.x(), dst.y(), dst.width(), dst.height()); + } + + const SkMatrix& skMatrix() const { return m_skMatrix; } + SkMatrix& skMatrix() { return m_skMatrix; } + +private: + SkMatrix m_skMatrix; +}; } // namespace gfx diff --git a/gfx/packing_rects.cpp b/gfx/packing_rects.cpp index 653ee4857..3850adb73 100644 --- a/gfx/packing_rects.cpp +++ b/gfx/packing_rects.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/packing_rects.h" @@ -26,9 +26,7 @@ void PackingRects::add(const Rect& rc) m_rects.push_back(rc); } -Size PackingRects::bestFit(base::task_token& token, - const int fixedWidth, - const int fixedHeight) +Size PackingRects::bestFit(base::task_token& token, const int fixedWidth, const int fixedHeight) { Size size(fixedWidth, fixedHeight); @@ -51,9 +49,8 @@ Size PackingRects::bestFit(base::task_token& token, int z = 0; bool fit = false; while (!token.canceled()) { - if (w*h >= neededArea) { - const Size sizeCandidate = Size(w + 2 * m_borderPadding, - h + 2 * m_borderPadding); + if (w * h >= neededArea) { + const Size sizeCandidate = Size(w + 2 * m_borderPadding, h + 2 * m_borderPadding); fit = pack(sizeCandidate, token); if (fit) { size = sizeCandidate; @@ -78,12 +75,12 @@ Size PackingRects::bestFit(base::task_token& token, return size; } -static bool by_area(const Rect* a, const Rect* b) { - return a->w*a->h > b->w*b->h; +static bool by_area(const Rect* a, const Rect* b) +{ + return a->w * a->h > b->w * b->h; } -bool PackingRects::pack(const Size& size, - base::task_token& token) +bool PackingRects::pack(const Size& size, base::task_token& token) { m_bounds = Rect(size).shrink(m_borderPadding); @@ -106,8 +103,7 @@ bool PackingRects::pack(const Size& size, // The rectangles are treated as its original size + // conditional extra border of during placement. for (int v = 0; v <= m_bounds.h - rc.h; ++v) { - const int hShapePadding = - (v == (m_bounds.h - rc.h) ? 0 : m_shapePadding); + const int hShapePadding = (v == (m_bounds.h - rc.h) ? 0 : m_shapePadding); for (int u = 0; u <= m_bounds.w - rc.w; ++u) { if (token.canceled()) return false; @@ -119,13 +115,11 @@ bool PackingRects::pack(const Size& size, // This fix resolves the special cases of exporting with // sheet type 'Packed' + 'Trim Cels' true + // 'Shape padding' > 0 + series of particular image sizes. - const int wShapePadding = - (u == (m_bounds.w - rc.w) ? 0 : m_shapePadding); - const gfx::Rect possible( - m_bounds.x + u, - m_bounds.y + v, - rc.w + wShapePadding, - rc.h + hShapePadding); + const int wShapePadding = (u == (m_bounds.w - rc.w) ? 0 : m_shapePadding); + const gfx::Rect possible(m_bounds.x + u, + m_bounds.y + v, + rc.w + wShapePadding, + rc.h + hShapePadding); const Region::Overlap overlap = rgn.contains(possible); if (overlap == Region::In) { diff --git a/gfx/packing_rects.h b/gfx/packing_rects.h index 9e1f132d6..e2bd3807d 100644 --- a/gfx/packing_rects.h +++ b/gfx/packing_rects.h @@ -16,50 +16,48 @@ namespace gfx { - // TODO add support for rotations - class PackingRects { - public: - PackingRects(int borderPadding = 0, int shapePadding = 0) : - m_borderPadding(borderPadding), - m_shapePadding(shapePadding) { - } +// TODO add support for rotations +class PackingRects { +public: + PackingRects(int borderPadding = 0, int shapePadding = 0) + : m_borderPadding(borderPadding) + , m_shapePadding(shapePadding) + { + } - typedef std::vector Rects; - typedef Rects::const_iterator const_iterator; + typedef std::vector Rects; + typedef Rects::const_iterator const_iterator; - // Iterate over all given rectangles (in the same order they where - // given in addSize() calls). - const_iterator begin() const { return m_rects.begin(); } - const_iterator end() const { return m_rects.end(); } + // Iterate over all given rectangles (in the same order they where + // given in addSize() calls). + const_iterator begin() const { return m_rects.begin(); } + const_iterator end() const { return m_rects.end(); } - std::size_t size() const { return m_rects.size(); } - const Rect& operator[](int i) const { return m_rects[i]; } + std::size_t size() const { return m_rects.size(); } + const Rect& operator[](int i) const { return m_rects[i]; } - // Adds a new rectangle. - void add(const Size& sz); - void add(const Rect& rc); + // Adds a new rectangle. + void add(const Size& sz); + void add(const Rect& rc); - // Returns the best size for the texture. - Size bestFit(base::task_token& token, - const int fixedWidth = 0, - const int fixedHeight = 0); + // Returns the best size for the texture. + Size bestFit(base::task_token& token, const int fixedWidth = 0, const int fixedHeight = 0); - // Rearrange all given rectangles to best fit a texture size. - // Returns true if all rectangles were correctly arranged or false - // if there is not enough space. - bool pack(const Size& size, - base::task_token& token); + // Rearrange all given rectangles to best fit a texture size. + // Returns true if all rectangles were correctly arranged or false + // if there is not enough space. + bool pack(const Size& size, base::task_token& token); - // Returns the bounds of the packed area. - const Rect& bounds() const { return m_bounds; } + // Returns the bounds of the packed area. + const Rect& bounds() const { return m_bounds; } - private: - int m_borderPadding; - int m_shapePadding; +private: + int m_borderPadding; + int m_shapePadding; - Rect m_bounds; - Rects m_rects; - }; + Rect m_bounds; + Rects m_rects; +}; } // namespace gfx diff --git a/gfx/packing_rects_tests.cpp b/gfx/packing_rects_tests.cpp index 814c6e3f1..1332403db 100644 --- a/gfx/packing_rects_tests.cpp +++ b/gfx/packing_rects_tests.cpp @@ -6,16 +6,16 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include #if LAF_WITH_REGION -#include "gfx/packing_rects.h" -#include "gfx/rect_io.h" -#include "gfx/size.h" + #include "gfx/packing_rects.h" + #include "gfx/rect_io.h" + #include "gfx/size.h" using namespace gfx; @@ -120,7 +120,7 @@ TEST(PackingRects, BorderAndShapePadding) EXPECT_EQ(Rect(10, 216, 200, 100), pr[2]); } -#endif // LAF_WITH_REGION +#endif // LAF_WITH_REGION int main(int argc, char** argv) { diff --git a/gfx/path_none.h b/gfx/path_none.h index 888792b2a..10235b500 100644 --- a/gfx/path_none.h +++ b/gfx/path_none.h @@ -13,29 +13,29 @@ namespace gfx { - class Matrix; +class Matrix; - class Path { - public: - Path() { } - Path& reset() { return *this; } - Path& rewind() { return *this; } - bool isEmpty() const { return true; } - Path& moveTo(float x, float y) { return *this; } - Path& moveTo(const Point& p) { return *this; } - Path& lineTo(float x, float y) { return *this; } - Path& lineTo(const Point& p) { return *this; } - Path& cubicTo(float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { return *this; } - Path& oval(const Rect& rc) { return *this; } - Path& rect(const Rect& rc) { return *this; } - Path& roundedRect(const Rect& rc, float rx, float ry) { return *this; } - Path& close() { return *this; } - void offset(float dx, float dy, Path* dst) const { } - void offset(float dx, float dy) { } - void transform(const Matrix& matrix, Path* dst) { } - void transform(const Matrix& matrix) { } - RectF bounds() const { return RectF(); } - }; +class Path { +public: + Path() {} + Path& reset() { return *this; } + Path& rewind() { return *this; } + bool isEmpty() const { return true; } + Path& moveTo(float x, float y) { return *this; } + Path& moveTo(const Point& p) { return *this; } + Path& lineTo(float x, float y) { return *this; } + Path& lineTo(const Point& p) { return *this; } + Path& cubicTo(float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { return *this; } + Path& oval(const Rect& rc) { return *this; } + Path& rect(const Rect& rc) { return *this; } + Path& roundedRect(const Rect& rc, float rx, float ry) { return *this; } + Path& close() { return *this; } + void offset(float dx, float dy, Path* dst) const {} + void offset(float dx, float dy) {} + void transform(const Matrix& matrix, Path* dst) {} + void transform(const Matrix& matrix) {} + RectF bounds() const { return RectF(); } +}; } // namespace gfx diff --git a/gfx/path_skia.h b/gfx/path_skia.h index f96d00851..20f5c9fde 100644 --- a/gfx/path_skia.h +++ b/gfx/path_skia.h @@ -16,101 +16,106 @@ namespace gfx { - // Simple wrapper for SkPath - // TODO add missing methods for curves - class Path { - public: - Path() { } - - Path& reset() { - m_skPath.reset(); - return *this; - } - - Path& rewind() { - m_skPath.rewind(); - return *this; - } - - bool isEmpty() const { - return m_skPath.isEmpty(); - } - - Path& moveTo(float x, float y) { - m_skPath.moveTo(x, y); - return *this; - } - - Path& moveTo(const Point& p) { - m_skPath.moveTo(p.x, p.y); - return *this; - } - - Path& lineTo(float x, float y) { - m_skPath.lineTo(x, y); - return *this; - } - - Path& lineTo(const Point& p) { - m_skPath.lineTo(p.x, p.y); - return *this; - } - - Path& cubicTo(float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { - m_skPath.cubicTo(dx1, dy1, dx2, dy2, dx3, dy3); - return *this; - } - - Path& oval(const Rect& rc) { - m_skPath.addOval(SkRect::MakeXYWH(rc.x, rc.y, rc.w, rc.h)); - return *this; - } - - Path& rect(const Rect& rc) { - m_skPath.addRect(SkRect::MakeXYWH(rc.x, rc.y, rc.w, rc.h)); - return *this; - } - - Path& roundedRect(const Rect& rc, float rx, float ry) { - m_skPath.addRoundRect(SkRect::MakeXYWH(rc.x+0.5, rc.y+0.5, rc.w, rc.h), rx, ry); - return *this; - } - - Path& close() { - m_skPath.close(); - return *this; - } - - void offset(float dx, float dy, Path* dst) const { - m_skPath.offset(dx, dy, &dst->m_skPath); - } - - void offset(float dx, float dy) { - m_skPath.offset(dx, dy); - } - - void transform(const Matrix& matrix, Path* dst) { - m_skPath.transform(matrix.skMatrix(), &dst->m_skPath); - } - - void transform(const Matrix& matrix) { - m_skPath.transform(matrix.skMatrix()); - } - - RectF bounds() const { - if (isEmpty()) - return RectF(); - - SkRect rc = m_skPath.computeTightBounds(); - return RectF(rc.x(), rc.y(), rc.width(), rc.height()); - } - - const SkPath& skPath() const { return m_skPath; } - SkPath& skPath() { return m_skPath; } - - private: - SkPath m_skPath; - }; +// Simple wrapper for SkPath +// TODO add missing methods for curves +class Path { +public: + Path() {} + + Path& reset() + { + m_skPath.reset(); + return *this; + } + + Path& rewind() + { + m_skPath.rewind(); + return *this; + } + + bool isEmpty() const { return m_skPath.isEmpty(); } + + Path& moveTo(float x, float y) + { + m_skPath.moveTo(x, y); + return *this; + } + + Path& moveTo(const Point& p) + { + m_skPath.moveTo(p.x, p.y); + return *this; + } + + Path& lineTo(float x, float y) + { + m_skPath.lineTo(x, y); + return *this; + } + + Path& lineTo(const Point& p) + { + m_skPath.lineTo(p.x, p.y); + return *this; + } + + Path& cubicTo(float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) + { + m_skPath.cubicTo(dx1, dy1, dx2, dy2, dx3, dy3); + return *this; + } + + Path& oval(const Rect& rc) + { + m_skPath.addOval(SkRect::MakeXYWH(rc.x, rc.y, rc.w, rc.h)); + return *this; + } + + Path& rect(const Rect& rc) + { + m_skPath.addRect(SkRect::MakeXYWH(rc.x, rc.y, rc.w, rc.h)); + return *this; + } + + Path& roundedRect(const Rect& rc, float rx, float ry) + { + m_skPath.addRoundRect(SkRect::MakeXYWH(rc.x + 0.5, rc.y + 0.5, rc.w, rc.h), rx, ry); + return *this; + } + + Path& close() + { + m_skPath.close(); + return *this; + } + + void offset(float dx, float dy, Path* dst) const { m_skPath.offset(dx, dy, &dst->m_skPath); } + + void offset(float dx, float dy) { m_skPath.offset(dx, dy); } + + void transform(const Matrix& matrix, Path* dst) + { + m_skPath.transform(matrix.skMatrix(), &dst->m_skPath); + } + + void transform(const Matrix& matrix) { m_skPath.transform(matrix.skMatrix()); } + + RectF bounds() const + { + if (isEmpty()) + return RectF(); + + SkRect rc = m_skPath.computeTightBounds(); + return RectF(rc.x(), rc.y(), rc.width(), rc.height()); + } + + const SkPath& skPath() const { return m_skPath; } + SkPath& skPath() { return m_skPath; } + +private: + SkPath m_skPath; +}; } // namespace gfx diff --git a/gfx/point.h b/gfx/point.h index 8d70d79c3..5c927081c 100644 --- a/gfx/point.h +++ b/gfx/point.h @@ -20,107 +20,101 @@ class PointT { public: T x, y; - PointT() : x(0), y(0) { - } + PointT() : x(0), y(0) {} - PointT(const T& x, const T& y) : x(x), y(y) { - } + PointT(const T& x, const T& y) : x(x), y(y) {} - PointT(const PointT& point) : x(point.x), y(point.y) { - } + PointT(const PointT& point) : x(point.x), y(point.y) {} template - explicit PointT(const PointT& point) : x(static_cast(point.x)), - y(static_cast(point.y)) { + explicit PointT(const PointT& point) : x(static_cast(point.x)) + , y(static_cast(point.y)) + { } template - explicit PointT(const SizeT& size) : x(size.w), y(size.h) { + explicit PointT(const SizeT& size) : x(size.w) + , y(size.h) + { } template - PointT& operator=(const PointT& pt) { + PointT& operator=(const PointT& pt) + { x = pt.x; y = pt.y; return *this; } template - const PointT& operator+=(const PointT& pt) { + const PointT& operator+=(const PointT& pt) + { x += pt.x; y += pt.y; return *this; } template - const PointT& operator-=(const PointT& pt) { + const PointT& operator-=(const PointT& pt) + { x -= pt.x; y -= pt.y; return *this; } - const PointT& operator+=(const T& value) { + const PointT& operator+=(const T& value) + { x += value; y += value; return *this; } - const PointT& operator-=(const T& value) { + const PointT& operator-=(const T& value) + { x -= value; y -= value; return *this; } - const PointT& operator*=(const T& value) { + const PointT& operator*=(const T& value) + { x *= value; y *= value; return *this; } - const PointT& operator/=(const T& value) { + const PointT& operator/=(const T& value) + { x /= value; y /= value; return *this; } template - PointT operator+(const PointT& pt) const { - return PointT(x+pt.x, y+pt.y); + PointT operator+(const PointT& pt) const + { + return PointT(x + pt.x, y + pt.y); } template - PointT operator-(const PointT& pt) const { - return PointT(x-pt.x, y-pt.y); + PointT operator-(const PointT& pt) const + { + return PointT(x - pt.x, y - pt.y); } - PointT operator+(const T& value) const { - return PointT(x+value, y+value); - } + PointT operator+(const T& value) const { return PointT(x + value, y + value); } - PointT operator-(const T& value) const { - return PointT(x-value, y-value); - } + PointT operator-(const T& value) const { return PointT(x - value, y - value); } - PointT operator*(const T& value) const { - return PointT(x*value, y*value); - } + PointT operator*(const T& value) const { return PointT(x * value, y * value); } - PointT operator/(const T& value) const { - return PointT(x/value, y/value); - } + PointT operator/(const T& value) const { return PointT(x / value, y / value); } - PointT operator-() const { - return PointT(-x, -y); - } + PointT operator-() const { return PointT(-x, -y); } - bool operator==(const PointT& pt) const { - return x == pt.x && y == pt.y; - } - - bool operator!=(const PointT& pt) const { - return x != pt.x || y != pt.y; - } + bool operator==(const PointT& pt) const { return x == pt.x && y == pt.y; } + bool operator!=(const PointT& pt) const { return x != pt.x || y != pt.y; } }; typedef PointT Point; @@ -129,7 +123,7 @@ typedef PointT PointF; } // namespace gfx #ifdef _DEBUG -#include "gfx/point_io.h" + #include "gfx/point_io.h" #endif #endif diff --git a/gfx/point_io.h b/gfx/point_io.h index f097516cc..5564b48f3 100644 --- a/gfx/point_io.h +++ b/gfx/point_io.h @@ -13,28 +13,27 @@ namespace gfx { - template - inline std::ostream& operator<<(std::ostream& os, const PointT& point) { - return os << "(" - << point.x << ", " - << point.y << ")"; - } - - template - inline std::istream& operator>>(std::istream& in, PointT& point) { - while (in && in.get() != '(') - ; - - if (!in) - return in; +template +inline std::ostream& operator<<(std::ostream& os, const PointT& point) +{ + return os << "(" << point.x << ", " << point.y << ")"; +} - char chr; - in >> point.x >> chr - >> point.y; +template +inline std::istream& operator>>(std::istream& in, PointT& point) +{ + while (in && in.get() != '(') + ; + if (!in) return in; - } + char chr; + in >> point.x >> chr >> point.y; + + return in; } +} // namespace gfx + #endif diff --git a/gfx/rect.h b/gfx/rect.h index c523679a5..4472f7e95 100644 --- a/gfx/rect.h +++ b/gfx/rect.h @@ -13,9 +13,12 @@ namespace gfx { -template class PointT; -template class SizeT; -template class BorderT; +template +class PointT; +template +class SizeT; +template +class BorderT; // A rectangle. template @@ -23,39 +26,31 @@ class RectT { public: T x, y, w, h; - T x2() const { return x+w; } - T y2() const { return y+h; } + T x2() const { return x + w; } + T y2() const { return y + h; } // Creates a new empty rectangle with the origin in 0,0. - RectT() : x(0), y(0), w(0), h(0) { - } + RectT() : x(0), y(0), w(0), h(0) {} // Creates a new rectangle with the specified size with the origin in 0,0. - RectT(const T& w, const T& h) : - x(0), y(0), - w(w), h(h) { - } + RectT(const T& w, const T& h) : x(0), y(0), w(w), h(h) {} // Creates a new rectangle with the specified size with the origin in 0,0. - explicit RectT(const SizeT& size) : - x(0), y(0), - w(size.w), h(size.h) { - } + explicit RectT(const SizeT& size) : x(0), y(0), w(size.w), h(size.h) {} - RectT(const RectT& rect) : - x(rect.x), y(rect.y), - w(rect.w), h(rect.h) { - } + RectT(const RectT& rect) : x(rect.x), y(rect.y), w(rect.w), h(rect.h) {} template - RectT(const RectT& rect) : - x(static_cast(rect.x)), y(static_cast(rect.y)), - w(static_cast(rect.w)), h(static_cast(rect.h)) { + RectT(const RectT& rect) + : x(static_cast(rect.x)) + , y(static_cast(rect.y)) + , w(static_cast(rect.w)) + , h(static_cast(rect.h)) + { } - RectT(const PointT& point, const SizeT& size) : - x(point.x), y(point.y), - w(size.w), h(size.h) { + RectT(const PointT& point, const SizeT& size) : x(point.x), y(point.y), w(size.w), h(size.h) + { } // Creates a new rectangle with the origin in point1 and size @@ -71,7 +66,8 @@ class RectT { // // See that point2 isn't included in the rectangle, it's like the // point returned by point2() member function. - RectT(const PointT& point1, const PointT& point2) { + RectT(const PointT& point1, const PointT& point2) + { PointT leftTop = point1; PointT rightBottom = point2; T t; @@ -94,89 +90,87 @@ class RectT { this->h = rightBottom.y - leftTop.y; } - RectT(const T& x, const T& y, const T& w, const T& h) : x(x), y(y), w(w), h(h) { - } + RectT(const T& x, const T& y, const T& w, const T& h) : x(x), y(y), w(w), h(h) {} // Verifies if the width and/or height of the rectangle are less or // equal than zero. - bool isEmpty() const { - return (w <= 0 || h <= 0); - } + bool isEmpty() const { return (w <= 0 || h <= 0); } // Returns the middle point of the rectangle (x+w/2, y+h/2). - PointT center() const { - return PointT(x+w/2, y+h/2); - } + PointT center() const { return PointT(x + w / 2, y + h / 2); } // Returns the point in the upper-left corner (that is inside the // rectangle). - PointT origin() const { - return PointT(x, y); - } + PointT origin() const { return PointT(x, y); } // Returns point in the lower-right corner that is outside the // rectangle (x+w, y+h). - PointT point2() const { - return PointT(x+w, y+h); - } + PointT point2() const { return PointT(x + w, y + h); } - SizeT size() const { - return SizeT(w, h); - } + SizeT size() const { return SizeT(w, h); } - RectT& setOrigin(const PointT& pt) { + RectT& setOrigin(const PointT& pt) + { x = pt.x; y = pt.y; return *this; } - RectT& setSize(const SizeT& sz) { + RectT& setSize(const SizeT& sz) + { w = sz.w; h = sz.h; return *this; } // Moves the rectangle origin in the specified delta. - RectT& offset(const T& dx, const T& dy) { + RectT& offset(const T& dx, const T& dy) + { x += dx; y += dy; return *this; } template - RectT& offset(const PointT& delta) { + RectT& offset(const PointT& delta) + { x += delta.x; y += delta.y; return *this; } - RectT& inflate(const T& delta) { + RectT& inflate(const T& delta) + { w += delta; h += delta; return *this; } - RectT& inflate(const T& dw, const T& dh) { + RectT& inflate(const T& dw, const T& dh) + { w += dw; h += dh; return *this; } - RectT& inflate(const SizeT& delta) { + RectT& inflate(const SizeT& delta) + { w += delta.w; h += delta.h; return *this; } - RectT& enlarge(const T& unit) { + RectT& enlarge(const T& unit) + { x -= unit; y -= unit; - w += unit*2; - h += unit*2; + w += unit * 2; + h += unit * 2; return *this; } - RectT& enlarge(const BorderT& br) { + RectT& enlarge(const BorderT& br) + { x -= br.left(); y -= br.top(); w += br.left() + br.right(); @@ -184,27 +178,31 @@ class RectT { return *this; } - RectT& enlargeXW(const T& unit) { + RectT& enlargeXW(const T& unit) + { x -= unit; - w += unit*2; + w += unit * 2; return *this; } - RectT& enlargeYH(const T& unit) { + RectT& enlargeYH(const T& unit) + { y -= unit; - h += unit*2; + h += unit * 2; return *this; } - RectT& shrink(const T& unit) { + RectT& shrink(const T& unit) + { x += unit; y += unit; - w -= unit*2; - h -= unit*2; + w -= unit * 2; + h -= unit * 2; return *this; } - RectT& shrink(const BorderT& br) { + RectT& shrink(const BorderT& br) + { x += br.left(); y += br.top(); w -= br.left() + br.right(); @@ -233,79 +231,76 @@ class RectT { // gfx::Rect bounds = boundsF; // ASSERT(bounds == gfx::Rect(0, 0, 1, 2)); // - RectT& floor() { + RectT& floor() + { x = std::floor(x); y = std::floor(y); return *this; } // Returns true if this rectangle encloses the pt point. - bool contains(const PointT& pt) const { - return - pt.x >= x && pt.x < x+w && - pt.y >= y && pt.y < y+h; + bool contains(const PointT& pt) const + { + return pt.x >= x && pt.x < x + w && pt.y >= y && pt.y < y + h; } - bool contains(const T& u, const T& v) const { - return - u >= x && u < x+w && - v >= y && v < y+h; - } + bool contains(const T& u, const T& v) const { return u >= x && u < x + w && v >= y && v < y + h; } // Returns true if this rectangle entirely contains the rc rectangle. - bool contains(const RectT& rc) const { + bool contains(const RectT& rc) const + { if (isEmpty() || rc.isEmpty()) return false; - return - rc.x >= x && rc.x+rc.w <= x+w && - rc.y >= y && rc.y+rc.h <= y+h; + return rc.x >= x && rc.x + rc.w <= x + w && rc.y >= y && rc.y + rc.h <= y + h; } // Returns true if the intersection between this rectangle with rc // rectangle is not empty. - bool intersects(const RectT& rc) const { + bool intersects(const RectT& rc) const + { if (isEmpty() || rc.isEmpty()) return false; - return - rc.x < x+w && rc.x+rc.w > x && - rc.y < y+h && rc.y+rc.h > y; + return rc.x < x + w && rc.x + rc.w > x && rc.y < y + h && rc.y + rc.h > y; } // Returns the union rectangle between this and rc rectangle. - RectT createUnion(const RectT& rc) const { + RectT createUnion(const RectT& rc) const + { if (isEmpty()) return rc; if (rc.isEmpty()) return *this; - return RectT(PointT(x < rc.x ? x: rc.x, - y < rc.y ? y: rc.y), - PointT(x+w > rc.x+rc.w ? x+w: rc.x+rc.w, - y+h > rc.y+rc.h ? y+h: rc.y+rc.h)); + return RectT(PointT(x < rc.x ? x : rc.x, y < rc.y ? y : rc.y), + PointT(x + w > rc.x + rc.w ? x + w : rc.x + rc.w, + y + h > rc.y + rc.h ? y + h : rc.y + rc.h)); } // Returns the intersection rectangle between this and rc rectangles. - RectT createIntersection(const RectT& rc) const { + RectT createIntersection(const RectT& rc) const + { if (intersects(rc)) - return RectT(PointT(x > rc.x ? x: rc.x, - y > rc.y ? y: rc.y), - PointT(x+w < rc.x+rc.w ? x+w: rc.x+rc.w, - y+h < rc.y+rc.h ? y+h: rc.y+rc.h)); + return RectT(PointT(x > rc.x ? x : rc.x, y > rc.y ? y : rc.y), + PointT(x + w < rc.x + rc.w ? x + w : rc.x + rc.w, + y + h < rc.y + rc.h ? y + h : rc.y + rc.h)); return RectT(); } - const RectT& operator+=(const BorderT& br) { + const RectT& operator+=(const BorderT& br) + { enlarge(br); return *this; } - const RectT& operator-=(const BorderT& br) { + const RectT& operator-=(const BorderT& br) + { shrink(br); return *this; } - RectT& operator*=(const T factor) { + RectT& operator*=(const T factor) + { x *= factor; y *= factor; w *= factor; @@ -313,7 +308,8 @@ class RectT { return *this; } - RectT& operator/=(const T factor) { + RectT& operator/=(const T factor) + { x /= factor; y /= factor; w /= factor; @@ -321,7 +317,8 @@ class RectT { return *this; } - RectT& operator*=(const SizeT& size) { + RectT& operator*=(const SizeT& size) + { x *= size.w; y *= size.h; w *= size.w; @@ -329,7 +326,8 @@ class RectT { return *this; } - RectT& operator/=(const SizeT& size) { + RectT& operator/=(const SizeT& size) + { x /= size.w; y /= size.h; w /= size.w; @@ -337,72 +335,56 @@ class RectT { return *this; } - const RectT& operator|=(const RectT& rc) { - return *this = createUnion(rc); - } + const RectT& operator|=(const RectT& rc) { return *this = createUnion(rc); } - const RectT& operator&=(const RectT& rc) { - return *this = createIntersection(rc); - } + const RectT& operator&=(const RectT& rc) { return *this = createIntersection(rc); } - RectT operator+(const BorderT& br) const { - return RectT(*this).enlarge(br); - } + RectT operator+(const BorderT& br) const { return RectT(*this).enlarge(br); } - RectT operator-(const BorderT& br) const { - return RectT(*this).shrink(br); - } + RectT operator-(const BorderT& br) const { return RectT(*this).shrink(br); } - RectT operator|(const RectT& other) const { - return createUnion(other); - } + RectT operator|(const RectT& other) const { return createUnion(other); } - RectT operator&(const RectT& other) const { - return createIntersection(other); - } + RectT operator&(const RectT& other) const { return createIntersection(other); } - RectT operator*(const T factor) const { - return RectT(x*factor, y*factor, - w*factor, h*factor); + RectT operator*(const T factor) const + { + return RectT(x * factor, y * factor, w * factor, h * factor); } - RectT operator*(const SizeT& size) const { - return RectT(x*size.w, y*size.h, - w*size.w, h*size.h); + RectT operator*(const SizeT& size) const + { + return RectT(x * size.w, y * size.h, w * size.w, h * size.h); } - RectT operator/(const T scale) const { - return RectT(x/scale, y/scale, - w/scale, h/scale); - } + RectT operator/(const T scale) const { return RectT(x / scale, y / scale, w / scale, h / scale); } - RectT operator/(const SizeT& size) const { - return RectT(x/size.w, y/size.h, - w/size.w, h/size.h); + RectT operator/(const SizeT& size) const + { + return RectT(x / size.w, y / size.h, w / size.w, h / size.h); } - bool operator==(const RectT& rc) const { - return - x == rc.x && w == rc.w && - y == rc.y && h == rc.h; + bool operator==(const RectT& rc) const + { + return x == rc.x && w == rc.w && y == rc.y && h == rc.h; } - bool operator!=(const RectT& rc) const { - return - x != rc.x || w != rc.w || - y != rc.y || h != rc.h; + bool operator!=(const RectT& rc) const + { + return x != rc.x || w != rc.w || y != rc.y || h != rc.h; } - RectT& fitIn(const RectT& bounds) { + RectT& fitIn(const RectT& bounds) + { if (w < h) { w = w * bounds.h / h; - x = bounds.x + bounds.w/2 - w/2; + x = bounds.x + bounds.w / 2 - w / 2; y = bounds.y; h = bounds.h; } else { h = h * bounds.w / w; - y = bounds.y + bounds.h/2 - h/2; + y = bounds.y + bounds.h / 2 - h / 2; x = bounds.x; w = bounds.w; } @@ -411,7 +393,8 @@ class RectT { // Slices vertically this Rect along the provided px coordinate. // Sets the left and right rects in the references of the same name. - const RectT& sliceV(T px, RectT& left, RectT& right) const { + const RectT& sliceV(T px, RectT& left, RectT& right) const + { if (px < x) { left = RectT(); right = *this; @@ -430,7 +413,8 @@ class RectT { // Slices horizontally this Rect along the provided py coordinate. // Sets the top and bottom rects in the references of the same name. - const RectT& sliceH(T py, RectT& top, RectT& bottom) const { + const RectT& sliceH(T py, RectT& top, RectT& bottom) const + { if (py < y) { top = RectT(); bottom = *this; @@ -460,7 +444,8 @@ class RectT { // | | | [6] | [7] | [8] | // +---------------------+ +--------+-----+------+ // - const RectT& nineSlice(const RectT& center, RectT slices[9]) const { + const RectT& nineSlice(const RectT& center, RectT slices[9]) const + { gfx::RectT left, middle, right; { @@ -469,13 +454,13 @@ class RectT { remaining.sliceV(x + center.x2(), middle, right); } - left .sliceH(y + center.y , slices[0], left); - middle.sliceH(y + center.y , slices[1], middle); - right .sliceH(y + center.y , slices[2], right); + left.sliceH(y + center.y, slices[0], left); + middle.sliceH(y + center.y, slices[1], middle); + right.sliceH(y + center.y, slices[2], right); - left .sliceH(y + center.y2(), slices[3], left); + left.sliceH(y + center.y2(), slices[3], left); middle.sliceH(y + center.y2(), slices[4], middle); - right .sliceH(y + center.y2(), slices[5], right); + right.sliceH(y + center.y2(), slices[5], right); slices[6] = left; slices[7] = middle; @@ -483,7 +468,6 @@ class RectT { return *this; } - }; typedef RectT Rect; @@ -492,7 +476,7 @@ typedef RectT RectF; } // namespace gfx #ifdef _DEBUG -#include "gfx/rect_io.h" + #include "gfx/rect_io.h" #endif #endif diff --git a/gfx/rect_io.h b/gfx/rect_io.h index b2b9ae322..c99564bdb 100644 --- a/gfx/rect_io.h +++ b/gfx/rect_io.h @@ -14,32 +14,27 @@ namespace gfx { - template - inline std::ostream& operator<<(std::ostream& os, const RectT& rect) { - return os << "(" - << rect.x << ", " - << rect.y << ", " - << rect.w << ", " - << rect.h << ")"; - } - - template - inline std::istream& operator>>(std::istream& in, RectT& rect) { - while (in && in.get() != '(') - ; - - if (!in) - return in; - - char chr; - in >> rect.x >> chr - >> rect.y >> chr - >> rect.w >> chr - >> rect.h >> chr; +template +inline std::ostream& operator<<(std::ostream& os, const RectT& rect) +{ + return os << "(" << rect.x << ", " << rect.y << ", " << rect.w << ", " << rect.h << ")"; +} + +template +inline std::istream& operator>>(std::istream& in, RectT& rect) +{ + while (in && in.get() != '(') + ; + if (!in) return in; - } + char chr; + in >> rect.x >> chr >> rect.y >> chr >> rect.w >> chr >> rect.h >> chr; + + return in; } +} // namespace gfx + #endif diff --git a/gfx/rect_tests.cpp b/gfx/rect_tests.cpp index 23519a803..548711e85 100644 --- a/gfx/rect_tests.cpp +++ b/gfx/rect_tests.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -64,35 +64,34 @@ TEST(Rect, Floor) EXPECT_EQ(gfx::Rect(-1, -1, 1, 2), gfx::RectF(-0.25, -0.75, 1, 2).floor()); } - TEST(Rect, SliceV) { const int x = 3, y = 4; gfx::Rect l, r; auto rect = gfx::Rect(x, y, 5, 7); rect.sliceV(x, l, r); - EXPECT_EQ(gfx::Rect(x,y,0,7), l); - EXPECT_EQ(gfx::Rect(x,y,5,7), r); + EXPECT_EQ(gfx::Rect(x, y, 0, 7), l); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), r); - rect.sliceV(x-1, l, r); - EXPECT_EQ(gfx::Rect(0,0,0,0), l); - EXPECT_EQ(gfx::Rect(x,y,5,7), r); + rect.sliceV(x - 1, l, r); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), l); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), r); - rect.sliceV(x+1, l, r); - EXPECT_EQ(gfx::Rect(x,y,1,7), l); - EXPECT_EQ(gfx::Rect(x+1,y,4,7), r); + rect.sliceV(x + 1, l, r); + EXPECT_EQ(gfx::Rect(x, y, 1, 7), l); + EXPECT_EQ(gfx::Rect(x + 1, y, 4, 7), r); - rect.sliceV(x+4, l, r); - EXPECT_EQ(gfx::Rect(x,y,4,7), l); - EXPECT_EQ(gfx::Rect(x+4,y,1,7), r); + rect.sliceV(x + 4, l, r); + EXPECT_EQ(gfx::Rect(x, y, 4, 7), l); + EXPECT_EQ(gfx::Rect(x + 4, y, 1, 7), r); - rect.sliceV(x+5, l, r); - EXPECT_EQ(gfx::Rect(x,y,5,7), l); - EXPECT_EQ(gfx::Rect(x+5,y,0,7), r); + rect.sliceV(x + 5, l, r); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), l); + EXPECT_EQ(gfx::Rect(x + 5, y, 0, 7), r); - rect.sliceV(x+6, l, r); - EXPECT_EQ(gfx::Rect(x,y,5,7), l); - EXPECT_EQ(gfx::Rect(0,0,0,0), r); + rect.sliceV(x + 6, l, r); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), l); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), r); } TEST(Rect, SliceH) @@ -101,28 +100,28 @@ TEST(Rect, SliceH) gfx::Rect t, b; auto rect = gfx::Rect(x, y, 5, 7); rect.sliceH(y, t, b); - EXPECT_EQ(gfx::Rect(x,y,5,0), t); - EXPECT_EQ(gfx::Rect(x,y,5,7), b); + EXPECT_EQ(gfx::Rect(x, y, 5, 0), t); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), b); - rect.sliceH(y-1, t, b); - EXPECT_EQ(gfx::Rect(0,0,0,0), t); - EXPECT_EQ(gfx::Rect(x,y,5,7), b); + rect.sliceH(y - 1, t, b); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), t); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), b); - rect.sliceH(y+1, t, b); - EXPECT_EQ(gfx::Rect(x,y,5,1), t); - EXPECT_EQ(gfx::Rect(x,y+1,5,6), b); + rect.sliceH(y + 1, t, b); + EXPECT_EQ(gfx::Rect(x, y, 5, 1), t); + EXPECT_EQ(gfx::Rect(x, y + 1, 5, 6), b); - rect.sliceH(y+6, t, b); - EXPECT_EQ(gfx::Rect(x,y,5,6), t); - EXPECT_EQ(gfx::Rect(x,y+6,5,1), b); + rect.sliceH(y + 6, t, b); + EXPECT_EQ(gfx::Rect(x, y, 5, 6), t); + EXPECT_EQ(gfx::Rect(x, y + 6, 5, 1), b); - rect.sliceH(y+7, t, b); - EXPECT_EQ(gfx::Rect(x,y,5,7), t); - EXPECT_EQ(gfx::Rect(x,y+7,5,0), b); + rect.sliceH(y + 7, t, b); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), t); + EXPECT_EQ(gfx::Rect(x, y + 7, 5, 0), b); - rect.sliceH(y+8, t, b); - EXPECT_EQ(gfx::Rect(x,y,5,7), t); - EXPECT_EQ(gfx::Rect(0,0,0,0), b); + rect.sliceH(y + 8, t, b); + EXPECT_EQ(gfx::Rect(x, y, 5, 7), t); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), b); } TEST(Rect, NineSlice) @@ -133,42 +132,42 @@ TEST(Rect, NineSlice) // Slice using an inner rect. rect.nineSlice(gfx::Rect(3, 3, 2, 2), slices); - EXPECT_EQ(gfx::Rect(x,y,6,6), rect); - EXPECT_EQ(gfx::Rect(x ,y ,3,3), slices[0]); - EXPECT_EQ(gfx::Rect(x+3,y ,2,3), slices[1]); - EXPECT_EQ(gfx::Rect(x+5,y ,1,3), slices[2]); - EXPECT_EQ(gfx::Rect(x ,y+3,3,2), slices[3]); - EXPECT_EQ(gfx::Rect(x+3,y+3,2,2), slices[4]); - EXPECT_EQ(gfx::Rect(x+5,y+3,1,2), slices[5]); - EXPECT_EQ(gfx::Rect(x ,y+5,3,1), slices[6]); - EXPECT_EQ(gfx::Rect(x+3,y+5,2,1), slices[7]); - EXPECT_EQ(gfx::Rect(x+5,y+5,1,1), slices[8]); + EXPECT_EQ(gfx::Rect(x, y, 6, 6), rect); + EXPECT_EQ(gfx::Rect(x, y, 3, 3), slices[0]); + EXPECT_EQ(gfx::Rect(x + 3, y, 2, 3), slices[1]); + EXPECT_EQ(gfx::Rect(x + 5, y, 1, 3), slices[2]); + EXPECT_EQ(gfx::Rect(x, y + 3, 3, 2), slices[3]); + EXPECT_EQ(gfx::Rect(x + 3, y + 3, 2, 2), slices[4]); + EXPECT_EQ(gfx::Rect(x + 5, y + 3, 1, 2), slices[5]); + EXPECT_EQ(gfx::Rect(x, y + 5, 3, 1), slices[6]); + EXPECT_EQ(gfx::Rect(x + 3, y + 5, 2, 1), slices[7]); + EXPECT_EQ(gfx::Rect(x + 5, y + 5, 1, 1), slices[8]); // Slice using a center rect with the same size as the rect being sliced. rect.nineSlice(gfx::Rect(0, 0, 6, 6), slices); - EXPECT_EQ(gfx::Rect(x,y,6,6), rect); - EXPECT_EQ(gfx::Rect(x ,y ,0,0), slices[0]); - EXPECT_EQ(gfx::Rect(x ,y ,6,0), slices[1]); - EXPECT_EQ(gfx::Rect(x+6,y ,0,0), slices[2]); - EXPECT_EQ(gfx::Rect(x ,y ,0,6), slices[3]); - EXPECT_EQ(gfx::Rect(x ,y ,6,6), slices[4]); - EXPECT_EQ(gfx::Rect(x+6,y ,0,6), slices[5]); - EXPECT_EQ(gfx::Rect(x ,y+6,0,0), slices[6]); - EXPECT_EQ(gfx::Rect(x ,y+6,6,0), slices[7]); - EXPECT_EQ(gfx::Rect(x+6,y+6,0,0), slices[8]); + EXPECT_EQ(gfx::Rect(x, y, 6, 6), rect); + EXPECT_EQ(gfx::Rect(x, y, 0, 0), slices[0]); + EXPECT_EQ(gfx::Rect(x, y, 6, 0), slices[1]); + EXPECT_EQ(gfx::Rect(x + 6, y, 0, 0), slices[2]); + EXPECT_EQ(gfx::Rect(x, y, 0, 6), slices[3]); + EXPECT_EQ(gfx::Rect(x, y, 6, 6), slices[4]); + EXPECT_EQ(gfx::Rect(x + 6, y, 0, 6), slices[5]); + EXPECT_EQ(gfx::Rect(x, y + 6, 0, 0), slices[6]); + EXPECT_EQ(gfx::Rect(x, y + 6, 6, 0), slices[7]); + EXPECT_EQ(gfx::Rect(x + 6, y + 6, 0, 0), slices[8]); // Slice using an outer rect. rect.nineSlice(gfx::Rect(-1, -1, 8, 8), slices); - EXPECT_EQ(gfx::Rect(x,y,6,6), rect); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[0]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[1]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[2]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[3]); - EXPECT_EQ(gfx::Rect(x,y,6,6), slices[4]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[5]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[6]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[7]); - EXPECT_EQ(gfx::Rect(0,0,0,0), slices[8]); + EXPECT_EQ(gfx::Rect(x, y, 6, 6), rect); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[0]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[1]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[2]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[3]); + EXPECT_EQ(gfx::Rect(x, y, 6, 6), slices[4]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[5]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[6]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[7]); + EXPECT_EQ(gfx::Rect(0, 0, 0, 0), slices[8]); } int main(int argc, char** argv) diff --git a/gfx/region.h b/gfx/region.h index a833c5925..19bf082f9 100644 --- a/gfx/region.h +++ b/gfx/region.h @@ -9,8 +9,8 @@ #pragma once #include "gfx/rect.h" -#include #include +#include #if LAF_SKIA // There is a header file on Skia (SkTFitsIn.h) that uses diff --git a/gfx/region_pixman.cpp b/gfx/region_pixman.cpp index f11737a8b..7a6e71d3e 100644 --- a/gfx/region_pixman.cpp +++ b/gfx/region_pixman.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "pixman.h" @@ -22,10 +22,7 @@ namespace gfx { inline Rect to_rect(const pixman_box32& extends) { - return Rect( - extends.x1, extends.y1, - extends.x2 - extends.x1, - extends.y2 - extends.y1); + return Rect(extends.x1, extends.y1, extends.x2 - extends.x1, extends.y2 - extends.y1); } Region::Region() @@ -99,7 +96,7 @@ Region::const_iterator Region::end() const bool Region::isEmpty() const { - return (pixman_region32_not_empty(&m_region) ? false: true); + return (pixman_region32_not_empty(&m_region) ? false : true); } bool Region::isRect() const @@ -157,15 +154,14 @@ Region& Region::createSubtraction(const Region& a, const Region& b) bool Region::contains(const PointT& pt) const { - return pixman_region32_contains_point(&m_region, pt.x, pt.y, NULL) ? true: false; + return pixman_region32_contains_point(&m_region, pt.x, pt.y, NULL) ? true : false; } Region::Overlap Region::contains(const Rect& rect) const { - static_assert( - int(Out) == int(PIXMAN_REGION_OUT) && - int(In) == int(PIXMAN_REGION_IN) && - int(Part) == int(PIXMAN_REGION_PART), "Pixman constants have changed"); + static_assert(int(Out) == int(PIXMAN_REGION_OUT) && int(In) == int(PIXMAN_REGION_IN) && + int(Part) == int(PIXMAN_REGION_PART), + "Pixman constants have changed"); pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() }; return (Region::Overlap)pixman_region32_contains_rectangle(&m_region, &box); diff --git a/gfx/region_pixman.h b/gfx/region_pixman.h index c4447bf73..98cdc3209 100644 --- a/gfx/region_pixman.h +++ b/gfx/region_pixman.h @@ -15,104 +15,123 @@ namespace gfx { - template class PointT; - - class Region; - - namespace details { - - #ifdef PIXMAN_VERSION_MAJOR - typedef struct pixman_box32 Box; - typedef struct pixman_region32 Region; - #else - struct Box { - int32_t x1, y1, x2, y2; - }; - struct Region { - Box extents; - void* data; - }; - #endif - - template - class RegionIterator { - public: - using iterator_category = std::forward_iterator_tag; - using value_type = T; - using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; - - RegionIterator() : m_ptr(nullptr) { } - RegionIterator(const RegionIterator& o) : m_ptr(o.m_ptr) { } - template - RegionIterator(const RegionIterator& o) : m_ptr(o.m_ptr) { } - RegionIterator& operator=(const RegionIterator& o) { m_ptr = o.m_ptr; return *this; } - RegionIterator& operator++() { ++m_ptr; return *this; } - RegionIterator operator++(int) { RegionIterator o(*this); ++m_ptr; return o; } - bool operator==(const RegionIterator& o) const { return m_ptr == o.m_ptr; } - bool operator!=(const RegionIterator& o) const { return m_ptr != o.m_ptr; } - reference operator*() { - m_rect.x = m_ptr->x1; - m_rect.y = m_ptr->y1; - m_rect.w = m_ptr->x2 - m_ptr->x1; - m_rect.h = m_ptr->y2 - m_ptr->y1; - return m_rect; - } - private: - Box* m_ptr; - mutable Rect m_rect; - template friend class RegionIterator; - friend class ::gfx::Region; - }; - - } // namespace details - - class Region { - public: - enum Overlap { Out, In, Part }; - - using iterator = details::RegionIterator; - using const_iterator = details::RegionIterator; - - Region(); - Region(const Region& copy); - explicit Region(const Rect& rect); - Region& operator=(const Rect& rect); - Region& operator=(const Region& copy); - ~Region(); - - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - bool isEmpty() const; - bool isRect() const; - bool isComplex() const; - std::size_t size() const; - Rect bounds() const; - - void clear(); - - void offset(int dx, int dy); - void offset(const PointT& delta); - - Region& createIntersection(const Region& a, const Region& b); - Region& createUnion(const Region& a, const Region& b); - Region& createSubtraction(const Region& a, const Region& b); - - bool contains(const PointT& pt) const; - Overlap contains(const Rect& rect) const; - - Region& operator+=(const Region& b) { return createUnion(*this, b); } - Region& operator|=(const Region& b) { return createUnion(*this, b); } - Region& operator&=(const Region& b) { return createIntersection(*this, b); } - Region& operator-=(const Region& b) { return createSubtraction(*this, b); } - - private: - mutable details::Region m_region; - }; +template +class PointT; + +class Region; + +namespace details { + +#ifdef PIXMAN_VERSION_MAJOR +typedef struct pixman_box32 Box; +typedef struct pixman_region32 Region; +#else +struct Box { + int32_t x1, y1, x2, y2; +}; +struct Region { + Box extents; + void* data; +}; +#endif + +template +class RegionIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + + RegionIterator() : m_ptr(nullptr) {} + RegionIterator(const RegionIterator& o) : m_ptr(o.m_ptr) {} + template + RegionIterator(const RegionIterator& o) : m_ptr(o.m_ptr) + { + } + RegionIterator& operator=(const RegionIterator& o) + { + m_ptr = o.m_ptr; + return *this; + } + RegionIterator& operator++() + { + ++m_ptr; + return *this; + } + RegionIterator operator++(int) + { + RegionIterator o(*this); + ++m_ptr; + return o; + } + bool operator==(const RegionIterator& o) const { return m_ptr == o.m_ptr; } + bool operator!=(const RegionIterator& o) const { return m_ptr != o.m_ptr; } + reference operator*() + { + m_rect.x = m_ptr->x1; + m_rect.y = m_ptr->y1; + m_rect.w = m_ptr->x2 - m_ptr->x1; + m_rect.h = m_ptr->y2 - m_ptr->y1; + return m_rect; + } + +private: + Box* m_ptr; + mutable Rect m_rect; + template + friend class RegionIterator; + friend class ::gfx::Region; +}; + +} // namespace details + +class Region { +public: + enum Overlap { Out, In, Part }; + + using iterator = details::RegionIterator; + using const_iterator = details::RegionIterator; + + Region(); + Region(const Region& copy); + explicit Region(const Rect& rect); + Region& operator=(const Rect& rect); + Region& operator=(const Region& copy); + ~Region(); + + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + bool isEmpty() const; + bool isRect() const; + bool isComplex() const; + std::size_t size() const; + Rect bounds() const; + + void clear(); + + void offset(int dx, int dy); + void offset(const PointT& delta); + + Region& createIntersection(const Region& a, const Region& b); + Region& createUnion(const Region& a, const Region& b); + Region& createSubtraction(const Region& a, const Region& b); + + bool contains(const PointT& pt) const; + Overlap contains(const Rect& rect) const; + + Region& operator+=(const Region& b) { return createUnion(*this, b); } + Region& operator|=(const Region& b) { return createUnion(*this, b); } + Region& operator&=(const Region& b) { return createIntersection(*this, b); } + Region& operator-=(const Region& b) { return createSubtraction(*this, b); } + +private: + mutable details::Region m_region; +}; } // namespace gfx diff --git a/gfx/region_skia.cpp b/gfx/region_skia.cpp index bff52ad91..a12b26eb4 100644 --- a/gfx/region_skia.cpp +++ b/gfx/region_skia.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/region.h" @@ -21,13 +21,11 @@ Region::Region() { } -Region::Region(const Region& copy) - : m_region(copy.m_region) +Region::Region(const Region& copy) : m_region(copy.m_region) { } -Region::Region(const Rect& rect) - : m_region(SkIRect::MakeXYWH(rect.x, rect.y, rect.w, rect.h)) +Region::Region(const Rect& rect) : m_region(SkIRect::MakeXYWH(rect.x, rect.y, rect.w, rect.h)) { } @@ -75,8 +73,10 @@ Rect Region::bounds() const Region::Overlap Region::contains(const Rect& rect) const { auto rc = SkIRect::MakeXYWH(rect.x, rect.y, rect.w, rect.h); - if (m_region.contains(rc)) return In; - if (m_region.intersects(rc)) return Part; + if (m_region.contains(rc)) + return In; + if (m_region.intersects(rc)) + return Part; return Out; } diff --git a/gfx/region_skia.h b/gfx/region_skia.h index 0f5cb4da4..ad6d6cc41 100644 --- a/gfx/region_skia.h +++ b/gfx/region_skia.h @@ -17,120 +17,123 @@ namespace gfx { - template class PointT; - - class Region; - - namespace details { - - using Region = SkRegion; - - template - class RegionIterator { - public: - using iterator_category = std::forward_iterator_tag; - using value_type = T; - using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; - - RegionIterator() { } - RegionIterator(const RegionIterator& o) : m_it(o.m_it) { } - template - RegionIterator(const RegionIterator& o) : m_it(o.m_it) { } - RegionIterator& operator=(const RegionIterator& o) { m_it = o.m_it; return *this; } - RegionIterator& operator++() { m_it.next(); return *this; } - bool operator==(const RegionIterator& o) const { - return (m_it.done() == o.m_it.done()); - } - bool operator!=(const RegionIterator& o) const { - return (m_it.done() != o.m_it.done()); - } - reference operator*() { - const SkIRect& rc = m_it.rect(); - m_rect.x = rc.x(); - m_rect.y = rc.y(); - m_rect.w = rc.width(); - m_rect.h = rc.height(); - return m_rect; - } - private: - SkRegion::Iterator m_it; - mutable Rect m_rect; - template friend class RegionIterator; - friend class ::gfx::Region; - }; - - } // namespace details - - class Region { - public: - enum Overlap { Out, In, Part }; - - using iterator = details::RegionIterator; - using const_iterator = details::RegionIterator; - - Region(); - Region(const Region& copy); - explicit Region(const Rect& rect); - Region& operator=(const Rect& rect); - Region& operator=(const Region& copy); - - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - bool isEmpty() const { return m_region.isEmpty(); } - bool isRect() const { return m_region.isRect(); } - bool isComplex() const { return m_region.isComplex(); } - - std::size_t size() const { - return m_region.computeRegionComplexity(); - } - - Rect bounds() const; - - void clear() { - m_region.setEmpty(); - } - - void offset(int dx, int dy) { - m_region.translate(dx, dy); - } - - void offset(const PointT& delta) { - m_region.translate(delta.x, delta.y); - } - - Region& createIntersection(const Region& a, const Region& b) { - m_region.op(a.m_region, b.m_region, SkRegion::kIntersect_Op); - return *this; - } - - Region& createUnion(const Region& a, const Region& b) { - m_region.op(a.m_region, b.m_region, SkRegion::kUnion_Op); - return *this; - } - - Region& createSubtraction(const Region& a, const Region& b) { - m_region.op(a.m_region, b.m_region, SkRegion::kDifference_Op); - return *this; - } - - bool contains(const PointT& pt) const { - return m_region.contains(pt.x, pt.y); - } - Overlap contains(const Rect& rect) const; - - Region& operator+=(const Region& b) { return createUnion(*this, b); } - Region& operator|=(const Region& b) { return createUnion(*this, b); } - Region& operator&=(const Region& b) { return createIntersection(*this, b); } - Region& operator-=(const Region& b) { return createSubtraction(*this, b); } - - private: - mutable details::Region m_region; - }; +template +class PointT; + +class Region; + +namespace details { + +using Region = SkRegion; + +template +class RegionIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + + RegionIterator() {} + RegionIterator(const RegionIterator& o) : m_it(o.m_it) {} + template + RegionIterator(const RegionIterator& o) : m_it(o.m_it) + { + } + RegionIterator& operator=(const RegionIterator& o) + { + m_it = o.m_it; + return *this; + } + RegionIterator& operator++() + { + m_it.next(); + return *this; + } + bool operator==(const RegionIterator& o) const { return (m_it.done() == o.m_it.done()); } + bool operator!=(const RegionIterator& o) const { return (m_it.done() != o.m_it.done()); } + reference operator*() + { + const SkIRect& rc = m_it.rect(); + m_rect.x = rc.x(); + m_rect.y = rc.y(); + m_rect.w = rc.width(); + m_rect.h = rc.height(); + return m_rect; + } + +private: + SkRegion::Iterator m_it; + mutable Rect m_rect; + template + friend class RegionIterator; + friend class ::gfx::Region; +}; + +} // namespace details + +class Region { +public: + enum Overlap { Out, In, Part }; + + using iterator = details::RegionIterator; + using const_iterator = details::RegionIterator; + + Region(); + Region(const Region& copy); + explicit Region(const Rect& rect); + Region& operator=(const Rect& rect); + Region& operator=(const Region& copy); + + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + bool isEmpty() const { return m_region.isEmpty(); } + bool isRect() const { return m_region.isRect(); } + bool isComplex() const { return m_region.isComplex(); } + + std::size_t size() const { return m_region.computeRegionComplexity(); } + + Rect bounds() const; + + void clear() { m_region.setEmpty(); } + + void offset(int dx, int dy) { m_region.translate(dx, dy); } + + void offset(const PointT& delta) { m_region.translate(delta.x, delta.y); } + + Region& createIntersection(const Region& a, const Region& b) + { + m_region.op(a.m_region, b.m_region, SkRegion::kIntersect_Op); + return *this; + } + + Region& createUnion(const Region& a, const Region& b) + { + m_region.op(a.m_region, b.m_region, SkRegion::kUnion_Op); + return *this; + } + + Region& createSubtraction(const Region& a, const Region& b) + { + m_region.op(a.m_region, b.m_region, SkRegion::kDifference_Op); + return *this; + } + + bool contains(const PointT& pt) const { return m_region.contains(pt.x, pt.y); } + Overlap contains(const Rect& rect) const; + + Region& operator+=(const Region& b) { return createUnion(*this, b); } + Region& operator|=(const Region& b) { return createUnion(*this, b); } + Region& operator&=(const Region& b) { return createIntersection(*this, b); } + Region& operator-=(const Region& b) { return createSubtraction(*this, b); } + +private: + mutable details::Region m_region; +}; } // namespace gfx diff --git a/gfx/region_tests.cpp b/gfx/region_tests.cpp index 3cb5e1bd3..403a53cb7 100644 --- a/gfx/region_tests.cpp +++ b/gfx/region_tests.cpp @@ -6,16 +6,16 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include #if LAF_WITH_REGION -#include "gfx/point.h" -#include "gfx/rect_io.h" -#include "gfx/region.h" + #include "gfx/point.h" + #include "gfx/rect_io.h" + #include "gfx/region.h" using namespace std; using namespace gfx; @@ -23,8 +23,7 @@ using namespace gfx; ostream& operator<<(ostream& os, const Region& rgn) { os << "{"; - for (Region::const_iterator it=rgn.begin(), end=rgn.end(); - it != end; ) { + for (Region::const_iterator it = rgn.begin(), end = rgn.end(); it != end;) { os << *it; ++it; if (it != end) @@ -95,13 +94,13 @@ TEST(Region, ContainsPoint) { Region a(Rect(2, 3, 4, 5)); EXPECT_TRUE(a.contains(Point(2, 3))); - EXPECT_FALSE(a.contains(Point(2-1, 3-1))); - EXPECT_FALSE(a.contains(Point(2+4, 3))); - EXPECT_FALSE(a.contains(Point(2, 3+5))); - EXPECT_FALSE(a.contains(Point(2+4, 3+5))); - EXPECT_TRUE(a.contains(Point(2+4-1, 3))); - EXPECT_TRUE(a.contains(Point(2, 3+5-1))); - EXPECT_TRUE(a.contains(Point(2+4-1, 3+5-1))); + EXPECT_FALSE(a.contains(Point(2 - 1, 3 - 1))); + EXPECT_FALSE(a.contains(Point(2 + 4, 3))); + EXPECT_FALSE(a.contains(Point(2, 3 + 5))); + EXPECT_FALSE(a.contains(Point(2 + 4, 3 + 5))); + EXPECT_TRUE(a.contains(Point(2 + 4 - 1, 3))); + EXPECT_TRUE(a.contains(Point(2, 3 + 5 - 1))); + EXPECT_TRUE(a.contains(Point(2 + 4 - 1, 3 + 5 - 1))); } TEST(Region, Iterators) @@ -112,19 +111,19 @@ TEST(Region, Iterators) EXPECT_TRUE(a.isComplex()); EXPECT_TRUE(a.size() > 1); int c = 0; - for (Region::iterator it=a.begin(), end=a.end(); it!=end; ++it) { + for (Region::iterator it = a.begin(), end = a.end(); it != end; ++it) { ++c; } EXPECT_EQ(2, c); c = 0; - for (Region::const_iterator it=a.begin(), end=a.end(); it!=end; ++it) { + for (Region::const_iterator it = a.begin(), end = a.end(); it != end; ++it) { ++c; } EXPECT_EQ(2, c); } -#endif // LAF_WITH_REGION +#endif // LAF_WITH_REGION int main(int argc, char** argv) { diff --git a/gfx/region_win.cpp b/gfx/region_win.cpp index 7436c2991..4d45e6d53 100644 --- a/gfx/region_win.cpp +++ b/gfx/region_win.cpp @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "gfx/region.h" @@ -14,19 +14,16 @@ namespace gfx { -Region::Region() - : m_hrgn(CreateRectRgn(0, 0, 0, 0)) +Region::Region() : m_hrgn(CreateRectRgn(0, 0, 0, 0)) { } -Region::Region(const Region& copy) - : m_hrgn(CreateRectRgn(0, 0, 0, 0)) +Region::Region(const Region& copy) : m_hrgn(CreateRectRgn(0, 0, 0, 0)) { CombineRgn(m_hrgn, copy.m_hrgn, nullptr, RGN_COPY); } -Region::Region(const Rect& rect) - : m_hrgn(CreateRectRgn(rect.x, rect.y, rect.x2(), rect.y2())) +Region::Region(const Rect& rect) : m_hrgn(CreateRectRgn(rect.x, rect.y, rect.x2(), rect.y2())) { } @@ -79,9 +76,7 @@ Rect Region::bounds() const { RECT rc = { 0, 0, 0, 0 }; int res = GetRgnBox(m_hrgn, &rc); - return gfx::Rect(rc.left, rc.top, - rc.right - rc.left, - rc.bottom - rc.top); + return gfx::Rect(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top); } std::size_t Region::size() const @@ -125,7 +120,7 @@ Region& Region::createSubtraction(const Region& a, const Region& b) bool Region::contains(const PointT& pt) const { - return PtInRegion(m_hrgn, pt.x, pt.y) ? true: false; + return PtInRegion(m_hrgn, pt.x, pt.y) ? true : false; } Region::Overlap Region::contains(const Rect& rect) const diff --git a/gfx/region_win.h b/gfx/region_win.h index 118a1d916..d787ff8c2 100644 --- a/gfx/region_win.h +++ b/gfx/region_win.h @@ -17,102 +17,122 @@ namespace gfx { - template class PointT; - - class Region; - - namespace details { - - template - class RegionIterator { - public: - using iterator_category = std::forward_iterator_tag; - using value_type = T; - using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; - - RegionIterator() { } - RegionIterator(LPRECT prect) : m_prect(prect) { } - RegionIterator(const RegionIterator& o) : m_prect(o.m_prect) { } - template - RegionIterator(const RegionIterator& o) : m_prect(o.m_prect) { } - RegionIterator& operator=(const RegionIterator& o) { m_prect = o.m_prect; return *this; } - RegionIterator& operator++() { ++m_prect; return *this; } - bool operator==(const RegionIterator& o) const { - return (m_prect == o.m_prect); - } - bool operator!=(const RegionIterator& o) const { - return (m_prect != o.m_prect); - } - reference operator*() { - m_rect.x = m_prect->left; - m_rect.y = m_prect->top; - m_rect.w = m_prect->right - m_prect->left; - m_rect.h = m_prect->bottom - m_prect->top; - return m_rect; - } - private: - LPRECT m_prect; - gfx::Rect m_rect; - template friend class RegionIterator; - }; - - } // namespace details - - class Region { - public: - enum Overlap { Out, In, Part }; - - using iterator = details::RegionIterator; - using const_iterator = details::RegionIterator; - - Region(); - Region(const Region& copy); - explicit Region(const Rect& rect); - Region& operator=(const Rect& rect); - Region& operator=(const Region& copy); - ~Region(); - - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - bool isEmpty() const { RECT rc; return GetRgnBox(m_hrgn, &rc) == NULLREGION; } - bool isRect() const { RECT rc; return GetRgnBox(m_hrgn, &rc) == SIMPLEREGION; } - bool isComplex() const { RECT rc; return GetRgnBox(m_hrgn, &rc) == COMPLEXREGION; } - - std::size_t size() const; - - Rect bounds() const; - - void clear(); - - void offset(int dx, int dy); - void offset(const PointT& delta) { - offset(delta.x, delta.y); - } - - Region& createIntersection(const Region& a, const Region& b); - Region& createUnion(const Region& a, const Region& b); - Region& createSubtraction(const Region& a, const Region& b); - - bool contains(const PointT& pt) const; - Overlap contains(const Rect& rect) const; - - Region& operator+=(const Region& b) { return createUnion(*this, b); } - Region& operator|=(const Region& b) { return createUnion(*this, b); } - Region& operator&=(const Region& b) { return createIntersection(*this, b); } - Region& operator-=(const Region& b) { return createSubtraction(*this, b); } - - private: - void resetData() const; - void fillData() const; - - HRGN m_hrgn = nullptr; - mutable LPRGNDATA m_data = nullptr; - }; +template +class PointT; + +class Region; + +namespace details { + +template +class RegionIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + + RegionIterator() {} + RegionIterator(LPRECT prect) : m_prect(prect) {} + RegionIterator(const RegionIterator& o) : m_prect(o.m_prect) {} + template + RegionIterator(const RegionIterator& o) : m_prect(o.m_prect) + { + } + RegionIterator& operator=(const RegionIterator& o) + { + m_prect = o.m_prect; + return *this; + } + RegionIterator& operator++() + { + ++m_prect; + return *this; + } + bool operator==(const RegionIterator& o) const { return (m_prect == o.m_prect); } + bool operator!=(const RegionIterator& o) const { return (m_prect != o.m_prect); } + reference operator*() + { + m_rect.x = m_prect->left; + m_rect.y = m_prect->top; + m_rect.w = m_prect->right - m_prect->left; + m_rect.h = m_prect->bottom - m_prect->top; + return m_rect; + } + +private: + LPRECT m_prect; + gfx::Rect m_rect; + template + friend class RegionIterator; +}; + +} // namespace details + +class Region { +public: + enum Overlap { Out, In, Part }; + + using iterator = details::RegionIterator; + using const_iterator = details::RegionIterator; + + Region(); + Region(const Region& copy); + explicit Region(const Rect& rect); + Region& operator=(const Rect& rect); + Region& operator=(const Region& copy); + ~Region(); + + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + bool isEmpty() const + { + RECT rc; + return GetRgnBox(m_hrgn, &rc) == NULLREGION; + } + bool isRect() const + { + RECT rc; + return GetRgnBox(m_hrgn, &rc) == SIMPLEREGION; + } + bool isComplex() const + { + RECT rc; + return GetRgnBox(m_hrgn, &rc) == COMPLEXREGION; + } + + std::size_t size() const; + + Rect bounds() const; + + void clear(); + + void offset(int dx, int dy); + void offset(const PointT& delta) { offset(delta.x, delta.y); } + + Region& createIntersection(const Region& a, const Region& b); + Region& createUnion(const Region& a, const Region& b); + Region& createSubtraction(const Region& a, const Region& b); + + bool contains(const PointT& pt) const; + Overlap contains(const Rect& rect) const; + + Region& operator+=(const Region& b) { return createUnion(*this, b); } + Region& operator|=(const Region& b) { return createUnion(*this, b); } + Region& operator&=(const Region& b) { return createIntersection(*this, b); } + Region& operator-=(const Region& b) { return createSubtraction(*this, b); } + +private: + void resetData() const; + void fillData() const; + + HRGN m_hrgn = nullptr; + mutable LPRGNDATA m_data = nullptr; +}; } // namespace gfx diff --git a/gfx/rgb.cpp b/gfx/rgb.cpp index 564c99ae5..cad303023 100644 --- a/gfx/rgb.cpp +++ b/gfx/rgb.cpp @@ -25,7 +25,6 @@ Rgb::Rgb(const Hsv& hsv) r = g = b = 0.0; switch (int(hue_prime)) { - case 6: case 0: r = chroma; @@ -60,14 +59,14 @@ Rgb::Rgb(const Hsv& hsv) g += m; b += m; - m_red = int(r*255.0+0.5); - m_green = int(g*255.0+0.5); - m_blue = int(b*255.0+0.5); + m_red = int(r * 255.0 + 0.5); + m_green = int(g * 255.0 + 0.5); + m_blue = int(b * 255.0 + 0.5); } Rgb::Rgb(const Hsl& hsl) { - const double chroma = (1.0 - std::fabs(2.0*hsl.lightness() - 1.0)) * hsl.saturation(); + const double chroma = (1.0 - std::fabs(2.0 * hsl.lightness() - 1.0)) * hsl.saturation(); const double hue_prime = hsl.hue() / 60.0; const double x = chroma * (1.0 - std::fabs(std::fmod(hue_prime, 2.0) - 1.0)); double r, g, b; @@ -75,7 +74,6 @@ Rgb::Rgb(const Hsl& hsl) r = g = b = 0.0; switch (int(hue_prime)) { - case 6: case 0: r = chroma; @@ -105,28 +103,28 @@ Rgb::Rgb(const Hsl& hsl) break; } - const double m = hsl.lightness() - chroma/2.0; + const double m = hsl.lightness() - chroma / 2.0; r += m; g += m; b += m; - m_red = int(r*255.0+0.5); - m_green = int(g*255.0+0.5); - m_blue = int(b*255.0+0.5); + m_red = int(r * 255.0 + 0.5); + m_green = int(g * 255.0 + 0.5); + m_blue = int(b * 255.0 + 0.5); } int Rgb::maxComponent() const { if (m_red > m_green) - return (m_red > m_blue) ? m_red: m_blue; - return (m_green > m_blue) ? m_green: m_blue; + return (m_red > m_blue) ? m_red : m_blue; + return (m_green > m_blue) ? m_green : m_blue; } int Rgb::minComponent() const { if (m_red < m_green) - return (m_red < m_blue) ? m_red: m_blue; - return (m_green < m_blue) ? m_green: m_blue; + return (m_red < m_blue) ? m_red : m_blue; + return (m_green < m_blue) ? m_green : m_blue; } } // namespace gfx diff --git a/gfx/rgb.h b/gfx/rgb.h index a5557842e..d156624a0 100644 --- a/gfx/rgb.h +++ b/gfx/rgb.h @@ -17,71 +17,54 @@ class Hsl; class Rgb { public: - Rgb() - : m_red(0) - , m_green(0) - , m_blue(0) - { } - - Rgb(int red, int green, int blue) - : m_red(red) - , m_green(green) - , m_blue(blue) + Rgb() : m_red(0), m_green(0), m_blue(0) {} + + Rgb(int red, int green, int blue) : m_red(red), m_green(green), m_blue(blue) { - ASSERT(red >= 0 && red <= 255); + ASSERT(red >= 0 && red <= 255); ASSERT(green >= 0 && green <= 255); - ASSERT(blue >= 0 && blue <= 255); + ASSERT(blue >= 0 && blue <= 255); } - Rgb(const Rgb& rgb) - : m_red(rgb.red()) - , m_green(rgb.green()) - , m_blue(rgb.blue()) - { } + Rgb(const Rgb& rgb) : m_red(rgb.red()), m_green(rgb.green()), m_blue(rgb.blue()) {} // Conversions explicit Rgb(const Hsv& hsv); explicit Rgb(const Hsl& hsl); - int red() const { - return m_red; - } + int red() const { return m_red; } - int green() const { - return m_green; - } + int green() const { return m_green; } - int blue() const { - return m_blue; - } + int blue() const { return m_blue; } int maxComponent() const; int minComponent() const; - void red(int red) { + void red(int red) + { ASSERT(red >= 0 && red <= 255); m_red = red; } - void green(int green) { + void green(int green) + { ASSERT(green >= 0 && green <= 255); m_green = green; } - void blue(int blue) { + void blue(int blue) + { ASSERT(blue >= 0 && blue <= 255); m_blue = blue; } - bool operator==(const Rgb& other) const { - return (m_red == other.m_red && - m_green == other.m_green && - m_blue == other.m_blue); + bool operator==(const Rgb& other) const + { + return (m_red == other.m_red && m_green == other.m_green && m_blue == other.m_blue); } - bool operator!=(const Rgb& other) const { - return !operator==(other); - } + bool operator!=(const Rgb& other) const { return !operator==(other); } private: int m_red; diff --git a/gfx/rgb_tests.cpp b/gfx/rgb_tests.cpp index 3c179f435..5072fb52d 100644 --- a/gfx/rgb_tests.cpp +++ b/gfx/rgb_tests.cpp @@ -5,28 +5,26 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include -#include "gfx/rgb.h" #include "gfx/hsv.h" +#include "gfx/rgb.h" using namespace gfx; using namespace std; namespace gfx { - ostream& operator<<(ostream& os, const Rgb& rgb) { - return os << "(" - << rgb.red() << ", " - << rgb.green() << ", " - << rgb.blue() << ")"; - } - +ostream& operator<<(ostream& os, const Rgb& rgb) +{ + return os << "(" << rgb.red() << ", " << rgb.green() << ", " << rgb.blue() << ")"; } +} // namespace gfx + TEST(Rgb, Ctor) { EXPECT_EQ(1, Rgb(1, 2, 3).red()); @@ -70,21 +68,21 @@ TEST(Rgb, FromHsv) for (double hue = 0.0; hue <= 360.0; hue += 10.0) { EXPECT_EQ(Rgb(255, 255, 255), Rgb(Hsv(hue, 0.000, 1.000))); EXPECT_EQ(Rgb(128, 128, 128), Rgb(Hsv(hue, 0.000, 0.500))); - EXPECT_EQ(Rgb( 0, 0, 0), Rgb(Hsv(hue, 0.000, 0.000))); + EXPECT_EQ(Rgb(0, 0, 0), Rgb(Hsv(hue, 0.000, 0.000))); } - EXPECT_EQ(Rgb( 3, 0, 0), Rgb(Hsv( 0.0, 1.000, 0.010))); - EXPECT_EQ(Rgb(252, 0, 0), Rgb(Hsv( 0.0, 1.000, 0.990))); - EXPECT_EQ(Rgb(255, 0, 0), Rgb(Hsv( 0.0, 1.000, 1.000))); - EXPECT_EQ(Rgb(191, 191, 0), Rgb(Hsv( 60.0, 1.000, 0.750))); - EXPECT_EQ(Rgb( 0, 128, 0), Rgb(Hsv(120.0, 1.000, 0.500))); - EXPECT_EQ(Rgb( 0, 255, 0), Rgb(Hsv(120.0, 1.000, 1.000))); + EXPECT_EQ(Rgb(3, 0, 0), Rgb(Hsv(0.0, 1.000, 0.010))); + EXPECT_EQ(Rgb(252, 0, 0), Rgb(Hsv(0.0, 1.000, 0.990))); + EXPECT_EQ(Rgb(255, 0, 0), Rgb(Hsv(0.0, 1.000, 1.000))); + EXPECT_EQ(Rgb(191, 191, 0), Rgb(Hsv(60.0, 1.000, 0.750))); + EXPECT_EQ(Rgb(0, 128, 0), Rgb(Hsv(120.0, 1.000, 0.500))); + EXPECT_EQ(Rgb(0, 255, 0), Rgb(Hsv(120.0, 1.000, 1.000))); EXPECT_EQ(Rgb(128, 255, 255), Rgb(Hsv(180.0, 0.500, 1.000))); EXPECT_EQ(Rgb(128, 128, 255), Rgb(Hsv(240.0, 0.500, 1.000))); - EXPECT_EQ(Rgb( 0, 0, 255), Rgb(Hsv(240.0, 1.000, 1.000))); - EXPECT_EQ(Rgb(191, 64, 191), Rgb(Hsv(300.0, 0.667, 0.750))); - EXPECT_EQ(Rgb(252, 0, 0), Rgb(Hsv(360.0, 1.000, 0.990))); - EXPECT_EQ(Rgb(255, 0, 0), Rgb(Hsv(360.0, 1.000, 1.000))); + EXPECT_EQ(Rgb(0, 0, 255), Rgb(Hsv(240.0, 1.000, 1.000))); + EXPECT_EQ(Rgb(191, 64, 191), Rgb(Hsv(300.0, 0.667, 0.750))); + EXPECT_EQ(Rgb(252, 0, 0), Rgb(Hsv(360.0, 1.000, 0.990))); + EXPECT_EQ(Rgb(255, 0, 0), Rgb(Hsv(360.0, 1.000, 1.000))); } int main(int argc, char** argv) diff --git a/gfx/size.h b/gfx/size.h index d32217a0b..aa5388252 100644 --- a/gfx/size.h +++ b/gfx/size.h @@ -22,119 +22,97 @@ class SizeT { public: T w, h; - SizeT() : w(0), h(0) { - } + SizeT() : w(0), h(0) {} - SizeT(const T& w, const T& h) : w(w), h(h) { - } + SizeT(const T& w, const T& h) : w(w), h(h) {} - SizeT(const SizeT& size) : w(size.w), h(size.h) { - } + SizeT(const SizeT& size) : w(size.w), h(size.h) {} template - explicit SizeT(const SizeT& size) : w(static_cast(size.w)), - h(static_cast(size.h)) { + explicit SizeT(const SizeT& size) : w(static_cast(size.w)) + , h(static_cast(size.h)) + { } - explicit SizeT(const PointT& point) : w(point.x), h(point.y) { - } + explicit SizeT(const PointT& point) : w(point.x), h(point.y) {} - SizeT createUnion(const SizeT& sz) const { - return SizeT(std::max(w, sz.w), - std::max(h, sz.h)); - } + SizeT createUnion(const SizeT& sz) const { return SizeT(std::max(w, sz.w), std::max(h, sz.h)); } - SizeT createIntersection(const SizeT& sz) const { - return SizeT(std::min(w, sz.w), - std::min(h, sz.h)); + SizeT createIntersection(const SizeT& sz) const + { + return SizeT(std::min(w, sz.w), std::min(h, sz.h)); } - SizeT& operator=(const SizeT& sz) { + SizeT& operator=(const SizeT& sz) + { w = sz.w; h = sz.h; return *this; } - const SizeT& operator+=(const SizeT& sz) { + const SizeT& operator+=(const SizeT& sz) + { w += sz.w; h += sz.h; return *this; } - const SizeT& operator-=(const SizeT& sz) { + const SizeT& operator-=(const SizeT& sz) + { w -= sz.w; h -= sz.h; return *this; } - const SizeT& operator+=(const T& value) { + const SizeT& operator+=(const T& value) + { w += value; h += value; return *this; } - const SizeT& operator-=(const T& value) { + const SizeT& operator-=(const T& value) + { w -= value; h -= value; return *this; } - const SizeT& operator*=(const T& value) { + const SizeT& operator*=(const T& value) + { w *= value; h *= value; return *this; } - const SizeT& operator/=(const T& value) { + const SizeT& operator/=(const T& value) + { w /= value; h /= value; return *this; } - const SizeT& operator|=(const SizeT& sz) { - return *this = createUnion(sz); - } + const SizeT& operator|=(const SizeT& sz) { return *this = createUnion(sz); } - const SizeT& operator&=(const SizeT& sz) { - return *this = createIntersection(sz); - } + const SizeT& operator&=(const SizeT& sz) { return *this = createIntersection(sz); } - SizeT operator+(const SizeT& sz) const { - return SizeT(w+sz.w, h+sz.h); - } + SizeT operator+(const SizeT& sz) const { return SizeT(w + sz.w, h + sz.h); } - SizeT operator-(const SizeT& sz) const { - return SizeT(w-sz.w, h-sz.h); - } + SizeT operator-(const SizeT& sz) const { return SizeT(w - sz.w, h - sz.h); } - SizeT operator+(const T& value) const { - return SizeT(w+value, h+value); - } - - SizeT operator-(const T& value) const { - return SizeT(w-value, h-value); - } + SizeT operator+(const T& value) const { return SizeT(w + value, h + value); } - SizeT operator*(const T& value) const { - return SizeT(w*value, h*value); - } + SizeT operator-(const T& value) const { return SizeT(w - value, h - value); } - SizeT operator/(const T& value) const { - return SizeT(w/value, h/value); - } + SizeT operator*(const T& value) const { return SizeT(w * value, h * value); } - SizeT operator-() const { - return SizeT(-w, -h); - } + SizeT operator/(const T& value) const { return SizeT(w / value, h / value); } - bool operator==(const SizeT& sz) const { - return w == sz.w && h == sz.h; - } + SizeT operator-() const { return SizeT(-w, -h); } - bool operator!=(const SizeT& sz) const { - return w != sz.w || h != sz.h; - } + bool operator==(const SizeT& sz) const { return w == sz.w && h == sz.h; } + bool operator!=(const SizeT& sz) const { return w != sz.w || h != sz.h; } }; typedef SizeT Size; @@ -143,7 +121,7 @@ typedef SizeT SizeF; } // namespace gfx #ifdef _DEBUG -#include "gfx/size_io.h" + #include "gfx/size_io.h" #endif #endif diff --git a/gfx/size_io.h b/gfx/size_io.h index 260a4d08f..bc7965d4d 100644 --- a/gfx/size_io.h +++ b/gfx/size_io.h @@ -13,28 +13,27 @@ namespace gfx { - template - inline std::ostream& operator<<(std::ostream& os, const SizeT& size) { - return os << "(" - << size.w << ", " - << size.h << ")"; - } - - template - inline std::istream& operator>>(std::istream& in, SizeT& size) { - while (in && in.get() != '(') - ; - - if (!in) - return in; +template +inline std::ostream& operator<<(std::ostream& os, const SizeT& size) +{ + return os << "(" << size.w << ", " << size.h << ")"; +} - char chr; - in >> size.w >> chr - >> size.h; +template +inline std::istream& operator>>(std::istream& in, SizeT& size) +{ + while (in && in.get() != '(') + ; + if (!in) return in; - } + char chr; + in >> size.w >> chr >> size.h; + + return in; } +} // namespace gfx + #endif diff --git a/os/app_main_tests.cpp b/os/app_main_tests.cpp index 4065dbd06..5b13942d2 100644 --- a/os/app_main_tests.cpp +++ b/os/app_main_tests.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include diff --git a/os/app_mode.h b/os/app_mode.h index d5c6e6739..b364ce924 100644 --- a/os/app_mode.h +++ b/os/app_mode.h @@ -10,7 +10,7 @@ namespace os { - enum class AppMode { CLI, GUI }; +enum class AppMode { CLI, GUI }; } // namespace os diff --git a/os/capabilities.h b/os/capabilities.h index 6565aeb34..55194b25d 100644 --- a/os/capabilities.h +++ b/os/capabilities.h @@ -11,34 +11,34 @@ namespace os { - enum class Capabilities { - // Supports the creation of multiple os::Window. If this is not - // set, the system supports just one display, like a phone device. - MultipleWindows = 1, - - // When os::Window can be resized. - CanResizeWindow = 2, - - // When we can change the window scale. - WindowScale = 4, - - // When we can set the mouse cursor with a custom os::Surface - // using os::Window::makeMouseCursor() - CustomMouseCursor = 8, - - // When GPU acceleration can be turned on. - // TODO this is being developed - GpuAccelerationSwitch = 16, - - // When the platform support changing the color space of the - // window. - ColorSpaces = 32, - - // Windows & Linux allow to the programmer to start the - // drag-window-to-resize-it loop from a os::Event:MouseDown, but - // macOS doesn't (macOS supports only start moving the window). - CanStartWindowResize = 64 - }; +enum class Capabilities { + // Supports the creation of multiple os::Window. If this is not + // set, the system supports just one display, like a phone device. + MultipleWindows = 1, + + // When os::Window can be resized. + CanResizeWindow = 2, + + // When we can change the window scale. + WindowScale = 4, + + // When we can set the mouse cursor with a custom os::Surface + // using os::Window::makeMouseCursor() + CustomMouseCursor = 8, + + // When GPU acceleration can be turned on. + // TODO this is being developed + GpuAccelerationSwitch = 16, + + // When the platform support changing the color space of the + // window. + ColorSpaces = 32, + + // Windows & Linux allow to the programmer to start the + // drag-window-to-resize-it loop from a os::Event:MouseDown, but + // macOS doesn't (macOS supports only start moving the window). + CanStartWindowResize = 64 +}; } // namespace os diff --git a/os/color_space.h b/os/color_space.h index 0939c6ce2..2baf25230 100644 --- a/os/color_space.h +++ b/os/color_space.h @@ -15,24 +15,24 @@ namespace os { - class ColorSpace; - using ColorSpaceRef = Ref; - - class ColorSpace : public RefCount { - public: - virtual ~ColorSpace() { } - virtual const gfx::ColorSpaceRef& gfxColorSpace() const = 0; - virtual bool isSRGB() const = 0; - }; - - class ColorSpaceConversion : public RefCount { - public: - virtual ~ColorSpaceConversion() { } - // Transform RGBA pixels between two color spaces. - virtual bool convertRgba(uint32_t* dst, const uint32_t* src, int n) = 0; - // Transform grayscale pixels (without alpha) between two color spaces. - virtual bool convertGray(uint8_t* dst, const uint8_t* src, int n) = 0; - }; +class ColorSpace; +using ColorSpaceRef = Ref; + +class ColorSpace : public RefCount { +public: + virtual ~ColorSpace() {} + virtual const gfx::ColorSpaceRef& gfxColorSpace() const = 0; + virtual bool isSRGB() const = 0; +}; + +class ColorSpaceConversion : public RefCount { +public: + virtual ~ColorSpaceConversion() {} + // Transform RGBA pixels between two color spaces. + virtual bool convertRgba(uint32_t* dst, const uint32_t* src, int n) = 0; + // Transform grayscale pixels (without alpha) between two color spaces. + virtual bool convertGray(uint8_t* dst, const uint8_t* src, int n) = 0; +}; } // namespace os diff --git a/os/common/event_queue.cpp b/os/common/event_queue.cpp index 7544fc157..f8006ccf8 100644 --- a/os/common/event_queue.cpp +++ b/os/common/event_queue.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #if LAF_WINDOWS @@ -21,7 +21,8 @@ namespace os { EventQueueImpl g_queue; -EventQueue* EventQueue::instance() { +EventQueue* EventQueue::instance() +{ return &g_queue; } diff --git a/os/common/file_dialog.h b/os/common/file_dialog.h index 737f66ff3..e409c6f1f 100644 --- a/os/common/file_dialog.h +++ b/os/common/file_dialog.h @@ -15,23 +15,16 @@ namespace os { class CommonFileDialog : public FileDialog { public: - CommonFileDialog() - : m_type(Type::OpenFile) { - } + CommonFileDialog() : m_type(Type::OpenFile) {} - void setType(const Type type) override { - m_type = type; - } + void setType(const Type type) override { m_type = type; } - void setTitle(const std::string& title) override { - m_title = title; - } + void setTitle(const std::string& title) override { m_title = title; } - void setDefaultExtension(const std::string& extension) override { - m_defExtension = extension; - } + void setDefaultExtension(const std::string& extension) override { m_defExtension = extension; } - void addFilter(const std::string& extension, const std::string& description) override { + void addFilter(const std::string& extension, const std::string& description) override + { if (m_defExtension.empty()) m_defExtension = extension; diff --git a/os/common/freetype_font.cpp b/os/common/freetype_font.cpp index 59ebd138b..f7e44f2a0 100644 --- a/os/common/freetype_font.cpp +++ b/os/common/freetype_font.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/common/freetype_font.h" @@ -18,9 +18,7 @@ namespace os { -FreeTypeFont::FreeTypeFont(ft::Lib& lib, - const char* filename, - const int height) +FreeTypeFont::FreeTypeFont(ft::Lib& lib, const char* filename, const int height) : m_face(lib.open(filename)) { if (m_face.isValid()) @@ -71,13 +69,11 @@ bool FreeTypeFont::hasCodePoint(int codepoint) const return m_face.hasCodePoint(codepoint); } -Ref load_free_type_font(ft::Lib& lib, - const char* filename, - const int height) +Ref load_free_type_font(ft::Lib& lib, const char* filename, const int height) { Ref font = base::make_ref(lib, filename, height); if (!font->isValid()) - font.reset(); // delete font + font.reset(); // delete font return font; } diff --git a/os/common/freetype_font.h b/os/common/freetype_font.h index e2b2dfa13..2e6dee5df 100644 --- a/os/common/freetype_font.h +++ b/os/common/freetype_font.h @@ -14,35 +14,31 @@ #include "os/font.h" namespace os { - class Font; - - class FreeTypeFont : public Font { - public: - using Face = ft::Face; - - FreeTypeFont(ft::Lib& lib, - const char* filename, - const int height); - ~FreeTypeFont(); - - bool isValid() const; - FontType type() override; - int height() const override; - int textLength(const std::string& str) const override; - bool isScalable() const override; - void setSize(int size) override; - void setAntialias(bool antialias) override; - bool hasCodePoint(int codepoint) const override; - - Face& face() { return m_face; } - - private: - mutable Face m_face; - }; - - Ref load_free_type_font(ft::Lib& lib, - const char* filename, - const int height); +class Font; + +class FreeTypeFont : public Font { +public: + using Face = ft::Face; + + FreeTypeFont(ft::Lib& lib, const char* filename, const int height); + ~FreeTypeFont(); + + bool isValid() const; + FontType type() override; + int height() const override; + int textLength(const std::string& str) const override; + bool isScalable() const override; + void setSize(int size) override; + void setAntialias(bool antialias) override; + bool hasCodePoint(int codepoint) const override; + + Face& face() { return m_face; } + +private: + mutable Face m_face; +}; + +Ref load_free_type_font(ft::Lib& lib, const char* filename, const int height); } // namespace os diff --git a/os/common/generic_surface.h b/os/common/generic_surface.h index 36c1ce85d..6936e1ecd 100644 --- a/os/common/generic_surface.h +++ b/os/common/generic_surface.h @@ -17,8 +17,7 @@ namespace os { namespace { -#define MUL_UN8(a, b, t) \ - ((t) = (a) * (b) + 0x80, ((((t) >> 8) + (t)) >> 8)) +#define MUL_UN8(a, b, t) ((t) = (a) * (b) + 0x80, ((((t) >> 8) + (t)) >> 8)) inline gfx::Color blend(const gfx::Color backdrop, gfx::Color src) { @@ -43,24 +42,25 @@ inline gfx::Color blend(const gfx::Color backdrop, gfx::Color src) int t; Ra = Ba + Sa - MUL_UN8(Ba, Sa, t); - Rr = Br + (Sr-Br) * Sa / Ra; - Rg = Bg + (Sg-Bg) * Sa / Ra; - Rb = Bb + (Sb-Bb) * Sa / Ra; + Rr = Br + (Sr - Br) * Sa / Ra; + Rg = Bg + (Sg - Bg) * Sa / Ra; + Rb = Bb + (Sb - Bb) * Sa / Ra; return gfx::rgba(Rr, Rg, Rb, Ra); } -} // anoynmous namespace +} // namespace template class GenericDrawColoredRgbaSurface : public Base { public: - - void drawColoredRgbaSurface(const Surface* src, gfx::Color fg, gfx::Color bg, const gfx::Clip& clipbase) override { + void drawColoredRgbaSurface(const Surface* src, + gfx::Color fg, + gfx::Color bg, + const gfx::Clip& clipbase) override + { gfx::Clip clip(clipbase); - if (!clip.clip(this->width(), - this->height(), - src->width(), src->height())) + if (!clip.clip(this->width(), this->height(), src->width(), src->height())) return; SurfaceFormatData format; @@ -69,24 +69,21 @@ class GenericDrawColoredRgbaSurface : public Base { ASSERT(format.format == kRgbaSurfaceFormat); ASSERT(format.bitsPerPixel == 32); - for (int v=0; vgetData( - clip.src.x, clip.src.y+v); + for (int v = 0; v < clip.size.h; ++v) { + const uint32_t* ptr = (const uint32_t*)src->getData(clip.src.x, clip.src.y + v); - for (int u=0; ugetPixel(clip.dst.x+u, clip.dst.y+v); + for (int u = 0; u < clip.size.w; ++u) { + gfx::Color dstColor = this->getPixel(clip.dst.x + u, clip.dst.y + v); if (gfx::geta(bg) > 0) dstColor = blend(dstColor, bg); uint32_t src = (((*ptr) & format.alphaMask) >> format.alphaShift); if (src > 0) { - src = gfx::rgba(gfx::getr(fg), - gfx::getg(fg), - gfx::getb(fg), src); + src = gfx::rgba(gfx::getr(fg), gfx::getg(fg), gfx::getb(fg), src); dstColor = blend(dstColor, src); } - this->putPixel(dstColor, clip.dst.x+u, clip.dst.y+v); + this->putPixel(dstColor, clip.dst.x + u, clip.dst.y + v); ++ptr; } } diff --git a/os/common/main.cpp b/os/common/main.cpp index 86fb7f700..2cc86d142 100644 --- a/os/common/main.cpp +++ b/os/common/main.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/memory.h" @@ -23,13 +23,13 @@ extern int app_main(int argc, char* argv[]); #if LAF_WINDOWS -int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - PWSTR lpCmdLine, int nCmdShow) { +int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow) +{ int argc = __argc; char** argv; if (__wargv && argc > 0) { argv = new char*[argc]; - for (int i=0; i 0) { argv = new char*[argc]; - for (int i=0; i= 0 && - codepoint < (int)m_chars.size() && - !m_chars[codepoint].isEmpty()); + return (codepoint >= 0 && codepoint < (int)m_chars.size() && !m_chars[codepoint].isEmpty()); } - Surface* sheetSurface() const { - return m_sheet.get(); - } + Surface* sheetSurface() const { return m_sheet.get(); } - gfx::Rect getCharBounds(int chr) const { + gfx::Rect getCharBounds(int chr) const + { chr -= (int)' '; if (chr >= 0 && chr < (int)m_chars.size()) return m_chars[chr]; @@ -76,7 +71,8 @@ class SpriteSheetFont : public Font { return gfx::Rect(); } - static FontRef fromSurface(const SurfaceRef& sur) { + static FontRef fromSurface(const SurfaceRef& sur) + { auto font = make_ref(); font->m_sheet = sur; @@ -93,9 +89,8 @@ class SpriteSheetFont : public Font { } private: - - bool findChar(const Surface* sur, int width, int height, - gfx::Rect& bounds, gfx::Rect& charBounds) { + bool findChar(const Surface* sur, int width, int height, gfx::Rect& bounds, gfx::Rect& charBounds) + { gfx::Color keyColor = sur->getPixel(0, 0); while (sur->getPixel(bounds.x, bounds.y) == keyColor) { @@ -112,14 +107,14 @@ class SpriteSheetFont : public Font { gfx::Color firstCharPixel = sur->getPixel(bounds.x, bounds.y); bounds.w = 0; - while ((bounds.x+bounds.w < width) && - (sur->getPixel(bounds.x+bounds.w, bounds.y) != keyColor)) { + while ((bounds.x + bounds.w < width) && + (sur->getPixel(bounds.x + bounds.w, bounds.y) != keyColor)) { bounds.w++; } bounds.h = 0; - while ((bounds.y+bounds.h < height) && - (sur->getPixel(bounds.x, bounds.y+bounds.h) != keyColor)) { + while ((bounds.y + bounds.h < height) && + (sur->getPixel(bounds.x, bounds.y + bounds.h) != keyColor)) { bounds.h++; } diff --git a/os/common/system.cpp b/os/common/system.cpp index 76dab7ab6..d881d71cd 100644 --- a/os/common/system.cpp +++ b/os/common/system.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/common/system.h" @@ -74,23 +74,25 @@ FontRef CommonSystem::loadTrueTypeFont(const char* filename, int height) KeyModifiers CommonSystem::keyModifiers() { - return - (KeyModifiers) - ((isKeyPressed(kKeyLShift) || - isKeyPressed(kKeyRShift) ? kKeyShiftModifier: 0) | - (isKeyPressed(kKeyLControl) || - isKeyPressed(kKeyRControl) ? kKeyCtrlModifier: 0) | - (isKeyPressed(kKeyAlt) ? kKeyAltModifier: 0) | - (isKeyPressed(kKeyAltGr) ? (kKeyCtrlModifier | kKeyAltModifier): 0) | - (isKeyPressed(kKeyCommand) ? kKeyCmdModifier: 0) | - (isKeyPressed(kKeySpace) ? kKeySpaceModifier: 0) | - (isKeyPressed(kKeyLWin) || - isKeyPressed(kKeyRWin) ? kKeyWinModifier: 0)); + return ( + KeyModifiers)((isKeyPressed(kKeyLShift) || isKeyPressed(kKeyRShift) ? kKeyShiftModifier : 0) | + (isKeyPressed(kKeyLControl) || isKeyPressed(kKeyRControl) ? kKeyCtrlModifier : + 0) | + (isKeyPressed(kKeyAlt) ? kKeyAltModifier : 0) | + (isKeyPressed(kKeyAltGr) ? (kKeyCtrlModifier | kKeyAltModifier) : 0) | + (isKeyPressed(kKeyCommand) ? kKeyCmdModifier : 0) | + (isKeyPressed(kKeySpace) ? kKeySpaceModifier : 0) | + (isKeyPressed(kKeyLWin) || isKeyPressed(kKeyRWin) ? kKeyWinModifier : 0)); } #if CLIP_ENABLE_IMAGE -void get_rgba32(const clip::image_spec& spec, const uint8_t* scanlineAddr, int* r, int* g, int* b, int* a) +void get_rgba32(const clip::image_spec& spec, + const uint8_t* scanlineAddr, + int* r, + int* g, + int* b, + int* a) { uint32_t c = *((uint32_t*)scanlineAddr); if (spec.alpha_mask) @@ -100,26 +102,36 @@ void get_rgba32(const clip::image_spec& spec, const uint8_t* scanlineAddr, int* // The source image is in straight-alpha and makeRgbaSurface returns a // surface using premultiplied-alpha so we have to premultiply the // source values. - *r = ((c & spec.red_mask) >> spec.red_shift )*(*a)/255; - *g = ((c & spec.green_mask)>> spec.green_shift)*(*a)/255; - *b = ((c & spec.blue_mask) >> spec.blue_shift )*(*a)/255; + *r = ((c & spec.red_mask) >> spec.red_shift) * (*a) / 255; + *g = ((c & spec.green_mask) >> spec.green_shift) * (*a) / 255; + *b = ((c & spec.blue_mask) >> spec.blue_shift) * (*a) / 255; } -void get_rgba24(const clip::image_spec& spec, const uint8_t* scanlineAddr, int* r, int* g, int* b, int* a) +void get_rgba24(const clip::image_spec& spec, + const uint8_t* scanlineAddr, + int* r, + int* g, + int* b, + int* a) { uint32_t c = *((uint32_t*)scanlineAddr); - *r = ((c & spec.red_mask) >> spec.red_shift); - *g = ((c & spec.green_mask)>> spec.green_shift); + *r = ((c & spec.red_mask) >> spec.red_shift); + *g = ((c & spec.green_mask) >> spec.green_shift); *b = ((c & spec.blue_mask) >> spec.blue_shift); *a = 255; } -void get_rgba16(const clip::image_spec& spec, const uint8_t* scanlineAddr, int* r, int* g, int* b, int* a) +void get_rgba16(const clip::image_spec& spec, + const uint8_t* scanlineAddr, + int* r, + int* g, + int* b, + int* a) { uint16_t c = *((uint16_t*)scanlineAddr); - *r = (((c & spec.red_mask )>>spec.red_shift )*255) / (spec.red_mask >>spec.red_shift); - *g = (((c & spec.green_mask)>>spec.green_shift)*255) / (spec.green_mask>>spec.green_shift); - *b = (((c & spec.blue_mask )>>spec.blue_shift )*255) / (spec.blue_mask >>spec.blue_shift); + *r = (((c & spec.red_mask) >> spec.red_shift) * 255) / (spec.red_mask >> spec.red_shift); + *g = (((c & spec.green_mask) >> spec.green_shift) * 255) / (spec.green_mask >> spec.green_shift); + *b = (((c & spec.blue_mask) >> spec.blue_shift) * 255) / (spec.blue_mask >> spec.blue_shift); *a = 255; } @@ -127,9 +139,7 @@ SurfaceRef CommonSystem::makeSurface(const clip::image& image) { const clip::image_spec spec = image.spec(); - if (spec.bits_per_pixel != 32 && - spec.bits_per_pixel != 24 && - spec.bits_per_pixel != 16) + if (spec.bits_per_pixel != 32 && spec.bits_per_pixel != 24 && spec.bits_per_pixel != 16) return nullptr; SurfaceRef surface = ((System*)this)->makeRgbaSurface(spec.width, spec.height); @@ -139,29 +149,21 @@ SurfaceRef CommonSystem::makeSurface(const clip::image& image) // Select color components retrieval function. void (*get_rgba)(const clip::image_spec&, const uint8_t*, int*, int*, int*, int*); switch (spec.bits_per_pixel) { - case 32: - get_rgba = get_rgba32; - break; - case 24: - get_rgba = get_rgba24; - break; - case 16: - get_rgba = get_rgba16; - break; + case 32: get_rgba = get_rgba32; break; + case 24: get_rgba = get_rgba24; break; + case 16: get_rgba = get_rgba16; break; } - for (int v=0; vgetData(0, v); const uint8_t* src = ((uint8_t*)image.data()) + v * spec.bytes_per_row; - for (int u=0; u; +class Cursor; +using CursorRef = Ref; - class Cursor : public RefCount { - public: - virtual ~Cursor() { } - virtual void* nativeHandle() = 0; - }; +class Cursor : public RefCount { +public: + virtual ~Cursor() {} + virtual void* nativeHandle() = 0; +}; } // namespace os diff --git a/os/dnd.cpp b/os/dnd.cpp index 1b8155f43..6eaae5d02 100644 --- a/os/dnd.cpp +++ b/os/dnd.cpp @@ -6,12 +6,12 @@ #if CLIP_ENABLE_IMAGE -#ifdef HAVE_CONFIG_H - #include "config.h" -#endif + #ifdef HAVE_CONFIG_H + #include "config.h" + #endif -#include "os/dnd.h" -#include "os/system.h" + #include "os/dnd.h" + #include "os/system.h" namespace os { @@ -62,4 +62,4 @@ SurfaceRef decode_gif(const uint8_t* buf, const uint32_t len) } // namespace os -#endif \ No newline at end of file +#endif diff --git a/os/dnd.h b/os/dnd.h index 557c2fbad..b8c8fb9c8 100644 --- a/os/dnd.h +++ b/os/dnd.h @@ -8,8 +8,8 @@ #define OS_DND_H_INCLUDED #pragma once -#include "base/paths.h" #include "base/debug.h" +#include "base/paths.h" #include "gfx/point.h" #include "os/surface.h" @@ -20,116 +20,117 @@ namespace os { - SurfaceRef default_decode_png(const uint8_t* buf, uint32_t len); - SurfaceRef default_decode_jpg(const uint8_t* buf, uint32_t len); - SurfaceRef default_decode_bmp(const uint8_t* buf, uint32_t len); - SurfaceRef default_decode_gif(const uint8_t* buf, uint32_t len); +SurfaceRef default_decode_png(const uint8_t* buf, uint32_t len); +SurfaceRef default_decode_jpg(const uint8_t* buf, uint32_t len); +SurfaceRef default_decode_bmp(const uint8_t* buf, uint32_t len); +SurfaceRef default_decode_gif(const uint8_t* buf, uint32_t len); - class Window; +class Window; #if CLIP_ENABLE_IMAGE - using DecoderFunc = SurfaceRef(*)(const uint8_t* buf, uint32_t len); +using DecoderFunc = SurfaceRef (*)(const uint8_t* buf, uint32_t len); - // Methods used to configure custom decoder functions by replacing the default implementations. +// Methods used to configure custom decoder functions by replacing the default implementations. - void set_decode_png(DecoderFunc func); - void set_decode_jpg(DecoderFunc func); - void set_decode_bmp(DecoderFunc func); - void set_decode_gif(DecoderFunc func); +void set_decode_png(DecoderFunc func); +void set_decode_jpg(DecoderFunc func); +void set_decode_bmp(DecoderFunc func); +void set_decode_gif(DecoderFunc func); - SurfaceRef decode_png(const uint8_t* buf, uint32_t len); - SurfaceRef decode_jpg(const uint8_t* buf, uint32_t len); - SurfaceRef decode_bmp(const uint8_t* buf, uint32_t len); - SurfaceRef decode_gif(const uint8_t* buf, uint32_t len); +SurfaceRef decode_png(const uint8_t* buf, uint32_t len); +SurfaceRef decode_jpg(const uint8_t* buf, uint32_t len); +SurfaceRef decode_bmp(const uint8_t* buf, uint32_t len); +SurfaceRef decode_gif(const uint8_t* buf, uint32_t len); #endif - // Operations that can be supported by source and target windows in a drag - // and drop operation. - enum class DropOperation { - None = 0, - Copy = 1, - Move = 2, - Link = 4, - All = Copy | Move | Link, - }; - - // Types of representations supported for each DragDataItem. - enum class DragDataItemType { - Paths, - Image, - Url, - }; - - // Interface to get dragged data from the platform's implementation. - class DragDataProvider { - public: - virtual ~DragDataProvider() {} - virtual base::paths getPaths() = 0; +// Operations that can be supported by source and target windows in a drag +// and drop operation. +enum class DropOperation { + None = 0, + Copy = 1, + Move = 2, + Link = 4, + All = Copy | Move | Link, +}; + +// Types of representations supported for each DragDataItem. +enum class DragDataItemType { + Paths, + Image, + Url, +}; + +// Interface to get dragged data from the platform's implementation. +class DragDataProvider { +public: + virtual ~DragDataProvider() {} + virtual base::paths getPaths() = 0; #if CLIP_ENABLE_IMAGE - virtual SurfaceRef getImage() = 0; + virtual SurfaceRef getImage() = 0; #endif - virtual std::string getUrl() = 0; - virtual bool contains(DragDataItemType type) { return false; } - }; - - class DragEvent { - public: - DragEvent(os::Window* target, - DropOperation supportedOperations, - const gfx::Point& dragPosition, - std::unique_ptr& dataProvider) - : m_target(target) - , m_supportedOperations(supportedOperations) - , m_position(dragPosition) - , m_dataProvider(std::move(dataProvider)) {} - - // Destination window of the DragEvent. - os::Window* target() const { return m_target; } - DropOperation dropResult() const { return m_dropResult; } - DropOperation supportedOperations() const { return m_supportedOperations; } - bool acceptDrop() const { return m_acceptDrop; } - const gfx::Point& position() { return m_position; } - DragDataProvider* dataProvider() { return m_dataProvider.get(); } - - // Sets what will be the outcome of dropping the dragged data when it is - // accepted by the target window. Only one of the enum values should be passed, - // do not combine values using bitwise operators. - void dropResult(DropOperation operation) { m_dropResult = operation; } - // Set this to true when the dropped data was accepted/processed by the - // target window, or set to false otherwise. - void acceptDrop(bool value) { m_acceptDrop = value; } - - bool sourceSupports(DropOperation op) { - return (static_cast(m_supportedOperations) & static_cast(op)) - == static_cast(op); - } - - private: - os::Window* m_target = nullptr; - DropOperation m_dropResult = DropOperation::Copy; - // Bitwise OR of the operations supported by the drag and drop source. - DropOperation m_supportedOperations; - bool m_acceptDrop = false; - gfx::Point m_position; - std::unique_ptr m_dataProvider = nullptr; - }; - - class DragTarget { - public: - virtual ~DragTarget() {}; - - // Called when a drag action enters a window that supports DnD. The - // DragEvent::dropResult must be set to the operation that is expected - // to occur by the target window once the drop is accepted. - virtual void dragEnter(os::DragEvent& ev) {} - // Called when the dragged data exits the window that supports DnD. - virtual void dragLeave(os::DragEvent& ev) {} - virtual void drag(os::DragEvent& ev) {} - virtual void drop(os::DragEvent& ev) {} - }; - + virtual std::string getUrl() = 0; + virtual bool contains(DragDataItemType type) { return false; } +}; + +class DragEvent { +public: + DragEvent(os::Window* target, + DropOperation supportedOperations, + const gfx::Point& dragPosition, + std::unique_ptr& dataProvider) + : m_target(target) + , m_supportedOperations(supportedOperations) + , m_position(dragPosition) + , m_dataProvider(std::move(dataProvider)) + { + } + + // Destination window of the DragEvent. + os::Window* target() const { return m_target; } + DropOperation dropResult() const { return m_dropResult; } + DropOperation supportedOperations() const { return m_supportedOperations; } + bool acceptDrop() const { return m_acceptDrop; } + const gfx::Point& position() { return m_position; } + DragDataProvider* dataProvider() { return m_dataProvider.get(); } + + // Sets what will be the outcome of dropping the dragged data when it is + // accepted by the target window. Only one of the enum values should be passed, + // do not combine values using bitwise operators. + void dropResult(DropOperation operation) { m_dropResult = operation; } + // Set this to true when the dropped data was accepted/processed by the + // target window, or set to false otherwise. + void acceptDrop(bool value) { m_acceptDrop = value; } + + bool sourceSupports(DropOperation op) + { + return (static_cast(m_supportedOperations) & static_cast(op)) == static_cast(op); + } + +private: + os::Window* m_target = nullptr; + DropOperation m_dropResult = DropOperation::Copy; + // Bitwise OR of the operations supported by the drag and drop source. + DropOperation m_supportedOperations; + bool m_acceptDrop = false; + gfx::Point m_position; + std::unique_ptr m_dataProvider = nullptr; +}; + +class DragTarget { +public: + virtual ~DragTarget() {}; + + // Called when a drag action enters a window that supports DnD. The + // DragEvent::dropResult must be set to the operation that is expected + // to occur by the target window once the drop is accepted. + virtual void dragEnter(os::DragEvent& ev) {} + // Called when the dragged data exits the window that supports DnD. + virtual void dragLeave(os::DragEvent& ev) {} + virtual void drag(os::DragEvent& ev) {} + virtual void drop(os::DragEvent& ev) {} +}; } // namespace os #pragma pop_macro("None") -#endif \ No newline at end of file +#endif diff --git a/os/draw_text.cpp b/os/draw_text.cpp index 41094ad34..2dd137bcf 100644 --- a/os/draw_text.cpp +++ b/os/draw_text.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/draw_text.h" @@ -20,10 +20,13 @@ namespace os { -gfx::Rect draw_text(Surface* surface, Font* font, +gfx::Rect draw_text(Surface* surface, + Font* font, const std::string& text, - gfx::Color fg, gfx::Color bg, - int x, int y, + gfx::Color fg, + gfx::Color bg, + int x, + int y, DrawTextDelegate* delegate) { base::utf8_decode decode(text); @@ -45,7 +48,7 @@ retry:; if (!newFont) break; - y += font->height()/2 - newFont->height()/2; + y += font->height() / 2 - newFont->height() / 2; font = newFont; goto retry; @@ -54,7 +57,6 @@ retry:; } switch (font->type()) { - case FontType::Unknown: // Do nothing break; @@ -120,17 +122,13 @@ retry:; gfx::Rect origDstBounds; const auto* glyph = feg.glyph(); if (glyph) - origDstBounds = gfx::Rect( - x + int(glyph->startX), - y + int(glyph->y), - int(glyph->endX) - int(glyph->startX), - int(glyph->bitmap->rows) ? int(glyph->bitmap->rows): 1); + origDstBounds = gfx::Rect(x + int(glyph->startX), + y + int(glyph->y), + int(glyph->endX) - int(glyph->startX), + int(glyph->bitmap->rows) ? int(glyph->bitmap->rows) : 1); if (delegate) { - delegate->preProcessChar( - feg.charIndex(), - feg.unicodeChar(), - fg, bg, origDstBounds); + delegate->preProcessChar(feg.charIndex(), feg.unicodeChar(), fg, bg, origDstBounds); } if (!glyph) @@ -151,13 +149,11 @@ retry:; const int clippedRows = dstBounds.y - origDstBounds.y; int dst_y = dstBounds.y; int t; - for (int v=0; vbitmap->buffer - + (v+clippedRows)*glyph->bitmap->pitch; + const uint8_t* p = glyph->bitmap->buffer + (v + clippedRows) * glyph->bitmap->pitch; int dst_x = dstBounds.x; - uint32_t* dst_address = - (uint32_t*)surface->getData(dst_x, dst_y); + uint32_t* dst_address = (uint32_t*)surface->getData(dst_x, dst_y); // TODO maybe if we are trying to draw in a SkiaSurface with a nullptr m_bitmap // (when GPU-acceleration is enabled) @@ -165,7 +161,7 @@ retry:; break; // Skip first clipped pixels - for (int u=0; ubitmap->pixel_mode == FT_PIXEL_MODE_GRAY) { ++p; } @@ -177,7 +173,7 @@ retry:; } } - for (int u=0; ubitmap->pixel_mode == FT_PIXEL_MODE_MONO) { - alpha = ((*p) & (1 << (7 - (bit++))) ? 255: 0); + alpha = ((*p) & (1 << (7 - (bit++))) ? 255 : 0); if (bit == 8) { bit = 0; ++p; @@ -193,35 +189,33 @@ retry:; } const uint32_t backdrop = *dst_address; - const gfx::Color backdropColor = - gfx::rgba( - ((backdrop & fd.redMask) >> fd.redShift), - ((backdrop & fd.greenMask) >> fd.greenShift), - ((backdrop & fd.blueMask) >> fd.blueShift), - ((backdrop & fd.alphaMask) >> fd.alphaShift)); - - gfx::Color output = gfx::rgba(gfx::getr(fg), - gfx::getg(fg), - gfx::getb(fg), - MUL_UN8(fg_alpha, alpha, t)); + const gfx::Color backdropColor = gfx::rgba( + ((backdrop & fd.redMask) >> fd.redShift), + ((backdrop & fd.greenMask) >> fd.greenShift), + ((backdrop & fd.blueMask) >> fd.blueShift), + ((backdrop & fd.alphaMask) >> fd.alphaShift)); + + gfx::Color output = + gfx::rgba(gfx::getr(fg), gfx::getg(fg), gfx::getb(fg), MUL_UN8(fg_alpha, alpha, t)); if (gfx::geta(bg) > 0) output = blend(blend(backdropColor, bg), output); else output = blend(backdropColor, output); - *dst_address = - ((gfx::getr(output) << fd.redShift ) & fd.redMask ) | - ((gfx::getg(output) << fd.greenShift) & fd.greenMask) | - ((gfx::getb(output) << fd.blueShift ) & fd.blueMask ) | - ((gfx::geta(output) << fd.alphaShift) & fd.alphaMask); + *dst_address = ((gfx::getr(output) << fd.redShift) & fd.redMask) | + ((gfx::getg(output) << fd.greenShift) & fd.greenMask) | + ((gfx::getb(output) << fd.blueShift) & fd.blueMask) | + ((gfx::geta(output) << fd.alphaShift) & fd.alphaMask); ++dst_address; } } } - if (!origDstBounds.w) origDstBounds.w = 1; - if (!origDstBounds.h) origDstBounds.h = 1; + if (!origDstBounds.w) + origDstBounds.w = 1; + if (!origDstBounds.h) + origDstBounds.h = 1; textBounds |= origDstBounds; if (delegate) delegate->postDrawChar(origDstBounds); @@ -231,7 +225,6 @@ retry:; surface->unlock(); break; } - } return textBounds; diff --git a/os/draw_text.h b/os/draw_text.h index 971d90997..3d09baffa 100644 --- a/os/draw_text.h +++ b/os/draw_text.h @@ -15,67 +15,72 @@ namespace os { - class Font; - class Surface; - class Paint; +class Font; +class Surface; +class Paint; - enum class TextAlign { Left, Center, Right }; +enum class TextAlign { Left, Center, Right }; - class DrawTextDelegate { - public: - virtual ~DrawTextDelegate() { } +class DrawTextDelegate { +public: + virtual ~DrawTextDelegate() {} - // This is called before drawing the character. - virtual void preProcessChar(const int index, - const int codepoint, - gfx::Color& fg, - gfx::Color& bg, - const gfx::Rect& charBounds) { - // Do nothing - } + // This is called before drawing the character. + virtual void preProcessChar(const int index, + const int codepoint, + gfx::Color& fg, + gfx::Color& bg, + const gfx::Rect& charBounds) + { + // Do nothing + } - virtual bool preDrawChar(const gfx::Rect& charBounds) { - // Returns false if the process should stop here. - return true; - } + virtual bool preDrawChar(const gfx::Rect& charBounds) + { + // Returns false if the process should stop here. + return true; + } - virtual void postDrawChar(const gfx::Rect& charBounds) { - // Do nothing - } - }; + virtual void postDrawChar(const gfx::Rect& charBounds) + { + // Do nothing + } +}; - // The surface can be nullptr just to process the string - // (e.g. measure how much space will use the text without drawing - // it). It uses FreeType2 library and harfbuzz. Doesn't support RTL - // (right-to-left) languages. - gfx::Rect draw_text( - Surface* surface, Font* font, - const std::string& text, - gfx::Color fg, gfx::Color bg, - int x, int y, - DrawTextDelegate* delegate); +// The surface can be nullptr just to process the string +// (e.g. measure how much space will use the text without drawing +// it). It uses FreeType2 library and harfbuzz. Doesn't support RTL +// (right-to-left) languages. +gfx::Rect draw_text(Surface* surface, + Font* font, + const std::string& text, + gfx::Color fg, + gfx::Color bg, + int x, + int y, + DrawTextDelegate* delegate); - // Uses SkTextUtils::Draw() to draw text (doesn't depend on harfbuzz - // or big dependencies, useful to print English text only). - void draw_text( - Surface* surface, Font* font, - const std::string& text, - const gfx::Point& pos, - const Paint* paint = nullptr, - const TextAlign textAlign = TextAlign::Left, - DrawTextDelegate* delegate = nullptr); +// Uses SkTextUtils::Draw() to draw text (doesn't depend on harfbuzz +// or big dependencies, useful to print English text only). +void draw_text(Surface* surface, + Font* font, + const std::string& text, + const gfx::Point& pos, + const Paint* paint = nullptr, + const TextAlign textAlign = TextAlign::Left, + DrawTextDelegate* delegate = nullptr); - // Uses SkShaper::Make() to draw text (harfbuzz if available), - // useful for RTL (right-to-left) languages. Avoid this function if - // you are not going to translate your app to non-English languages - // (prefer os::draw_text() when possible). - void draw_text_with_shaper( - Surface* surface, Font* font, - const std::string& text, - const gfx::Point& pos, - const Paint* paint = nullptr, - const TextAlign textAlign = TextAlign::Left, - DrawTextDelegate* delegate = nullptr); +// Uses SkShaper::Make() to draw text (harfbuzz if available), +// useful for RTL (right-to-left) languages. Avoid this function if +// you are not going to translate your app to non-English languages +// (prefer os::draw_text() when possible). +void draw_text_with_shaper(Surface* surface, + Font* font, + const std::string& text, + const gfx::Point& pos, + const Paint* paint = nullptr, + const TextAlign textAlign = TextAlign::Left, + DrawTextDelegate* delegate = nullptr); } // namespace os diff --git a/os/error.h b/os/error.h index a01288707..e57ea05e8 100644 --- a/os/error.h +++ b/os/error.h @@ -10,7 +10,7 @@ namespace os { - void error_message(const char* msg); +void error_message(const char* msg); } // namespace os diff --git a/os/event.h b/os/event.h index 8acb92709..119d35dfa 100644 --- a/os/event.h +++ b/os/event.h @@ -23,137 +23,143 @@ namespace os { - class Event { - public: - enum Type { - None, - - // macOS: When the Quit option is selected from the popup menu - // of the app icon in the dock bar. - CloseApp, - - // When the X is pressed in the current window. - CloseWindow, - - // When the window is resized/maximized/restored (any time the - // client area size of the window changes) - ResizeWindow, - - // Some files are dropped in the window - DropFiles, - - // Common mouse events - MouseEnter, - MouseLeave, - MouseMove, - MouseDown, - MouseUp, - MouseWheel, - MouseDoubleClick, - - // A key is pressed (or is autorepeated if the key is kept pressed) - KeyDown, - - // A key is released - KeyUp, - - // Pinch gesture with fingers to zoom in/out - TouchMagnify, - Callback, - }; - - enum MouseButton { - NoneButton, - LeftButton, - RightButton, - MiddleButton, - X1Button, - X2Button, - }; - - Event() : m_type(None), - m_window(nullptr), - m_scancode(kKeyNil), - m_modifiers(kKeyUninitializedModifier), - m_unicodeChar(0), - m_isDead(false), - m_repeat(0), - m_preciseWheel(false), - m_pointerType(PointerType::Unknown), - m_button(NoneButton), - m_magnification(0.0f), - m_pressure(0.0f) { - } - - Type type() const { return m_type; } - const WindowRef& window() const { return m_window; } - const base::paths& files() const { return m_files; } - // TODO Rename this to virtualKey(), which is the real - // meaning. Then we need another kind of "scan code" with the - // position in the keyboard, which might be useful to identify - // keys by its position (e.g. WASD keys in other keyboard - // layouts). - KeyScancode scancode() const { return m_scancode; } - KeyModifiers modifiers() const { return m_modifiers; } - int unicodeChar() const { return m_unicodeChar; } - bool isDeadKey() const { return m_isDead; } - int repeat() const { return m_repeat; } - gfx::Point position() const { return m_position; } - gfx::Point wheelDelta() const { return m_wheelDelta; } - - // We suppose that if we are receiving precise scrolling deltas, - // it means that the user is using a touch-like surface (trackpad, - // magic mouse scrolling, touch wacom tablet, etc.) - bool preciseWheel() const { return m_preciseWheel; } - - PointerType pointerType() const { return m_pointerType; } - MouseButton button() const { return m_button; } - float magnification() const { return m_magnification; } - float pressure() const { return m_pressure; } - - void setType(Type type) { m_type = type; } - void setWindow(const WindowRef& window) { m_window = window; } - void setFiles(const base::paths& files) { m_files = files; } - void setCallback(std::function&& func) { m_callback = std::move(func); } - - void setScancode(KeyScancode scancode) { m_scancode = scancode; } - void setModifiers(KeyModifiers modifiers) { m_modifiers = modifiers; } - void setUnicodeChar(int unicodeChar) { m_unicodeChar = unicodeChar; } - void setDeadKey(bool state) { m_isDead = state; } - void setRepeat(int repeat) { m_repeat = repeat; } - void setPosition(const gfx::Point& pos) { m_position = pos; } - void setWheelDelta(const gfx::Point& delta) { m_wheelDelta = delta; } - void setPreciseWheel(bool precise) { m_preciseWheel = precise; } - void setPointerType(PointerType pointerType) { m_pointerType = pointerType; } - void setButton(MouseButton button) { m_button = button; } - void setMagnification(float magnification) { m_magnification = magnification; } - void setPressure(float pressure) { m_pressure = pressure; } - - void execCallback() { if (m_callback) m_callback(); } - - private: - Type m_type; - WindowRef m_window; - base::paths m_files; - std::function m_callback; - KeyScancode m_scancode; - KeyModifiers m_modifiers; - int m_unicodeChar; - bool m_isDead; - int m_repeat; // repeat=0 means the first time the key is pressed - gfx::Point m_position; - gfx::Point m_wheelDelta; - bool m_preciseWheel; - PointerType m_pointerType; - MouseButton m_button; - - // For TouchMagnify event - float m_magnification; - - // Pressure of stylus used in mouse-like events - float m_pressure; +class Event { +public: + enum Type { + None, + + // macOS: When the Quit option is selected from the popup menu + // of the app icon in the dock bar. + CloseApp, + + // When the X is pressed in the current window. + CloseWindow, + + // When the window is resized/maximized/restored (any time the + // client area size of the window changes) + ResizeWindow, + + // Some files are dropped in the window + DropFiles, + + // Common mouse events + MouseEnter, + MouseLeave, + MouseMove, + MouseDown, + MouseUp, + MouseWheel, + MouseDoubleClick, + + // A key is pressed (or is autorepeated if the key is kept pressed) + KeyDown, + + // A key is released + KeyUp, + + // Pinch gesture with fingers to zoom in/out + TouchMagnify, + Callback, }; + enum MouseButton { + NoneButton, + LeftButton, + RightButton, + MiddleButton, + X1Button, + X2Button, + }; + + Event() + : m_type(None) + , m_window(nullptr) + , m_scancode(kKeyNil) + , m_modifiers(kKeyUninitializedModifier) + , m_unicodeChar(0) + , m_isDead(false) + , m_repeat(0) + , m_preciseWheel(false) + , m_pointerType(PointerType::Unknown) + , m_button(NoneButton) + , m_magnification(0.0f) + , m_pressure(0.0f) + { + } + + Type type() const { return m_type; } + const WindowRef& window() const { return m_window; } + const base::paths& files() const { return m_files; } + // TODO Rename this to virtualKey(), which is the real + // meaning. Then we need another kind of "scan code" with the + // position in the keyboard, which might be useful to identify + // keys by its position (e.g. WASD keys in other keyboard + // layouts). + KeyScancode scancode() const { return m_scancode; } + KeyModifiers modifiers() const { return m_modifiers; } + int unicodeChar() const { return m_unicodeChar; } + bool isDeadKey() const { return m_isDead; } + int repeat() const { return m_repeat; } + gfx::Point position() const { return m_position; } + gfx::Point wheelDelta() const { return m_wheelDelta; } + + // We suppose that if we are receiving precise scrolling deltas, + // it means that the user is using a touch-like surface (trackpad, + // magic mouse scrolling, touch wacom tablet, etc.) + bool preciseWheel() const { return m_preciseWheel; } + + PointerType pointerType() const { return m_pointerType; } + MouseButton button() const { return m_button; } + float magnification() const { return m_magnification; } + float pressure() const { return m_pressure; } + + void setType(Type type) { m_type = type; } + void setWindow(const WindowRef& window) { m_window = window; } + void setFiles(const base::paths& files) { m_files = files; } + void setCallback(std::function&& func) { m_callback = std::move(func); } + + void setScancode(KeyScancode scancode) { m_scancode = scancode; } + void setModifiers(KeyModifiers modifiers) { m_modifiers = modifiers; } + void setUnicodeChar(int unicodeChar) { m_unicodeChar = unicodeChar; } + void setDeadKey(bool state) { m_isDead = state; } + void setRepeat(int repeat) { m_repeat = repeat; } + void setPosition(const gfx::Point& pos) { m_position = pos; } + void setWheelDelta(const gfx::Point& delta) { m_wheelDelta = delta; } + void setPreciseWheel(bool precise) { m_preciseWheel = precise; } + void setPointerType(PointerType pointerType) { m_pointerType = pointerType; } + void setButton(MouseButton button) { m_button = button; } + void setMagnification(float magnification) { m_magnification = magnification; } + void setPressure(float pressure) { m_pressure = pressure; } + + void execCallback() + { + if (m_callback) + m_callback(); + } + +private: + Type m_type; + WindowRef m_window; + base::paths m_files; + std::function m_callback; + KeyScancode m_scancode; + KeyModifiers m_modifiers; + int m_unicodeChar; + bool m_isDead; + int m_repeat; // repeat=0 means the first time the key is pressed + gfx::Point m_position; + gfx::Point m_wheelDelta; + bool m_preciseWheel; + PointerType m_pointerType; + MouseButton m_button; + + // For TouchMagnify event + float m_magnification; + + // Pressure of stylus used in mouse-like events + float m_pressure; +}; + } // namespace os #pragma pop_macro("None") diff --git a/os/event_queue.h b/os/event_queue.h index 1c44ba7ff..c1c761919 100644 --- a/os/event_queue.h +++ b/os/event_queue.h @@ -11,46 +11,47 @@ namespace os { - class Event; - - class EventQueue { - public: - static constexpr const double kWithoutTimeout = -1.0; - - virtual ~EventQueue() { } - - // Wait for a new event. We can specify a timeout in seconds to - // limit the time of wait for the next event. - virtual void getEvent(Event& ev, double timeout = kWithoutTimeout) = 0; - - // Adds a new event in the queue to be processed by - // getEvent(). It's used by each platform to convert - // platform-specific messages into platform-independent events - // (os::Event). - virtual void queueEvent(const Event& ev) = 0; - - // Clears all events in the queue. You shouldn't call this - // function, it's used internally to clear all events before the - // System instance is destroyed. Anyway you might want to use it - // in case that you want to ensure that no more WindowRef is - // alive. - virtual void clearEvents() = 0; - - // Deprecated old method. We should remove this line after some - // releases. It's here to avoid calling getEvent(Event&, double) - // even when we use a bool 2nd argument. - void getEvent(Event& ev, bool) = delete; - - // On macOS we need the EventQueue before the creation of the - // System. E.g. when we double-click a file an Event to open that - // file is queued in application:openFile:, code which is executed - // before the user's main() code. - static EventQueue* instance(); - }; - - inline void queue_event(const Event& ev) { - EventQueue::instance()->queueEvent(ev); - } +class Event; + +class EventQueue { +public: + static constexpr const double kWithoutTimeout = -1.0; + + virtual ~EventQueue() {} + + // Wait for a new event. We can specify a timeout in seconds to + // limit the time of wait for the next event. + virtual void getEvent(Event& ev, double timeout = kWithoutTimeout) = 0; + + // Adds a new event in the queue to be processed by + // getEvent(). It's used by each platform to convert + // platform-specific messages into platform-independent events + // (os::Event). + virtual void queueEvent(const Event& ev) = 0; + + // Clears all events in the queue. You shouldn't call this + // function, it's used internally to clear all events before the + // System instance is destroyed. Anyway you might want to use it + // in case that you want to ensure that no more WindowRef is + // alive. + virtual void clearEvents() = 0; + + // Deprecated old method. We should remove this line after some + // releases. It's here to avoid calling getEvent(Event&, double) + // even when we use a bool 2nd argument. + void getEvent(Event& ev, bool) = delete; + + // On macOS we need the EventQueue before the creation of the + // System. E.g. when we double-click a file an Event to open that + // file is queued in application:openFile:, code which is executed + // before the user's main() code. + static EventQueue* instance(); +}; + +inline void queue_event(const Event& ev) +{ + EventQueue::instance()->queueEvent(ev); +} } // namespace os diff --git a/os/font.h b/os/font.h index ca834f54a..84ac3f5fb 100644 --- a/os/font.h +++ b/os/font.h @@ -16,40 +16,36 @@ namespace os { - class Font; - class FontStyle; - class Typeface; - using FontRef = Ref; - - enum class FontType { - Unknown, - SpriteSheet, // SpriteSheet - FreeType, // FreeType - Native, // Skia - }; - - class Font : public RefCount { - public: - Font() : m_fallback(nullptr) { } - virtual ~Font() { } - virtual FontType type() = 0; - virtual int height() const = 0; - virtual int textLength(const std::string& str) const = 0; - virtual bool isScalable() const = 0; - virtual void setSize(int size) = 0; - virtual void setAntialias(bool antialias) = 0; - virtual bool hasCodePoint(int codepoint) const = 0; - - Font* fallback() const { - return m_fallback; - } - void setFallback(Font* font) { - m_fallback = font; - } - - private: - Font* m_fallback; - }; +class Font; +class FontStyle; +class Typeface; +using FontRef = Ref; + +enum class FontType { + Unknown, + SpriteSheet, // SpriteSheet + FreeType, // FreeType + Native, // Skia +}; + +class Font : public RefCount { +public: + Font() : m_fallback(nullptr) {} + virtual ~Font() {} + virtual FontType type() = 0; + virtual int height() const = 0; + virtual int textLength(const std::string& str) const = 0; + virtual bool isScalable() const = 0; + virtual void setSize(int size) = 0; + virtual void setAntialias(bool antialias) = 0; + virtual bool hasCodePoint(int codepoint) const = 0; + + Font* fallback() const { return m_fallback; } + void setFallback(Font* font) { m_fallback = font; } + +private: + Font* m_fallback; +}; } // namespace os diff --git a/os/font_manager.h b/os/font_manager.h index 5cec28bda..8689f39df 100644 --- a/os/font_manager.h +++ b/os/font_manager.h @@ -15,15 +15,16 @@ namespace os { - class FontManager : public RefCount { - protected: - virtual ~FontManager() { } - public: - virtual int countFamilies() const = 0; - virtual std::string familyName(int index) const = 0; - virtual Ref familyStyleSet(int index) const = 0; - virtual Ref matchFamily(const std::string& familyName) const = 0; - }; +class FontManager : public RefCount { +protected: + virtual ~FontManager() {} + +public: + virtual int countFamilies() const = 0; + virtual std::string familyName(int index) const = 0; + virtual Ref familyStyleSet(int index) const = 0; + virtual Ref matchFamily(const std::string& familyName) const = 0; +}; } // namespace os diff --git a/os/font_style.h b/os/font_style.h index ec2e8948d..b5f6b4937 100644 --- a/os/font_style.h +++ b/os/font_style.h @@ -12,79 +12,77 @@ namespace os { - class FontStyle { - public: - enum class Weight { - Invisible = 0, - Thin = 100, - ExtraLight = 200, - Light = 300, - Normal = 400, - Medium = 500, - SemiBold = 600, - Bold = 700, - ExtraBold = 800, - Black = 900, - ExtraBlack = 1000, - }; - - enum class Width { - UltraCondensed = 1, - ExtraCondensed = 2, - Condensed = 3, - SemiCondensed = 4, - Normal = 5, - SemiExpanded = 6, - Expanded = 7, - ExtraExpanded = 8, - UltraExpanded = 9, - }; - - enum class Slant { - Upright, - Italic, - Oblique, - }; - - constexpr FontStyle(const Weight weight, - const Width width, - const Slant slant) - : m_value(int(weight) | - (int(width) << 16) | - (int(slant) << 24)) { } - - constexpr FontStyle() : FontStyle(Weight::Normal, - Width::Normal, - Slant::Upright) { } - - bool operator==(const FontStyle& other) const { - return m_value == other.m_value; - } - - Weight weight() const { return Weight(m_value & 0xFFFF); } - Width width() const { return Width((m_value >> 16) & 0xFF); } - Slant slant() const { return Slant((m_value >> 24) & 0xFF); } - - static constexpr FontStyle Normal() { - return FontStyle(Weight::Normal, Width::Normal, Slant::Upright); - } - - static constexpr FontStyle Bold() { - return FontStyle(Weight::Bold, Width::Normal, Slant::Upright); - } - - static constexpr FontStyle Italic() { - return FontStyle(Weight::Normal, Width::Normal, Slant::Italic); - } - - static constexpr FontStyle BoldItalic() { - return FontStyle(Weight::Bold, Width::Normal, Slant::Italic); - } - - private: - uint32_t m_value; +class FontStyle { +public: + enum class Weight { + Invisible = 0, + Thin = 100, + ExtraLight = 200, + Light = 300, + Normal = 400, + Medium = 500, + SemiBold = 600, + Bold = 700, + ExtraBold = 800, + Black = 900, + ExtraBlack = 1000, }; + enum class Width { + UltraCondensed = 1, + ExtraCondensed = 2, + Condensed = 3, + SemiCondensed = 4, + Normal = 5, + SemiExpanded = 6, + Expanded = 7, + ExtraExpanded = 8, + UltraExpanded = 9, + }; + + enum class Slant { + Upright, + Italic, + Oblique, + }; + + constexpr FontStyle(const Weight weight, const Width width, const Slant slant) + : m_value(int(weight) | (int(width) << 16) | (int(slant) << 24)) + { + } + + constexpr FontStyle() : FontStyle(Weight::Normal, Width::Normal, Slant::Upright) {} + + bool operator==(const FontStyle& other) const { return m_value == other.m_value; } + + Weight weight() const { return Weight(m_value & 0xFFFF); } + Width width() const { return Width((m_value >> 16) & 0xFF); } + Slant slant() const { return Slant((m_value >> 24) & 0xFF); } + + static constexpr FontStyle Normal() + { + return FontStyle(Weight::Normal, Width::Normal, Slant::Upright); + } + + static constexpr FontStyle Bold() + { + return FontStyle(Weight::Bold, Width::Normal, Slant::Upright); + } + + static constexpr FontStyle Italic() + { + return FontStyle(Weight::Normal, Width::Normal, Slant::Italic); + } + + static constexpr FontStyle BoldItalic() + { + return FontStyle(Weight::Bold, Width::Normal, Slant::Italic); + } + +private: + uint32_t m_value; +}; + } // namespace os #endif diff --git a/os/font_style_set.h b/os/font_style_set.h index 1f78fc68f..34e47b5e4 100644 --- a/os/font_style_set.h +++ b/os/font_style_set.h @@ -13,19 +13,18 @@ namespace os { - class FontStyle; - - class FontStyleSet : public RefCount { - protected: - virtual ~FontStyleSet() { } - public: - virtual int count() = 0; - virtual void getStyle(int index, - FontStyle& style, - std::string& name) = 0; - virtual Ref typeface(int index) = 0; - virtual Ref matchStyle(const FontStyle& style) = 0; - }; +class FontStyle; + +class FontStyleSet : public RefCount { +protected: + virtual ~FontStyleSet() {} + +public: + virtual int count() = 0; + virtual void getStyle(int index, FontStyle& style, std::string& name) = 0; + virtual Ref typeface(int index) = 0; + virtual Ref matchStyle(const FontStyle& style) = 0; +}; } // namespace os diff --git a/os/gl/gl_context.h b/os/gl/gl_context.h index 3381982de..fb0247a31 100644 --- a/os/gl/gl_context.h +++ b/os/gl/gl_context.h @@ -13,12 +13,12 @@ namespace os { class GLContext { public: - virtual ~GLContext() { } + virtual ~GLContext() {} virtual bool isValid() { return false; } virtual bool createGLContext() { return false; } - virtual void destroyGLContext() { } - virtual void makeCurrent() { } - virtual void swapBuffers() { } + virtual void destroyGLContext() {} + virtual void makeCurrent() {} + virtual void swapBuffers() {} }; } // namespace os diff --git a/os/gl/gl_context_glx.h b/os/gl/gl_context_glx.h index 8b941100b..4afc69ec2 100644 --- a/os/gl/gl_context_glx.h +++ b/os/gl/gl_context_glx.h @@ -18,20 +18,14 @@ namespace os { class GLContextGLX : public GLContext { public: - GLContextGLX(::Display* display, ::Window window) - : m_display(display) - , m_window(window) { - } + GLContextGLX(::Display* display, ::Window window) : m_display(display), m_window(window) {} - ~GLContextGLX() { - destroyGLContext(); - } + ~GLContextGLX() { destroyGLContext(); } - bool isValid() override { - return m_glCtx != nullptr; - } + bool isValid() override { return m_glCtx != nullptr; } - bool createGLContext() override { + bool createGLContext() override + { GLint attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, 0 }; XVisualInfo* vi = glXChooseVisual(m_display, 0, attr); if (!vi) @@ -49,28 +43,31 @@ class GLContextGLX : public GLContext { ::Window root; int x, y, w, h; unsigned int border_width, depth; - XGetGeometry(m_display, m_window, &root, - &x, &y, (unsigned int*)&w, (unsigned int*)&h, - &border_width, &depth); + XGetGeometry(m_display, + m_window, + &root, + &x, + &y, + (unsigned int*)&w, + (unsigned int*)&h, + &border_width, + &depth); glViewport(0, 0, w, h); return true; } - void destroyGLContext() override { + void destroyGLContext() override + { if (m_glCtx) { glXDestroyContext(m_display, m_glCtx); m_glCtx = nullptr; } } - void makeCurrent() override { - glXMakeCurrent(m_display, m_window, m_glCtx); - } + void makeCurrent() override { glXMakeCurrent(m_display, m_window, m_glCtx); } - void swapBuffers() override { - glXSwapBuffers(m_display, m_window); - } + void swapBuffers() override { glXSwapBuffers(m_display, m_window); } private: ::Display* m_display = nullptr; diff --git a/os/gl/gl_context_nsgl.h b/os/gl/gl_context_nsgl.h index 30a4a74df..6f5bc310e 100644 --- a/os/gl/gl_context_nsgl.h +++ b/os/gl/gl_context_nsgl.h @@ -25,9 +25,7 @@ class GLContextNSGL : public GLContext { void makeCurrent() override; void swapBuffers() override; - id nsglContext() { - return m_nsgl; - } + id nsglContext() { return m_nsgl; } private: id m_nsgl = nullptr; // NSOpenGLContext diff --git a/os/gl/gl_context_nsgl.mm b/os/gl/gl_context_nsgl.mm index 9e53100c7..84565d4ce 100644 --- a/os/gl/gl_context_nsgl.mm +++ b/os/gl/gl_context_nsgl.mm @@ -5,15 +5,15 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/gl/gl_context_nsgl.h" #include -#include #include +#include namespace os { @@ -66,12 +66,11 @@ if (!nsPixelFormat) return false; - m_nsgl = [[NSOpenGLContext alloc] initWithFormat:nsPixelFormat - shareContext:nil]; + m_nsgl = [[NSOpenGLContext alloc] initWithFormat:nsPixelFormat shareContext:nil]; if (!m_nsgl) return false; - GLint swapInterval = 0; // disable vsync + GLint swapInterval = 0; // disable vsync [m_nsgl setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; if (m_view) diff --git a/os/gl/gl_context_wgl.h b/os/gl/gl_context_wgl.h index f244de050..2d72ac3be 100644 --- a/os/gl/gl_context_wgl.h +++ b/os/gl/gl_context_wgl.h @@ -17,43 +17,47 @@ namespace os { class GLContextWGL : public GLContext { public: - GLContextWGL(HWND hwnd) - : m_hwnd(hwnd) - , m_glrc(nullptr) { - } + GLContextWGL(HWND hwnd) : m_hwnd(hwnd), m_glrc(nullptr) {} - ~GLContextWGL() { - destroyGLContext(); - } + ~GLContextWGL() { destroyGLContext(); } - bool isValid() override { - return m_glrc != nullptr; - } + bool isValid() override { return m_glrc != nullptr; } - bool createGLContext() override { + bool createGLContext() override + { HDC olddc = wglGetCurrentDC(); HGLRC oldglrc = wglGetCurrentContext(); HDC hdc = GetDC(m_hwnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), - 1, // version number - PFD_DRAW_TO_WINDOW | // support window - PFD_SUPPORT_OPENGL | // support OpenGL - PFD_DOUBLEBUFFER, // double buffered - PFD_TYPE_RGBA, // RGBA type - 24, // 24-bit color depth - 0, 0, 0, 0, 0, 0, // color bits ignored - 8, // 8-bit alpha buffer - 0, // shift bit ignored - 0, // no accumulation buffer - 0, 0, 0, 0, // accum bits ignored - 0, // no z-buffer - 0, // no stencil buffer - 0, // no auxiliary buffer - PFD_MAIN_PLANE, // main layer - 0, // reserved - 0, 0, 0 // layer masks ignored + 1, // version number + PFD_DRAW_TO_WINDOW | // support window + PFD_SUPPORT_OPENGL | // support OpenGL + PFD_DOUBLEBUFFER, // double buffered + PFD_TYPE_RGBA, // RGBA type + 24, // 24-bit color depth + 0, + 0, + 0, + 0, + 0, + 0, // color bits ignored + 8, // 8-bit alpha buffer + 0, // shift bit ignored + 0, // no accumulation buffer + 0, + 0, + 0, + 0, // accum bits ignored + 0, // no z-buffer + 0, // no stencil buffer + 0, // no auxiliary buffer + PFD_MAIN_PLANE, // main layer + 0, // reserved + 0, + 0, + 0 // layer masks ignored }; int pixelFormat = ChoosePixelFormat(hdc, &pfd); SetPixelFormat(hdc, pixelFormat, &pfd); @@ -68,7 +72,8 @@ class GLContextWGL : public GLContext { return true; } - void destroyGLContext() override { + void destroyGLContext() override + { if (m_glrc) { wglMakeCurrent(nullptr, nullptr); wglDeleteContext(m_glrc); @@ -76,13 +81,15 @@ class GLContextWGL : public GLContext { } } - void makeCurrent() override { + void makeCurrent() override + { HDC hdc = GetDC(m_hwnd); wglMakeCurrent(hdc, m_glrc); ReleaseDC(m_hwnd, hdc); } - void swapBuffers() override { + void swapBuffers() override + { HDC hdc = GetDC(m_hwnd); SwapBuffers(hdc); ReleaseDC(m_hwnd, hdc); diff --git a/os/keys.h b/os/keys.h index 715d251aa..d836df49c 100644 --- a/os/keys.h +++ b/os/keys.h @@ -10,155 +10,155 @@ namespace os { - enum KeyModifiers { - kKeyNoneModifier = 0, - kKeyShiftModifier = 1, - kKeyCtrlModifier = 2, - kKeyAltModifier = 4, - kKeyCmdModifier = 8, - kKeySpaceModifier = 16, - kKeyWinModifier = 32, - kKeyUninitializedModifier = 64, - }; +enum KeyModifiers { + kKeyNoneModifier = 0, + kKeyShiftModifier = 1, + kKeyCtrlModifier = 2, + kKeyAltModifier = 4, + kKeyCmdModifier = 8, + kKeySpaceModifier = 16, + kKeyWinModifier = 32, + kKeyUninitializedModifier = 64, +}; - // TODO These are virtual key code (not scancodes), we should rename - // it to KeyCodes or use Unicode directly as on macOS (some - // special keys like F1, arrow keys, etc. have a special - // unicode value). - enum KeyScancode { - kKeyNil = 0, - kKeyA = 1, - kKeyB = 2, - kKeyC = 3, - kKeyD = 4, - kKeyE = 5, - kKeyF = 6, - kKeyG = 7, - kKeyH = 8, - kKeyI = 9, - kKeyJ = 10, - kKeyK = 11, - kKeyL = 12, - kKeyM = 13, - kKeyN = 14, - kKeyO = 15, - kKeyP = 16, - kKeyQ = 17, - kKeyR = 18, - kKeyS = 19, - kKeyT = 20, - kKeyU = 21, - kKeyV = 22, - kKeyW = 23, - kKeyX = 24, - kKeyY = 25, - kKeyZ = 26, - kKey0 = 27, - kKey1 = 28, - kKey2 = 29, - kKey3 = 30, - kKey4 = 31, - kKey5 = 32, - kKey6 = 33, - kKey7 = 34, - kKey8 = 35, - kKey9 = 36, - kKey0Pad = 37, - kKey1Pad = 38, - kKey2Pad = 39, - kKey3Pad = 40, - kKey4Pad = 41, - kKey5Pad = 42, - kKey6Pad = 43, - kKey7Pad = 44, - kKey8Pad = 45, - kKey9Pad = 46, - kKeyF1 = 47, - kKeyF2 = 48, - kKeyF3 = 49, - kKeyF4 = 50, - kKeyF5 = 51, - kKeyF6 = 52, - kKeyF7 = 53, - kKeyF8 = 54, - kKeyF9 = 55, - kKeyF10 = 56, - kKeyF11 = 57, - kKeyF12 = 58, - kKeyEsc = 59, - kKeyTilde = 60, - kKeyMinus = 61, - kKeyEquals = 62, - kKeyBackspace = 63, - kKeyTab = 64, - kKeyOpenbrace = 65, - kKeyClosebrace = 66, - kKeyEnter = 67, - kKeyColon = 68, - kKeyQuote = 69, - kKeyBackslash = 70, - kKeyBackslash2 = 71, - kKeyComma = 72, - kKeyStop = 73, - kKeySlash = 74, - kKeySpace = 75, - kKeyInsert = 76, - kKeyDel = 77, - kKeyHome = 78, - kKeyEnd = 79, - kKeyPageUp = 80, - kKeyPageDown = 81, - kKeyLeft = 82, - kKeyRight = 83, - kKeyUp = 84, - kKeyDown = 85, - kKeySlashPad = 86, - kKeyAsterisk = 87, - kKeyMinusPad = 88, - kKeyPlusPad = 89, - kKeyDelPad = 90, - kKeyEnterPad = 91, - kKeyPrtscr = 92, - kKeyPause = 93, - kKeyAbntC1 = 94, - kKeyYen = 95, - kKeyKana = 96, - kKeyConvert = 97, - kKeyNoconvert = 98, - kKeyAt = 99, - kKeyCircumflex = 100, - kKeyColon2 = 101, - kKeyKanji = 102, - kKeyEqualsPad = 103, // macOS - kKeyBackquote = 104, // macOS - kKeySemicolon = 105, // macOS - kKeyUnknown1 = 106, - kKeyUnknown2 = 107, - kKeyUnknown3 = 108, - kKeyUnknown4 = 109, - kKeyUnknown5 = 110, - kKeyUnknown6 = 111, - kKeyUnknown7 = 112, - kKeyUnknown8 = 113, +// TODO These are virtual key code (not scancodes), we should rename +// it to KeyCodes or use Unicode directly as on macOS (some +// special keys like F1, arrow keys, etc. have a special +// unicode value). +enum KeyScancode { + kKeyNil = 0, + kKeyA = 1, + kKeyB = 2, + kKeyC = 3, + kKeyD = 4, + kKeyE = 5, + kKeyF = 6, + kKeyG = 7, + kKeyH = 8, + kKeyI = 9, + kKeyJ = 10, + kKeyK = 11, + kKeyL = 12, + kKeyM = 13, + kKeyN = 14, + kKeyO = 15, + kKeyP = 16, + kKeyQ = 17, + kKeyR = 18, + kKeyS = 19, + kKeyT = 20, + kKeyU = 21, + kKeyV = 22, + kKeyW = 23, + kKeyX = 24, + kKeyY = 25, + kKeyZ = 26, + kKey0 = 27, + kKey1 = 28, + kKey2 = 29, + kKey3 = 30, + kKey4 = 31, + kKey5 = 32, + kKey6 = 33, + kKey7 = 34, + kKey8 = 35, + kKey9 = 36, + kKey0Pad = 37, + kKey1Pad = 38, + kKey2Pad = 39, + kKey3Pad = 40, + kKey4Pad = 41, + kKey5Pad = 42, + kKey6Pad = 43, + kKey7Pad = 44, + kKey8Pad = 45, + kKey9Pad = 46, + kKeyF1 = 47, + kKeyF2 = 48, + kKeyF3 = 49, + kKeyF4 = 50, + kKeyF5 = 51, + kKeyF6 = 52, + kKeyF7 = 53, + kKeyF8 = 54, + kKeyF9 = 55, + kKeyF10 = 56, + kKeyF11 = 57, + kKeyF12 = 58, + kKeyEsc = 59, + kKeyTilde = 60, + kKeyMinus = 61, + kKeyEquals = 62, + kKeyBackspace = 63, + kKeyTab = 64, + kKeyOpenbrace = 65, + kKeyClosebrace = 66, + kKeyEnter = 67, + kKeyColon = 68, + kKeyQuote = 69, + kKeyBackslash = 70, + kKeyBackslash2 = 71, + kKeyComma = 72, + kKeyStop = 73, + kKeySlash = 74, + kKeySpace = 75, + kKeyInsert = 76, + kKeyDel = 77, + kKeyHome = 78, + kKeyEnd = 79, + kKeyPageUp = 80, + kKeyPageDown = 81, + kKeyLeft = 82, + kKeyRight = 83, + kKeyUp = 84, + kKeyDown = 85, + kKeySlashPad = 86, + kKeyAsterisk = 87, + kKeyMinusPad = 88, + kKeyPlusPad = 89, + kKeyDelPad = 90, + kKeyEnterPad = 91, + kKeyPrtscr = 92, + kKeyPause = 93, + kKeyAbntC1 = 94, + kKeyYen = 95, + kKeyKana = 96, + kKeyConvert = 97, + kKeyNoconvert = 98, + kKeyAt = 99, + kKeyCircumflex = 100, + kKeyColon2 = 101, + kKeyKanji = 102, + kKeyEqualsPad = 103, // macOS + kKeyBackquote = 104, // macOS + kKeySemicolon = 105, // macOS + kKeyUnknown1 = 106, + kKeyUnknown2 = 107, + kKeyUnknown3 = 108, + kKeyUnknown4 = 109, + kKeyUnknown5 = 110, + kKeyUnknown6 = 111, + kKeyUnknown7 = 112, + kKeyUnknown8 = 113, - kKeyFirstModifierScancode = 114, + kKeyFirstModifierScancode = 114, - kKeyLShift = 114, - kKeyRShift = 115, - kKeyLControl = 116, - kKeyRControl = 117, - kKeyAlt = 118, - kKeyAltGr = 119, - kKeyLWin = 120, - kKeyRWin = 121, - kKeyMenu = 122, - kKeyCommand = 123, - kKeyScrLock = 124, - kKeyNumLock = 125, - kKeyCapsLock = 126, + kKeyLShift = 114, + kKeyRShift = 115, + kKeyLControl = 116, + kKeyRControl = 117, + kKeyAlt = 118, + kKeyAltGr = 119, + kKeyLWin = 120, + kKeyRWin = 121, + kKeyMenu = 122, + kKeyCommand = 123, + kKeyScrLock = 124, + kKeyNumLock = 125, + kKeyCapsLock = 126, - kKeyScancodes = 127 - }; + kKeyScancodes = 127 +}; } // namespace os diff --git a/os/logger.h b/os/logger.h index f040bc64e..5f25df96c 100644 --- a/os/logger.h +++ b/os/logger.h @@ -10,11 +10,11 @@ namespace os { - class Logger { - public: - virtual ~Logger() { } - virtual void logError(const char* error) = 0; - }; +class Logger { +public: + virtual ~Logger() {} + virtual void logError(const char* error) = 0; +}; } // namespace os diff --git a/os/menus.h b/os/menus.h index 386f602fc..dd25b9588 100644 --- a/os/menus.h +++ b/os/menus.h @@ -17,94 +17,91 @@ #include namespace os { - class MenuItem; - - struct MenuItemInfo { - enum Type { - Normal, - Separator - }; - - enum Action { - UserDefined, - - // macOS standard commands - Hide, - HideOthers, - ShowAll, - Quit, - Minimize, - Zoom, - }; - - Type type; - Action action; - std::string text; - Shortcut shortcut; - std::function execute; - std::function validate; - - explicit MenuItemInfo(const Type type = Normal, - const Action action = UserDefined) - : type(type) - , action(action) { - } - - explicit MenuItemInfo(const std::string& text, - const Action action = UserDefined) - : type(Normal) - , action(action) - , text(text) { - } - }; +class MenuItem; - class Menu; - class MenuItem; - class Menus; - - using MenuItemRef = Ref; - using MenuRef = Ref; - using MenusRef = Ref; - - class MenuItem : public RefCount { - public: - virtual ~MenuItem() { } - virtual void setText(const std::string& text) = 0; - virtual void setSubmenu(const MenuRef& submenu) = 0; - virtual void setEnabled(bool state) = 0; - virtual void setChecked(bool state) = 0; - virtual void setShortcut(const Shortcut& shortcut) = 0; - - // Indicates that this is the "Edit" menu with the - // Cut/Copy/Paste/etc. commands. Used by the laf implementation on - // macOS to switch the "Edit" menu completely with a standard - // implementation when necessary. - // - // If you are going to use a native file dialog (os::FileDialog), - // you will need to specify a standard "Edit" menu to make the - // Undo/Redo/Cut/Copy/Paste/etc. keyboard shortcuts work. - // - // The specific details are not beautiful or important, but you - // can search for "OSXEditMenuHack" to know why this is needed. - virtual void setAsStandardEditMenuItem() = 0; - }; +struct MenuItemInfo { + enum Type { Normal, Separator }; - class Menu : public RefCount { - public: - virtual ~Menu() { } - virtual void addItem(const MenuItemRef& item) = 0; - virtual void insertItem(const int index, const MenuItemRef& item) = 0; - virtual void removeItem(const MenuItemRef& item) = 0; - }; + enum Action { + UserDefined, - class Menus : public RefCount { - public: - virtual ~Menus() { } - virtual MenuRef makeMenu() = 0; - virtual MenuItemRef makeMenuItem(const MenuItemInfo& info) = 0; - virtual void setAppMenu(const MenuRef& menu) = 0; + // macOS standard commands + Hide, + HideOthers, + ShowAll, + Quit, + Minimize, + Zoom, }; + Type type; + Action action; + std::string text; + Shortcut shortcut; + std::function execute; + std::function validate; + + explicit MenuItemInfo(const Type type = Normal, const Action action = UserDefined) + : type(type) + , action(action) + { + } + + explicit MenuItemInfo(const std::string& text, const Action action = UserDefined) + : type(Normal) + , action(action) + , text(text) + { + } +}; + +class Menu; +class MenuItem; +class Menus; + +using MenuItemRef = Ref; +using MenuRef = Ref; +using MenusRef = Ref; + +class MenuItem : public RefCount { +public: + virtual ~MenuItem() {} + virtual void setText(const std::string& text) = 0; + virtual void setSubmenu(const MenuRef& submenu) = 0; + virtual void setEnabled(bool state) = 0; + virtual void setChecked(bool state) = 0; + virtual void setShortcut(const Shortcut& shortcut) = 0; + + // Indicates that this is the "Edit" menu with the + // Cut/Copy/Paste/etc. commands. Used by the laf implementation on + // macOS to switch the "Edit" menu completely with a standard + // implementation when necessary. + // + // If you are going to use a native file dialog (os::FileDialog), + // you will need to specify a standard "Edit" menu to make the + // Undo/Redo/Cut/Copy/Paste/etc. keyboard shortcuts work. + // + // The specific details are not beautiful or important, but you + // can search for "OSXEditMenuHack" to know why this is needed. + virtual void setAsStandardEditMenuItem() = 0; +}; + +class Menu : public RefCount { +public: + virtual ~Menu() {} + virtual void addItem(const MenuItemRef& item) = 0; + virtual void insertItem(const int index, const MenuItemRef& item) = 0; + virtual void removeItem(const MenuItemRef& item) = 0; +}; + +class Menus : public RefCount { +public: + virtual ~Menus() {} + virtual MenuRef makeMenu() = 0; + virtual MenuItemRef makeMenuItem(const MenuItemInfo& info) = 0; + virtual void setAppMenu(const MenuRef& menu) = 0; +}; + } // namespace os #endif diff --git a/os/native_cursor.h b/os/native_cursor.h index c1adfab95..d8ba8dc2b 100644 --- a/os/native_cursor.h +++ b/os/native_cursor.h @@ -13,29 +13,29 @@ namespace os { - enum class NativeCursor { - Hidden, - Arrow, - Crosshair, - IBeam, - Wait, - Link, - Help, - Forbidden, - Move, - SizeNS, - SizeWE, - SizeN, - SizeNE, - SizeE, - SizeSE, - SizeS, - SizeSW, - SizeW, - SizeNW, +enum class NativeCursor { + Hidden, + Arrow, + Crosshair, + IBeam, + Wait, + Link, + Help, + Forbidden, + Move, + SizeNS, + SizeWE, + SizeN, + SizeNE, + SizeE, + SizeSE, + SizeS, + SizeSW, + SizeW, + SizeNW, - Cursors [[maybe_unused]] - }; + Cursors [[maybe_unused]] +}; } // namespace os diff --git a/os/native_dialogs.h b/os/native_dialogs.h index 8f6d41937..f4a853ff4 100644 --- a/os/native_dialogs.h +++ b/os/native_dialogs.h @@ -15,43 +15,43 @@ #include namespace os { - class Window; - class FileDialog; - class NativeDialogs; - using FileDialogRef = Ref; - - class FileDialog : public RefCount { - public: - enum class Type { - OpenFile, - OpenFiles, - OpenFolder, - SaveFile, - }; - - enum class Result { - Error = -1, // This happens when we cannot open the native dialog - Cancel = 0, // The user canceled the dialog - OK = 1, // The user selected some file(s) - }; - - virtual ~FileDialog() { } - virtual void setType(const Type type) = 0; - virtual void setTitle(const std::string& title) = 0; - virtual void setDefaultExtension(const std::string& extension) = 0; - virtual void addFilter(const std::string& extension, const std::string& description) = 0; - virtual std::string fileName() = 0; - virtual void getMultipleFileNames(base::paths& output) = 0; - virtual void setFileName(const std::string& filename) = 0; - virtual Result show(Window* parent) = 0; +class Window; +class FileDialog; +class NativeDialogs; +using FileDialogRef = Ref; + +class FileDialog : public RefCount { +public: + enum class Type { + OpenFile, + OpenFiles, + OpenFolder, + SaveFile, }; - class NativeDialogs : public RefCount { - public: - virtual ~NativeDialogs() { } - virtual FileDialogRef makeFileDialog() = 0; + enum class Result { + Error = -1, // This happens when we cannot open the native dialog + Cancel = 0, // The user canceled the dialog + OK = 1, // The user selected some file(s) }; + virtual ~FileDialog() {} + virtual void setType(const Type type) = 0; + virtual void setTitle(const std::string& title) = 0; + virtual void setDefaultExtension(const std::string& extension) = 0; + virtual void addFilter(const std::string& extension, const std::string& description) = 0; + virtual std::string fileName() = 0; + virtual void getMultipleFileNames(base::paths& output) = 0; + virtual void setFileName(const std::string& filename) = 0; + virtual Result show(Window* parent) = 0; +}; + +class NativeDialogs : public RefCount { +public: + virtual ~NativeDialogs() {} + virtual FileDialogRef makeFileDialog() = 0; +}; + } // namespace os #endif diff --git a/os/none/os.cpp b/os/none/os.cpp index b68013dc3..361bf284e 100644 --- a/os/none/os.cpp +++ b/os/none/os.cpp @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "base/memory.h" @@ -22,57 +22,69 @@ class NoneSystem : public System { public: const std::string& appName() const override { return m_appName; } void setAppName(const std::string& appName) override { m_appName = appName; } - void setAppMode(AppMode appMode) override { } + void setAppMode(AppMode appMode) override {} - void markCliFileAsProcessed(const std::string& fn) override { } - void finishLaunching() override { } - void activateApp() override { } + void markCliFileAsProcessed(const std::string& fn) override {} + void finishLaunching() override {} + void activateApp() override {} Capabilities capabilities() const override { return (Capabilities)0; } - void setTabletOptions(const TabletOptions&) override { } + void setTabletOptions(const TabletOptions&) override {} TabletOptions tabletOptions() const override { return TabletOptions(); } Logger* logger() override { return nullptr; } Menus* menus() override { return nullptr; } NativeDialogs* nativeDialogs() override { return nullptr; } EventQueue* eventQueue() override { return nullptr; } ScreenRef mainScreen() override { return nullptr; } - void listScreens(ScreenList& screens) override { } + void listScreens(ScreenList& screens) override {} Window* defaultWindow() override { return nullptr; } Ref makeWindow(const WindowSpec& spec) override { return nullptr; } - Ref makeSurface(int width, int height, - const os::ColorSpaceRef& colorSpace) override { return nullptr; } + Ref makeSurface(int width, int height, const os::ColorSpaceRef& colorSpace) override + { + return nullptr; + } #if CLIP_ENABLE_IMAGE Ref makeSurface(const clip::image& image) override { return nullptr; } #endif - Ref makeRgbaSurface(int width, int height, - const os::ColorSpaceRef& colorSpace) override { return nullptr; } + Ref makeRgbaSurface(int width, int height, const os::ColorSpaceRef& colorSpace) override + { + return nullptr; + } Ref loadSurface(const char* filename) override { return nullptr; } Ref loadRgbaSurface(const char* filename) override { return nullptr; } - Ref makeCursor(const Surface* surface, - const gfx::Point& focus, - const int scale) override { return nullptr; } + Ref makeCursor(const Surface* surface, const gfx::Point& focus, const int scale) override + { + return nullptr; + } FontManager* fontManager() override { return nullptr; } Ref loadSpriteSheetFont(const char* filename, int scale) override { return nullptr; } Ref loadTrueTypeFont(const char* filename, int height) override { return nullptr; } bool isKeyPressed(KeyScancode scancode) override { return false; } KeyModifiers keyModifiers() override { return kKeyNoneModifier; } int getUnicodeFromScancode(KeyScancode scancode) override { return 0; } - void setTranslateDeadKeys(bool state) override { } + void setTranslateDeadKeys(bool state) override {} gfx::Point mousePosition() const override { return gfx::Point(0, 0); } - void setMousePosition(const gfx::Point& screenPosition) override { } - gfx::Color getColorFromScreen(const gfx::Point& screenPosition) const override { return gfx::ColorNone; } - void listColorSpaces(std::vector& list) override { } + void setMousePosition(const gfx::Point& screenPosition) override {} + gfx::Color getColorFromScreen(const gfx::Point& screenPosition) const override + { + return gfx::ColorNone; + } + void listColorSpaces(std::vector& list) override {} os::ColorSpaceRef makeColorSpace(const gfx::ColorSpaceRef& cs) override { return nullptr; } - Ref convertBetweenColorSpace( - const os::ColorSpaceRef& src, const os::ColorSpaceRef& dst) override { return nullptr; } - void setWindowsColorSpace(const os::ColorSpaceRef& cs) override { } + Ref convertBetweenColorSpace(const os::ColorSpaceRef& src, + const os::ColorSpaceRef& dst) override + { + return nullptr; + } + void setWindowsColorSpace(const os::ColorSpaceRef& cs) override {} os::ColorSpaceRef windowsColorSpace() override { return nullptr; } private: std::string m_appName; }; -System* make_system_impl() { +System* make_system_impl() +{ return new NoneSystem; } diff --git a/os/none/paint.h b/os/none/paint.h index 4f612193c..200daf649 100644 --- a/os/none/paint.h +++ b/os/none/paint.h @@ -12,33 +12,33 @@ namespace os { - // Dummy Paint implementation for non-GUI apps/laf (when LAF_SKIA is - // false) - class Paint : public PaintBase { - public: - bool antialias() const { return m_antialias; } - void antialias(const bool state) { m_antialias = state; } - - Style style() const { return m_style; } - void style(const Style style) { m_style = style; } - - gfx::Color color() const { return m_color; } - void color(const gfx::Color color) { m_color = color; } - - float strokeWidth() const { return m_strokeWidth; } - void strokeWidth(const float strokeWidth) { m_strokeWidth = strokeWidth; } - - BlendMode blendMode() const { return m_blendMode; } - void blendMode(const BlendMode blendMode) { m_blendMode = blendMode; } - - private: - bool m_antialias = false; - Style m_style = Fill; - // Opaque black must be the default (to match SkPaint default) - gfx::Color m_color = gfx::rgba(0, 0, 0, 255); - float m_strokeWidth = 1.0f; - BlendMode m_blendMode = BlendMode::SrcOver; - }; +// Dummy Paint implementation for non-GUI apps/laf (when LAF_SKIA is +// false) +class Paint : public PaintBase { +public: + bool antialias() const { return m_antialias; } + void antialias(const bool state) { m_antialias = state; } + + Style style() const { return m_style; } + void style(const Style style) { m_style = style; } + + gfx::Color color() const { return m_color; } + void color(const gfx::Color color) { m_color = color; } + + float strokeWidth() const { return m_strokeWidth; } + void strokeWidth(const float strokeWidth) { m_strokeWidth = strokeWidth; } + + BlendMode blendMode() const { return m_blendMode; } + void blendMode(const BlendMode blendMode) { m_blendMode = blendMode; } + +private: + bool m_antialias = false; + Style m_style = Fill; + // Opaque black must be the default (to match SkPaint default) + gfx::Color m_color = gfx::rgba(0, 0, 0, 255); + float m_strokeWidth = 1.0f; + BlendMode m_blendMode = BlendMode::SrcOver; +}; } // namespace os diff --git a/os/osx/app.h b/os/osx/app.h index 12353b640..bd8e2b5b9 100644 --- a/os/osx/app.h +++ b/os/osx/app.h @@ -15,26 +15,26 @@ namespace os { - class AppOSX { - public: - static AppOSX* instance(); +class AppOSX { +public: + static AppOSX* instance(); - AppOSX(); - ~AppOSX(); + AppOSX(); + ~AppOSX(); - bool init(); - void setAppMode(AppMode appMode); + bool init(); + void setAppMode(AppMode appMode); - bool isHidden() const; + bool isHidden() const; - void markCliFileAsProcessed(const std::string& fn); - void finishLaunching(); - void activateApp(); + void markCliFileAsProcessed(const std::string& fn); + void finishLaunching(); + void activateApp(); - private: - class Impl; - Impl* m_impl; - }; +private: + class Impl; + Impl* m_impl; +}; } // namespace os diff --git a/os/osx/app.mm b/os/osx/app.mm index a1700bf79..99bca30a3 100644 --- a/os/osx/app.mm +++ b/os/osx/app.mm @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -21,7 +21,8 @@ class AppOSX::Impl { public: - bool init() { + bool init() + { m_app = [NSApplicationOSX sharedApplication]; m_appDelegate = [AppDelegateOSX new]; @@ -37,29 +38,25 @@ bool init() { return true; } - void setAppMode(AppMode appMode) { + void setAppMode(AppMode appMode) + { switch (appMode) { case AppMode::CLI: [m_app setActivationPolicy:NSApplicationActivationPolicyProhibited]; break; case AppMode::GUI: [m_app setActivationPolicy:NSApplicationActivationPolicyRegular]; break; } } - bool isHidden() const { - return [m_appDelegate isHidden]; - } + bool isHidden() const { return [m_appDelegate isHidden]; } - void markCliFileAsProcessed(const std::string& fn) { - [m_appDelegate markCliFileAsProcessed:fn]; - } + void markCliFileAsProcessed(const std::string& fn) { [m_appDelegate markCliFileAsProcessed:fn]; } - void finishLaunching() { + void finishLaunching() + { [m_app finishLaunching]; [m_appDelegate resetCliFiles]; } - void activateApp() { - [m_app activateIgnoringOtherApps:YES]; - } + void activateApp() { [m_app activateIgnoringOtherApps:YES]; } private: NSApplication* m_app; @@ -74,8 +71,7 @@ void activateApp() { return g_instance; } -AppOSX::AppOSX() - : m_impl(new Impl) +AppOSX::AppOSX() : m_impl(new Impl) { ASSERT(!g_instance); g_instance = this; diff --git a/os/osx/app_delegate.h b/os/osx/app_delegate.h index 0bbaf04a9..32f67b175 100644 --- a/os/osx/app_delegate.h +++ b/os/osx/app_delegate.h @@ -15,10 +15,10 @@ #include @interface NSApplicationOSX : NSApplication -- (void)sendEvent:(NSEvent *)event; +- (void)sendEvent:(NSEvent*)event; @end -@interface AppDelegateOSX : NSObject { +@interface AppDelegateOSX : NSObject { // Files that were already processed in the CLI, so we don't need to // generate a DropFiles event. std::set m_cliFiles; diff --git a/os/osx/app_delegate.mm b/os/osx/app_delegate.mm index 61ac23601..d8e055927 100644 --- a/os/osx/app_delegate.mm +++ b/os/osx/app_delegate.mm @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include @@ -22,7 +22,7 @@ @implementation NSApplicationOSX -- (void)sendEvent:(NSEvent *)event +- (void)sendEvent:(NSEvent*)event { if ([event type] == NSKeyDown) { if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask) { @@ -47,7 +47,8 @@ - (void)sendEvent:(NSEvent *)event return; } } - else if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == (NSCommandKeyMask | NSShiftKeyMask)) { + else if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == + (NSCommandKeyMask | NSShiftKeyMask)) { if ([[event charactersIgnoringModifiers] isEqualToString:@"Z"]) { if ([self sendAction:@selector(redo:) to:nil from:self]) return; @@ -120,8 +121,8 @@ - (BOOL)application:(NSApplication*)app openFiles:(NSArray*)filenames // filter for files that were already processed in the CLI (m_cliFiles) base::paths files; - for (int i=0; i<[filenames count]; ++i) { - NSString* fnString = [filenames objectAtIndex: i]; + for (int i = 0; i < [filenames count]; ++i) { + NSString* fnString = [filenames objectAtIndex:i]; std::string fn = base::normalize_path([fnString UTF8String]); if (m_cliFiles.find(fn) == m_cliFiles.end()) files.push_back(fn); @@ -145,8 +146,7 @@ - (void)executeMenuItem:(id)sender - (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - if (menuItem && - [menuItem respondsToSelector:@selector(validateLafMenuItem)]) { + if (menuItem && [menuItem respondsToSelector:@selector(validateLafMenuItem)]) { [((id)menuItem) validateLafMenuItem]; return menuItem.enabled; } diff --git a/os/osx/color_space.h b/os/osx/color_space.h index 4343bc6d0..94856ec9d 100644 --- a/os/osx/color_space.h +++ b/os/osx/color_space.h @@ -11,7 +11,7 @@ #include "os/color_space.h" #ifdef __OBJC__ -#include + #include #endif #include diff --git a/os/osx/color_space.mm b/os/osx/color_space.mm index 95d2858eb..9bae9639c 100644 --- a/os/osx/color_space.mm +++ b/os/osx/color_space.mm @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/osx/color_space.h" @@ -21,12 +21,9 @@ if (cgCS) { CFDataRef icc = CGColorSpaceCopyICCProfile(cgCS); if (icc) { - auto gfxCS = gfx::ColorSpace::MakeICC(CFDataGetBytePtr(icc), - CFDataGetLength(icc)); + auto gfxCS = gfx::ColorSpace::MakeICC(CFDataGetBytePtr(icc), CFDataGetLength(icc)); - gfxCS->setName( - std::string("Display Profile: ") + - [[nsColorSpace localizedName] UTF8String]); + gfxCS->setName(std::string("Display Profile: ") + [[nsColorSpace localizedName] UTF8String]); osCS = os::instance()->makeColorSpace(gfxCS); CFRelease(icc); @@ -39,8 +36,7 @@ void list_display_colorspaces(std::vector& list) { // One color profile for each screen for (NSScreen* screen in [NSScreen screens]) { - os::ColorSpaceRef osCS = - convert_nscolorspace_to_os_colorspace([screen colorSpace]); + os::ColorSpaceRef osCS = convert_nscolorspace_to_os_colorspace([screen colorSpace]); if (osCS) list.push_back(osCS); } diff --git a/os/osx/dnd.h b/os/osx/dnd.h index 749e332b2..8b89d6047 100644 --- a/os/osx/dnd.h +++ b/os/osx/dnd.h @@ -10,33 +10,33 @@ #ifdef __OBJC__ -#include "base/paths.h" -#include "gfx/point.h" -#include "os/dnd.h" -#include "os/surface.h" + #include "base/paths.h" + #include "gfx/point.h" + #include "os/dnd.h" + #include "os/surface.h" -#include + #include namespace os { - class DragDataProviderOSX : public DragDataProvider { - public: - DragDataProviderOSX(NSPasteboard* pasteboard) : m_pasteboard(pasteboard) {} +class DragDataProviderOSX : public DragDataProvider { +public: + DragDataProviderOSX(NSPasteboard* pasteboard) : m_pasteboard(pasteboard) {} - private: - NSPasteboard* m_pasteboard; +private: + NSPasteboard* m_pasteboard; - base::paths getPaths() override; + base::paths getPaths() override; - SurfaceRef getImage() override; + SurfaceRef getImage() override; - std::string getUrl() override; + std::string getUrl() override; - bool contains(DragDataItemType type) override; - }; + bool contains(DragDataItemType type) override; +}; - NSDragOperation as_nsdragoperation(const os::DropOperation op); - os::DropOperation as_dropoperation(const NSDragOperation nsdop); - gfx::Point drag_position(id sender); +NSDragOperation as_nsdragoperation(const os::DropOperation op); +os::DropOperation as_dropoperation(const NSDragOperation nsdop); +gfx::Point drag_position(id sender); } // namespace os diff --git a/os/osx/dnd.mm b/os/osx/dnd.mm index f7e6b4a38..46c0a6b9b 100644 --- a/os/osx/dnd.mm +++ b/os/osx/dnd.mm @@ -4,11 +4,11 @@ // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. +#include "os/dnd.h" #include "base/exception.h" #include "base/fs.h" #include "clip/clip.h" #include "clip/clip_osx.h" -#include "os/dnd.h" #include "os/osx/dnd.h" #include "os/osx/window.h" #include "os/surface_format.h" @@ -26,8 +26,8 @@ if ([m_pasteboard.types containsObject:NSFilenamesPboardType]) { NSArray* filenames = [m_pasteboard propertyListForType:NSFilenamesPboardType]; - for (int i=0; i<[filenames count]; ++i) { - NSString* fn = [filenames objectAtIndex: i]; + for (int i = 0; i < [filenames count]; ++i) { + NSString* fn = [filenames objectAtIndex:i]; files.push_back(base::normalize_path([fn UTF8String])); } @@ -47,24 +47,21 @@ std::string DragDataProviderOSX::getUrl() { - NSURL* url = [NSURL URLFromPasteboard: m_pasteboard]; + NSURL* url = [NSURL URLFromPasteboard:m_pasteboard]; return url ? url.absoluteString.UTF8String : ""; } bool DragDataProviderOSX::contains(DragDataItemType type) { for (NSPasteboardType t in m_pasteboard.types) { - if (type == DragDataItemType::Paths && - [t isEqual: NSFilenamesPboardType]) + if (type == DragDataItemType::Paths && [t isEqual:NSFilenamesPboardType]) return true; if (type == DragDataItemType::Image && - ([t isEqual: NSPasteboardTypeTIFF] || - [t isEqual: NSPasteboardTypePNG])) + ([t isEqual:NSPasteboardTypeTIFF] || [t isEqual:NSPasteboardTypePNG])) return true; - if (type == DragDataItemType::Url && - [t isEqual: NSURLPboardType]) + if (type == DragDataItemType::Url && [t isEqual:NSURLPboardType]) return true; } return false; diff --git a/os/osx/event_queue.mm b/os/osx/event_queue.mm index 8e93925bf..80bdae15b 100644 --- a/os/osx/event_queue.mm +++ b/os/osx/event_queue.mm @@ -6,11 +6,11 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif -#include #include +#include #include "os/osx/event_queue.h" @@ -18,8 +18,7 @@ namespace os { -EventQueueOSX::EventQueueOSX() - : m_sleeping(false) +EventQueueOSX::EventQueueOSX() : m_sleeping(false) { } @@ -64,8 +63,7 @@ // combinations, and send them directly to the main // NSView. Without this, the NSApplication intercepts the key // combination and use it to go to the next key view. - if (event.type == NSEventTypeKeyDown && - app.keyWindow) { + if (event.type == NSEventTypeKeyDown && app.keyWindow) { [app.keyWindow.contentView keyDown:event]; } else { diff --git a/os/osx/generate_drop_files.h b/os/osx/generate_drop_files.h index 48e13e30b..b7a1e3e57 100644 --- a/os/osx/generate_drop_files.h +++ b/os/osx/generate_drop_files.h @@ -14,8 +14,8 @@ inline os::Event generate_drop_files_from_nsarray(NSArray* filenames) { base::paths files; - for (int i=0; i<[filenames count]; ++i) { - NSString* fn = [filenames objectAtIndex: i]; + for (int i = 0; i < [filenames count]; ++i) { + NSString* fn = [filenames objectAtIndex:i]; files.push_back(base::normalize_path([fn UTF8String])); } diff --git a/os/osx/keys.h b/os/osx/keys.h index ec7f35ea0..644e63f77 100644 --- a/os/osx/keys.h +++ b/os/osx/keys.h @@ -14,12 +14,12 @@ namespace os { - KeyScancode scancode_from_nsevent(NSEvent* event); +KeyScancode scancode_from_nsevent(NSEvent* event); - CFStringRef get_unicode_from_key_code(const UInt16 keyCode, - const NSEventModifierFlags modifierFlags, - UInt32* deadKeyState = nullptr); +CFStringRef get_unicode_from_key_code(const UInt16 keyCode, + const NSEventModifierFlags modifierFlags, + UInt32* deadKeyState = nullptr); -} +} // namespace os #endif diff --git a/os/osx/keys.mm b/os/osx/keys.mm index db9130e7e..97d0e55b0 100644 --- a/os/osx/keys.mm +++ b/os/osx/keys.mm @@ -8,13 +8,13 @@ #define KEY_TRACE(...) #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/osx/keys.h" -#include #include // TIS functions +#include namespace os { @@ -163,7 +163,7 @@ static KeyScancode from_keycode_to_scancode(UInt16 keyCode) { // Converts macOS virtual key code into a os::KeyScancode static KeyScancode map[256] = { - // 0x00 + // 0x00 kKeyA, // 0x00 - kVK_ANSI_A kKeyS, // 0x01 - kVK_ANSI_S kKeyD, // 0x02 - kVK_ANSI_D @@ -323,7 +323,7 @@ KeyScancode scancode_from_nsevent(NSEvent* event) // QWERTY Cmd" keyboard layout. NSString* chars = event.characters; if (chars.length > 0) { - int chr = [chars characterAtIndex:chars.length-1]; + int chr = [chars characterAtIndex:chars.length - 1]; // Avoid activating space bar modifier. E.g. pressing // Ctrl+Alt+Shift+S on "Spanish ISO" layout generates a @@ -332,8 +332,7 @@ KeyScancode scancode_from_nsevent(NSEvent* event) if (chr != 32) { code = from_char_to_scancode(chr); if (code != kKeyNil) { - KEY_TRACE("scancode_from_nsevent %d -> %d (characters)\n", - (int)chr, (int)code); + KEY_TRACE("scancode_from_nsevent %d -> %d (characters)\n", (int)chr, (int)code); return code; } } @@ -341,11 +340,12 @@ KeyScancode scancode_from_nsevent(NSEvent* event) chars = event.charactersIgnoringModifiers; if (chars.length > 0) { - int chr = [chars characterAtIndex:chars.length-1]; + int chr = [chars characterAtIndex:chars.length - 1]; code = from_char_to_scancode(chr); if (code != kKeyNil) { KEY_TRACE("scancode_from_nsevent %d -> %d (charactersIgnoringModifiers)\n", - (int)chr, (int)code); + (int)chr, + (int)code); return code; } } @@ -353,9 +353,8 @@ KeyScancode scancode_from_nsevent(NSEvent* event) #else // Don't use this code, it reports scancodes always as QWERTY // and doesn't work for Dvorak or AZERTY layouts. { - CFStringRef strRef = get_unicode_from_key_code( - event.keyCode, - event.modifierFlags & NSCommandKeyMask); + CFStringRef strRef = get_unicode_from_key_code(event.keyCode, + event.modifierFlags & NSCommandKeyMask); if (strRef) { KeyScancode code = kKeyNil; @@ -363,11 +362,12 @@ KeyScancode scancode_from_nsevent(NSEvent* event) int length = CFStringGetLength(strRef); if (length > 0) { // Converts the first unicode char into a macOS virtual key - UInt16 chr = CFStringGetCharacterAtIndex(strRef, length-1); + UInt16 chr = CFStringGetCharacterAtIndex(strRef, length - 1); code = from_char_to_scancode(chr); if (code != kKeyNil) { KEY_TRACE("scancode_from_nsevent %d -> %d (get_unicode_from_key_code)\n", - (int)chr, (int)code); + (int)chr, + (int)code); } } @@ -380,8 +380,7 @@ KeyScancode scancode_from_nsevent(NSEvent* event) #endif KeyScancode code = from_keycode_to_scancode(event.keyCode); - KEY_TRACE("scancode_from_nsevent %d -> %d (keyCode)\n", - (int)event.keyCode, (int)code); + KEY_TRACE("scancode_from_nsevent %d -> %d (keyCode)\n", (int)event.keyCode, (int)code); return code; } @@ -400,13 +399,14 @@ CFStringRef get_unicode_from_key_code(const UInt16 keyCode, // kTISPropertyUnicodeKeyLayoutData (returns nullptr) when the input // source is Japanese (Romaji/Hiragana/Katakana). - //TISInputSourceRef inputSource = TISCopyCurrentKeyboardInputSource(); + // TISInputSourceRef inputSource = TISCopyCurrentKeyboardInputSource(); TISInputSourceRef inputSource = TISCopyCurrentKeyboardLayoutInputSource(); - CFDataRef keyLayoutData = (CFDataRef)TISGetInputSourceProperty(inputSource, kTISPropertyUnicodeKeyLayoutData); + CFDataRef keyLayoutData = (CFDataRef)TISGetInputSourceProperty(inputSource, + kTISPropertyUnicodeKeyLayoutData); const UCKeyboardLayout* keyLayout = - (keyLayoutData ? (const UCKeyboardLayout*)CFDataGetBytePtr(keyLayoutData): nullptr); + (keyLayoutData ? (const UCKeyboardLayout*)CFDataGetBytePtr(keyLayoutData) : nullptr); - UInt32 deadKeyStateWrap = (deadKeyState ? *deadKeyState: 0); + UInt32 deadKeyStateWrap = (deadKeyState ? *deadKeyState : 0); UniChar output[4]; UniCharCount length; @@ -427,17 +427,16 @@ CFStringRef get_unicode_from_key_code(const UInt16 keyCode, // Reference here: // https://developer.apple.com/reference/coreservices/1390584-uckeytranslate?language=objc - UCKeyTranslate( - keyLayout, - keyCode, - kUCKeyActionDown, - modifier_key_state, - LMGetKbdType(), - (deadKeyState ? 0: kUCKeyTranslateNoDeadKeysMask), - &deadKeyStateWrap, - sizeof(output) / sizeof(output[0]), - &length, - output); + UCKeyTranslate(keyLayout, + keyCode, + kUCKeyActionDown, + modifier_key_state, + LMGetKbdType(), + (deadKeyState ? 0 : kUCKeyTranslateNoDeadKeysMask), + &deadKeyStateWrap, + sizeof(output) / sizeof(output[0]), + &length, + output); if (deadKeyState) *deadKeyState = deadKeyStateWrap; diff --git a/os/osx/logger.h b/os/osx/logger.h index d86a14c9e..4e63d4c24 100644 --- a/os/osx/logger.h +++ b/os/osx/logger.h @@ -13,10 +13,10 @@ namespace os { - class LoggerOSX : public Logger { - public: - void logError(const char* error) override; - }; +class LoggerOSX : public Logger { +public: + void logError(const char* error) override; +}; } // namespace os diff --git a/os/osx/menus.h b/os/osx/menus.h index 402ff93ed..af4f2420d 100644 --- a/os/osx/menus.h +++ b/os/osx/menus.h @@ -13,13 +13,13 @@ namespace os { - class MenusOSX : public Menus { - public: - MenusOSX(); - MenuRef makeMenu() override; - MenuItemRef makeMenuItem(const MenuItemInfo& info) override; - void setAppMenu(const MenuRef& menu) override; - }; +class MenusOSX : public Menus { +public: + MenusOSX(); + MenuRef makeMenu() override; + MenuItemRef makeMenuItem(const MenuItemInfo& info) override; + void setAppMenu(const MenuRef& menu) override; +}; } // namespace os diff --git a/os/osx/menus.mm b/os/osx/menus.mm index e8e8e56ba..22bc54b8d 100644 --- a/os/osx/menus.mm +++ b/os/osx/menus.mm @@ -15,7 +15,7 @@ #include "os/shortcut.h" namespace os { - class MenuItemOSX; +class MenuItemOSX; } @interface NSMenuOSX : NSMenu @@ -70,6 +70,7 @@ - (void)validateLafMenuItem; void insertItem(const int index, const MenuItemRef& item) override; void removeItem(const MenuItemRef& item) override; NSMenu* handle() { return m_handle; } + private: NSMenu* m_handle; }; @@ -110,7 +111,7 @@ - (void)executeMenuItem:(id)sender // mouse (i.e. some kind of event is generated). os::Event ev; ev.setType(os::Event::Callback); - ev.setCallback([self]{ original->execute(); }); + ev.setCallback([self] { original->execute(); }); os::queue_event(ev); } - (void)validateLafMenuItem @@ -125,17 +126,13 @@ - (void)validateLafMenuItem ////////////////////////////////////////////////////////////////////// // os::MenuItem impl -MenuItemOSX::MenuItemOSX(const MenuItemInfo& info) - : m_handle(nullptr) - , m_submenu(nullptr) +MenuItemOSX::MenuItemOSX(const MenuItemInfo& info) : m_handle(nullptr), m_submenu(nullptr) { switch (info.type) { - case MenuItemInfo::Normal: { SEL sel = nil; id target = nil; switch (info.action) { - case MenuItemInfo::UserDefined: sel = @selector(executeMenuItem:); @@ -146,36 +143,23 @@ - (void)validateLafMenuItem target = m_handle; break; - case MenuItemInfo::Hide: - sel = @selector(hide:); - break; + case MenuItemInfo::Hide: sel = @selector(hide:); break; - case MenuItemInfo::HideOthers: - sel = @selector(hideOtherApplications:); - break; + case MenuItemInfo::HideOthers: sel = @selector(hideOtherApplications:); break; - case MenuItemInfo::ShowAll: - sel = @selector(unhideAllApplications:); - break; + case MenuItemInfo::ShowAll: sel = @selector(unhideAllApplications:); break; - case MenuItemInfo::Quit: - sel = @selector(terminate:); - break; + case MenuItemInfo::Quit: sel = @selector(terminate:); break; - case MenuItemInfo::Minimize: - sel = @selector(performMiniaturize:); - break; + case MenuItemInfo::Minimize: sel = @selector(performMiniaturize:); break; - case MenuItemInfo::Zoom: - sel = @selector(performZoom:); - break; + case MenuItemInfo::Zoom: sel = @selector(performZoom:); break; } - m_handle = - [[NSMenuItemOSX alloc:AddRef(this)] - initWithTitle:[NSString stringWithUTF8String:info.text.c_str()] - action:sel - keyEquivalent:@""]; + m_handle = [[NSMenuItemOSX alloc:AddRef(this)] + initWithTitle:[NSString stringWithUTF8String:info.text.c_str()] + action:sel + keyEquivalent:@""]; m_handle.target = target; m_execute = info.execute; @@ -186,9 +170,7 @@ - (void)validateLafMenuItem break; } - case MenuItemInfo::Separator: - m_handle = [NSMenuItem separatorItem]; - break; + case MenuItemInfo::Separator: m_handle = [NSMenuItem separatorItem]; break; } } @@ -245,10 +227,14 @@ - (void)validateLafMenuItem { KeyModifiers mods = shortcut.modifiers(); NSEventModifierFlags nsFlags = 0; - if (mods & kKeyShiftModifier) nsFlags |= NSEventModifierFlagShift; - if (mods & kKeyCtrlModifier) nsFlags |= NSEventModifierFlagControl; - if (mods & kKeyAltModifier) nsFlags |= NSEventModifierFlagOption; - if (mods & kKeyCmdModifier) nsFlags |= NSEventModifierFlagCommand; + if (mods & kKeyShiftModifier) + nsFlags |= NSEventModifierFlagShift; + if (mods & kKeyCtrlModifier) + nsFlags |= NSEventModifierFlagControl; + if (mods & kKeyAltModifier) + nsFlags |= NSEventModifierFlagOption; + if (mods & kKeyCmdModifier) + nsFlags |= NSEventModifierFlagCommand; NSString* keyStr; if (shortcut.unicode()) { @@ -322,8 +308,7 @@ - (void)validateLafMenuItem void MenuOSX::insertItem(const int index, const MenuItemRef& item) { ASSERT(item); - [m_handle insertItem:((MenuItemOSX*)item.get())->handle() - atIndex:index]; + [m_handle insertItem:((MenuItemOSX*)item.get())->handle() atIndex:index]; } void MenuOSX::removeItem(const MenuItemRef& item) diff --git a/os/osx/native_dialogs.h b/os/osx/native_dialogs.h index ae4bd95e0..213cfb800 100644 --- a/os/osx/native_dialogs.h +++ b/os/osx/native_dialogs.h @@ -13,11 +13,11 @@ namespace os { - class NativeDialogsOSX : public NativeDialogs { - public: - NativeDialogsOSX(); - FileDialogRef makeFileDialog() override; - }; +class NativeDialogsOSX : public NativeDialogs { +public: + NativeDialogsOSX(); + FileDialogRef makeFileDialog() override; +}; } // namespace os diff --git a/os/osx/native_dialogs.mm b/os/osx/native_dialogs.mm index f995c0121..7cc88e7a0 100644 --- a/os/osx/native_dialogs.mm +++ b/os/osx/native_dialogs.mm @@ -46,8 +46,8 @@ // class OSXEditMenuHack { public: - OSXEditMenuHack(NSMenuItem* currentEditMenuItem) - : m_editMenuItem(currentEditMenuItem) { + OSXEditMenuHack(NSMenuItem* currentEditMenuItem) : m_editMenuItem(currentEditMenuItem) + { if (!m_editMenuItem) return; @@ -64,13 +64,15 @@ [editMenu addItem:newItem(@"Copy", @selector(copy:), @"c", NSEventModifierFlagCommand)]; [editMenu addItem:newItem(@"Paste", @selector(paste:), @"v", NSEventModifierFlagCommand)]; [editMenu addItem:newItem(@"Delete", @selector(delete:), @"", 0)]; - [editMenu addItem:newItem(@"Select All", @selector(selectAll:), @"a", NSEventModifierFlagCommand)]; + [editMenu + addItem:newItem(@"Select All", @selector(selectAll:), @"a", NSEventModifierFlagCommand)]; m_submenu = m_editMenuItem.submenu; m_editMenuItem.submenu = editMenu; } - ~OSXEditMenuHack() { + ~OSXEditMenuHack() + { if (!m_editMenuItem) return; @@ -82,30 +84,23 @@ } private: - NSMenuItem* newItem(NSString* title, SEL sel, - NSString* key, - NSEventModifierFlags flags) { - auto item = [[NSMenuItem alloc] initWithTitle:title - action:sel - keyEquivalent:key]; + NSMenuItem* newItem(NSString* title, SEL sel, NSString* key, NSEventModifierFlags flags) + { + auto item = [[NSMenuItem alloc] initWithTitle:title action:sel keyEquivalent:key]; if (flags) item.keyEquivalentModifierMask = flags; // Search for menu items in the main menu that already contain the // same keyEquivalent, and disable them temporarily. - disableMenuItemsWithKeyEquivalent( - [[NSApplication sharedApplication] mainMenu], - key, flags); + disableMenuItemsWithKeyEquivalent([[NSApplication sharedApplication] mainMenu], key, flags); return item; } - void disableMenuItemsWithKeyEquivalent(NSMenu* menu, - NSString* key, - NSEventModifierFlags flags) { + void disableMenuItemsWithKeyEquivalent(NSMenu* menu, NSString* key, NSEventModifierFlags flags) + { for (NSMenuItem* item in menu.itemArray) { - if ([item.keyEquivalent isEqualToString:key] && - item.keyEquivalentModifierMask == flags) { + if ([item.keyEquivalent isEqualToString:key] && item.keyEquivalentModifierMask == flags) { m_restoreKeys[item] = item.keyEquivalent; item.keyEquivalent = @""; } @@ -170,7 +165,7 @@ - (void)runModal OSXEditMenuHack hack(os::g_standardEditMenuItem); [[[NSApplication sharedApplication] mainMenu] setAutoenablesItems:NO]; -#ifndef __MAC_10_6 // runModalForTypes is deprecated in 10.6 +#ifndef __MAC_10_6 // runModalForTypes is deprecated in 10.6 if ([panel isKindOfClass:[NSOpenPanel class]]) { // As we're using OS X 10.4 framework, it looks like runModal // doesn't recognize the allowedFileTypes property. So we force it @@ -185,7 +180,7 @@ - (void)runModal } window->setCursor(oldCursor); - NSWindow* nsWindow = (__bridge NSWindow *)window->nativeHandle(); + NSWindow* nsWindow = (__bridge NSWindow*)window->nativeHandle(); [nsWindow makeKeyAndOrderFront:nil]; [[[NSApplication sharedApplication] mainMenu] setAutoenablesItems:YES]; } @@ -212,22 +207,16 @@ - (void)setFileTypeChangeObserver:(std::function)observer class FileDialogOSX : public CommonFileDialog { public: - FileDialogOSX() { - } + FileDialogOSX() {} - std::string fileName() override { - return m_filename; - } + std::string fileName() override { return m_filename; } - void getMultipleFileNames(base::paths& output) override { - output = m_filenames; - } + void getMultipleFileNames(base::paths& output) override { output = m_filenames; } - void setFileName(const std::string& filename) override { - m_filename = filename; - } + void setFileName(const std::string& filename) override { m_filename = filename; } - Result show(Window* window) override { + Result show(Window* window) override + { Result retValue = Result::Cancel; @autoreleasepool { NSSavePanel* panel = nil; @@ -237,9 +226,9 @@ Result show(Window* window) override { } else { panel = [NSOpenPanel new]; - [(NSOpenPanel*)panel setAllowsMultipleSelection:(m_type == Type::OpenFiles ? YES: NO)]; - [(NSOpenPanel*)panel setCanChooseFiles:(m_type != Type::OpenFolder ? YES: NO)]; - [(NSOpenPanel*)panel setCanChooseDirectories:(m_type == Type::OpenFolder ? YES: NO)]; + [(NSOpenPanel*)panel setAllowsMultipleSelection:(m_type == Type::OpenFiles ? YES : NO)]; + [(NSOpenPanel*)panel setCanChooseFiles:(m_type != Type::OpenFolder ? YES : NO)]; + [(NSOpenPanel*)panel setCanChooseDirectories:(m_type == Type::OpenFolder ? YES : NO)]; } [panel setTitle:[NSString stringWithUTF8String:m_title.c_str()]]; @@ -248,8 +237,7 @@ Result show(Window* window) override { if (m_type != Type::OpenFolder && !m_filters.empty()) { NSMutableArray* types = [[NSMutableArray alloc] init]; - if (m_type == Type::OpenFile || - m_type == Type::OpenFiles) { + if (m_type == Type::OpenFile || m_type == Type::OpenFiles) { // Empty item so we can show all the allowed file types again [types addObject:@""]; } @@ -276,7 +264,8 @@ Result show(Window* window) override { std::string defPath = base::get_file_path(m_filename); std::string defName = base::get_file_name(m_filename); if (!defPath.empty()) - [panel setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:defPath.c_str()]]]; + [panel + setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:defPath.c_str()]]]; if (!defName.empty()) [panel setNameFieldStringValue:[NSString stringWithUTF8String:defName.c_str()]]; @@ -307,7 +296,7 @@ Result show(Window* window) override { // Function to be called when user selects another file type // from the combobox. - [helper setFileTypeChangeObserver:[this, panel](){ + [helper setFileTypeChangeObserver:[this, panel]() { NSString* extension = m_popup.selectedItem.title; if (extension.length == 0) { NSMutableArray* allTypes = [[NSMutableArray alloc] init]; @@ -346,11 +335,11 @@ Result show(Window* window) override { } private: - // The accessory view is any extra NSView that we want to show in // the NSSavePanel/NSOpenPanel, in our case, we want to show a // combobox (NSPopUpButton) with the available file formats. - NSView* createAccessoryView(NSSavePanel* panel) { + NSView* createAccessoryView(NSSavePanel* panel) + { auto label = [NSTextField labelWithString:@"File Format:"]; if ([NSFont respondsToSelector:@selector(smallSystemFontSize)]) @@ -359,8 +348,7 @@ Result show(Window* window) override { label.textColor = [NSColor secondaryLabelColor]; // Combobox with file formats - auto popup = [[NSPopUpButton alloc] initWithFrame:NSZeroRect - pullsDown:false]; + auto popup = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:false]; popup.autoenablesItems = false; // All items enabled for (NSString* item in panel.allowedFileTypes) { [popup addItemWithTitle:item]; diff --git a/os/osx/screen.h b/os/osx/screen.h index 64cebfa41..957cc2dc4 100644 --- a/os/osx/screen.h +++ b/os/osx/screen.h @@ -10,16 +10,17 @@ #ifdef __OBJC__ -#include "os/osx/color_space.h" -#include "os/screen.h" + #include "os/osx/color_space.h" + #include "os/screen.h" -#include + #include namespace os { class ScreenOSX : public Screen { public: - ScreenOSX(NSScreen* screen) : m_screen(screen) { + ScreenOSX(NSScreen* screen) : m_screen(screen) + { auto rc = screen.frame; auto wa = screen.visibleFrame; @@ -33,17 +34,15 @@ class ScreenOSX : public Screen { m_workarea.w = wa.size.width; m_workarea.h = wa.size.height; } - bool isMainScreen() const override { - return m_screen == [NSScreen mainScreen]; - } - gfx::Rect bounds() const override { return m_bounds; } + bool isMainScreen() const override { return m_screen == [NSScreen mainScreen]; } + gfx::Rect bounds() const override { return m_bounds; } gfx::Rect workarea() const override { return m_workarea; } - os::ColorSpaceRef colorSpace() const override { + os::ColorSpaceRef colorSpace() const override + { return convert_nscolorspace_to_os_colorspace([m_screen colorSpace]); } - void* nativeHandle() const override { - return (__bridge void*)m_screen; - } + void* nativeHandle() const override { return (__bridge void*)m_screen; } + private: NSScreen* m_screen; gfx::Rect m_bounds; diff --git a/os/osx/system.h b/os/osx/system.h index 67f1ef11b..acece367e 100644 --- a/os/osx/system.h +++ b/os/osx/system.h @@ -30,49 +30,43 @@ void osx_set_async_view(bool state); class SystemOSX : public CommonSystem { public: - SystemOSX() : m_menus(nullptr) { } + SystemOSX() : m_menus(nullptr) {} ~SystemOSX(); - void setAppMode(AppMode appMode) override { - AppOSX::instance()->setAppMode(appMode); - } + void setAppMode(AppMode appMode) override { AppOSX::instance()->setAppMode(appMode); } - void markCliFileAsProcessed(const std::string& fn) override { + void markCliFileAsProcessed(const std::string& fn) override + { AppOSX::instance()->markCliFileAsProcessed(fn); } - void finishLaunching() override { + void finishLaunching() override + { // Start processing NSApplicationDelegate events. (E.g. after // calling this we'll receive application:openFiles: and we'll // generate DropFiles events.) events AppOSX::instance()->finishLaunching(); } - void activateApp() override { - AppOSX::instance()->activateApp(); - } + void activateApp() override { AppOSX::instance()->activateApp(); } - Logger* logger() override { - return new LoggerOSX; - } + Logger* logger() override { return new LoggerOSX; } - Menus* menus() override { + Menus* menus() override + { if (!m_menus) m_menus = make_ref(); return m_menus.get(); } - bool isKeyPressed(KeyScancode scancode) override { - return osx_is_key_pressed(scancode); - } + bool isKeyPressed(KeyScancode scancode) override { return osx_is_key_pressed(scancode); } - int getUnicodeFromScancode(KeyScancode scancode) override { + int getUnicodeFromScancode(KeyScancode scancode) override + { return osx_get_unicode_from_scancode(scancode); } - CursorRef makeCursor(const Surface* surface, - const gfx::Point& focus, - const int scale) override; + CursorRef makeCursor(const Surface* surface, const gfx::Point& focus, const int scale) override; gfx::Point mousePosition() const override; void setMousePosition(const gfx::Point& screenPosition) override; diff --git a/os/osx/system.mm b/os/osx/system.mm index b2885278c..92cabef95 100644 --- a/os/osx/system.mm +++ b/os/osx/system.mm @@ -5,7 +5,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/osx/system.h" @@ -16,15 +16,13 @@ class CursorOSX : public os::Cursor { public: - CursorOSX(NSCursor* nsCursor) : m_nsCursor(nsCursor) { } + CursorOSX(NSCursor* nsCursor) : m_nsCursor(nsCursor) {} ~CursorOSX() { m_nsCursor = nil; } CursorOSX(const CursorOSX&) = delete; CursorOSX& operator=(const CursorOSX&) = delete; - void* nativeHandle() override { - return (__bridge void*)m_nsCursor; - } + void* nativeHandle() override { return (__bridge void*)m_nsCursor; } private: NSCursor* m_nsCursor; @@ -35,9 +33,7 @@ destroyInstance(); } -CursorRef SystemOSX::makeCursor(const Surface* surface, - const gfx::Point& focus, - const int scale) +CursorRef SystemOSX::makeCursor(const Surface* surface, const gfx::Point& focus, const int scale) { ASSERT(surface); SurfaceFormatData format; @@ -45,33 +41,32 @@ if (format.bitsPerPixel != 32) return nullptr; - const int w = scale*surface->width(); - const int h = scale*surface->height(); + const int w = scale * surface->width(); + const int h = scale * surface->height(); - if (4*w*h == 0) + if (4 * w * h == 0) return nullptr; @autoreleasepool { - NSBitmapImageRep* bmp = - [[NSBitmapImageRep alloc] - initWithBitmapDataPlanes:nil - pixelsWide:w - pixelsHigh:h - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat:NSAlphaNonpremultipliedBitmapFormat - bytesPerRow:w*4 - bitsPerPixel:32]; + NSBitmapImageRep* bmp = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:nil + pixelsWide:w + pixelsHigh:h + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:NSAlphaNonpremultipliedBitmapFormat + bytesPerRow:w * 4 + bitsPerPixel:32]; if (!bmp) return nullptr; uint32_t* dst = (uint32_t*)[bmp bitmapData]; - for (int y=0; ygetData(0, y/scale); - for (int x=0, u=0; xgetData(0, y / scale); + for (int x = 0, u = 0; x < w; ++x, ++dst) { *dst = *src; if (++u == scale) { u = 0; @@ -86,10 +81,9 @@ [img addRepresentation:bmp]; - NSCursor* nsCursor = - [[NSCursor alloc] initWithImage:img - hotSpot:NSMakePoint(scale*focus.x + scale/2, - scale*focus.y + scale/2)]; + NSCursor* nsCursor = [[NSCursor alloc] + initWithImage:img + hotSpot:NSMakePoint(scale * focus.x + scale / 2, scale * focus.y + scale / 2)]; if (!nsCursor) return nullptr; @@ -108,15 +102,15 @@ { NSScreen* menuBarScreen = [NSScreen screens][0]; CGWarpMouseCursorPosition( - CGPointMake(screenPosition.x, - menuBarScreen.frame.size.height - screenPosition.y)); + CGPointMake(screenPosition.x, menuBarScreen.frame.size.height - screenPosition.y)); } gfx::Color SystemOSX::getColorFromScreen(const gfx::Point& screenPosition) const { gfx::Color color = gfx::ColorNone; - CGImageRef image = CGDisplayCreateImageForRect(CGMainDisplayID(), - CGRectMake(screenPosition.x, screenPosition.y, 1, 1)); + CGImageRef image = CGDisplayCreateImageForRect( + CGMainDisplayID(), + CGRectMake(screenPosition.x, screenPosition.y, 1, 1)); if (image) { CGBitmapInfo info = CGImageGetBitmapInfo(image); CGDataProviderRef provider = CGImageGetDataProvider(image); @@ -137,7 +131,7 @@ } // If we release the provider then CGImageRelease() crashes - //CGDataProviderRelease(provider); + // CGDataProviderRelease(provider); } CGImageRelease(image); } @@ -156,4 +150,4 @@ list.push_back(make_ref(screen)); } -} +} // namespace os diff --git a/os/osx/view.h b/os/osx/view.h index 2aab6735b..02872f0a1 100644 --- a/os/osx/view.h +++ b/os/osx/view.h @@ -14,10 +14,10 @@ #ifdef __OBJC__ -#include + #include namespace os { - class WindowOSX; +class WindowOSX; } @interface ViewOSX : NSView { diff --git a/os/osx/view.mm b/os/osx/view.mm index 5c2042f1b..fc5ba4f3a 100644 --- a/os/osx/view.mm +++ b/os/osx/view.mm @@ -8,16 +8,16 @@ #define KEY_TRACE(...) #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/osx/view.h" #include "base/debug.h" #include "gfx/point.h" -#include "os/osx/dnd.h" #include "os/event.h" #include "os/event_queue.h" +#include "os/osx/dnd.h" #include "os/osx/generate_drop_files.h" #include "os/osx/keys.h" #include "os/osx/window.h" @@ -49,15 +49,13 @@ gfx::Point get_local_mouse_pos(NSView* view, NSEvent* event) { - NSPoint point = [view convertPoint:[event locationInWindow] - fromView:nil]; + NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil]; int scale = 1; if ([view window]) scale = [(WindowOSXObjc*)[view window] scale]; // "os" layer coordinates expect (X,Y) origin at the top-left corner. - return gfx::Point(point.x / scale, - (view.bounds.size.height - point.y) / scale); + return gfx::Point(point.x / scale, (view.bounds.size.height - point.y) / scale); } Event::MouseButton get_mouse_buttons(NSEvent* event) @@ -67,14 +65,11 @@ switch (event.type) { case NSEventTypeLeftMouseDown: case NSEventTypeLeftMouseUp: - case NSEventTypeLeftMouseDragged: - return Event::LeftButton; + case NSEventTypeLeftMouseDragged: return Event::LeftButton; case NSEventTypeRightMouseDown: case NSEventTypeRightMouseUp: - case NSEventTypeRightMouseDragged: - return Event::RightButton; - default: - break; + case NSEventTypeRightMouseDragged: return Event::RightButton; + default: break; } switch (event.buttonNumber) { @@ -93,11 +88,16 @@ KeyModifiers get_modifiers_from_nsevent(NSEvent* event) { int modifiers = kKeyNoneModifier; NSEventModifierFlags nsFlags = event.modifierFlags; - if (nsFlags & NSEventModifierFlagShift) modifiers |= kKeyShiftModifier; - if (nsFlags & NSEventModifierFlagControl) modifiers |= kKeyCtrlModifier; - if (nsFlags & NSEventModifierFlagOption) modifiers |= kKeyAltModifier; - if (nsFlags & NSEventModifierFlagCommand) modifiers |= kKeyCmdModifier; - if (osx_is_key_pressed(kKeySpace)) modifiers |= kKeySpaceModifier; + if (nsFlags & NSEventModifierFlagShift) + modifiers |= kKeyShiftModifier; + if (nsFlags & NSEventModifierFlagControl) + modifiers |= kKeyCtrlModifier; + if (nsFlags & NSEventModifierFlagOption) + modifiers |= kKeyAltModifier; + if (nsFlags & NSEventModifierFlagCommand) + modifiers |= kKeyCmdModifier; + if (osx_is_key_pressed(kKeySpace)) + modifiers |= kKeySpaceModifier; return (KeyModifiers)modifiers; } @@ -145,13 +145,11 @@ - (id)initWithFrame:(NSRect)frameRect self = [super initWithFrame:frameRect]; if (self != nil) { [self createMouseTrackingArea]; - [self registerForDraggedTypes: - [NSArray arrayWithObjects: - NSFilenamesPboardType, - NSPasteboardTypePNG, - NSPasteboardTypeTIFF, - NSURLPboardType, - nil]]; + [self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, + NSPasteboardTypePNG, + NSPasteboardTypeTIFF, + NSURLPboardType, + nil]]; // Create a CALayer for backing content with async drawing. This // fixes performance issues on Retina displays with wide color @@ -262,13 +260,12 @@ - (void)keyDown:(NSEvent*)event ev.setType(Event::KeyDown); ev.setScancode(scancode); ev.setModifiers(get_modifiers_from_nsevent(event)); - ev.setRepeat(event.ARepeat ? 1: 0); + ev.setRepeat(event.ARepeat ? 1 : 0); ev.setUnicodeChar(0); bool sendMsg = true; - CFStringRef strRef = get_unicode_from_key_code(event.keyCode, - event.modifierFlags); + CFStringRef strRef = get_unicode_from_key_code(event.keyCode, event.modifierFlags); if (strRef) { int length = CFStringGetLength(strRef); if (length == 1) @@ -277,17 +274,15 @@ - (void)keyDown:(NSEvent*)event } if (scancode >= 0 && scancode < kKeyScancodes) - g_pressedKeys[scancode] = (ev.unicodeChar() ? ev.unicodeChar(): 1); + g_pressedKeys[scancode] = (ev.unicodeChar() ? ev.unicodeChar() : 1); if (g_translateDeadKeys) { - strRef = get_unicode_from_key_code(event.keyCode, - event.modifierFlags, - &g_lastDeadKeyState); + strRef = get_unicode_from_key_code(event.keyCode, event.modifierFlags, &g_lastDeadKeyState); if (strRef) { int length = CFStringGetLength(strRef); if (length > 0) { sendMsg = false; - for (int i=0; ionResize(gfx::Size(newSize.width, - newSize.height)); + m_impl->onResize(gfx::Size(newSize.width, newSize.height)); } } @@ -545,12 +531,10 @@ - (void)scrollWheel:(NSEvent*)event // preciseScrollingDelta, resulting in unexpected behavior as we // don't know how to interpret the scrollingDelta values // accurately from those devices. - (event.phase != NSEventPhaseNone || - event.momentumPhase != NSEventPhaseNone)) { + (event.phase != NSEventPhaseNone || event.momentumPhase != NSEventPhaseNone)) { ev.setPointerType(os::PointerType::Touchpad); // TODO we shouldn't change the sign - ev.setWheelDelta(gfx::Point(-event.scrollingDeltaX / scale, - -event.scrollingDeltaY / scale)); + ev.setWheelDelta(gfx::Point(-event.scrollingDeltaX / scale, -event.scrollingDeltaY / scale)); ev.setPreciseWheel(true); } else { @@ -587,12 +571,10 @@ - (void)tabletProximity:(NSEvent*)event { if (event.isEnteringProximity == YES) { switch (event.pointingDeviceType) { - case NSPointingDeviceTypePen: m_pointerType = os::PointerType::Pen; break; + case NSPointingDeviceTypePen: m_pointerType = os::PointerType::Pen; break; case NSPointingDeviceTypeCursor: m_pointerType = os::PointerType::Cursor; break; case NSPointingDeviceTypeEraser: m_pointerType = os::PointerType::Eraser; break; - default: - m_pointerType = os::PointerType::Unknown; - break; + default: m_pointerType = os::PointerType::Unknown; break; } } else { @@ -614,16 +596,13 @@ - (void)setCursor:(NSCursor*)cursor - (void)createMouseTrackingArea { // Create a tracking area to receive mouseMoved events - m_trackingArea = - [[NSTrackingArea alloc] - initWithRect:self.bounds - options:(NSTrackingMouseEnteredAndExited | - NSTrackingMouseMoved | - NSTrackingActiveInActiveApp | - NSTrackingEnabledDuringMouseDrag | - NSTrackingCursorUpdate) - owner:self - userInfo:nil]; + m_trackingArea = [[NSTrackingArea alloc] + initWithRect:self.bounds + options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | + NSTrackingActiveInActiveApp | NSTrackingEnabledDuringMouseDrag | + NSTrackingCursorUpdate) + owner:self + userInfo:nil]; [self addTrackingArea:m_trackingArea]; } @@ -650,8 +629,7 @@ - (void)updateCurrentCursor // functions are hard to balance. if (!g_emptyNsCursor) { NSImage* img = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)]; - g_emptyNsCursor = [[NSCursor alloc] initWithImage:img - hotSpot:NSMakePoint(0, 0)]; + g_emptyNsCursor = [[NSCursor alloc] initWithImage:img hotSpot:NSMakePoint(0, 0)]; } [g_emptyNsCursor set]; } @@ -713,7 +691,7 @@ - (void)draggingExited:(id)sender window->notifyDragLeave(ev); } -- (BOOL)performDragOperation:(id )sender +- (BOOL)performDragOperation:(id)sender { NSPasteboard* pasteboard = [sender draggingPasteboard]; WindowOSXObjc* target = (WindowOSXObjc*)sender.draggingDestinationWindow; @@ -743,7 +721,7 @@ - (void)doCommandBySelector:(SEL)selector - (void)setTranslateDeadKeys:(BOOL)state { - g_translateDeadKeys = (state ? true: false); + g_translateDeadKeys = (state ? true : false); g_lastDeadKeyState = 0; } diff --git a/os/osx/window.h b/os/osx/window.h index bdacc1fe6..a14fb9a76 100644 --- a/os/osx/window.h +++ b/os/osx/window.h @@ -10,7 +10,7 @@ #pragma once #ifdef __OBJC__ -#include + #include #endif #include "gfx/point.h" @@ -26,10 +26,10 @@ #include "os/window_spec.h" namespace os { - class Event; - class Surface; - class WindowOSX; -} +class Event; +class Surface; +class WindowOSX; +} // namespace os #ifdef __OBJC__ @@ -42,8 +42,7 @@ namespace os { ViewOSX* __strong m_view; int m_scale; } -- (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl - spec:(const os::WindowSpec*)spec; +- (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl spec:(const os::WindowSpec*)spec; - (os::WindowOSX*)impl; - (void)removeImpl; - (int)scale; @@ -58,7 +57,7 @@ using WindowOSXObjc_id = WindowOSXObjc*; #else -#include + #include using WindowOSXObjc_id = id; #endif @@ -92,8 +91,7 @@ class WindowOSX : public os::Window { void releaseMouse() override; void setMousePosition(const gfx::Point& position) override; - void performWindowAction(const WindowAction action, - const Event* event) override; + void performWindowAction(const WindowAction action, const Event* event) override; os::ScreenRef screen() const override; os::ColorSpaceRef colorSpace() const override; diff --git a/os/osx/window.mm b/os/osx/window.mm index b01208b9d..855c7c2d7 100644 --- a/os/osx/window.mm +++ b/os/osx/window.mm @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/osx/window.h" @@ -22,8 +22,7 @@ @implementation WindowOSXObjc -- (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl - spec:(const os::WindowSpec*)spec +- (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl spec:(const os::WindowSpec*)spec { // This autoreleasepool reduces the total number of references that // the NSWindow object has when we close it. @@ -38,30 +37,33 @@ - (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl nsScreen = [NSScreen mainScreen]; NSWindowStyleMask style = 0; - if (spec->titled()) style |= NSWindowStyleMaskTitled; - if (spec->closable()) style |= NSWindowStyleMaskClosable; - if (spec->minimizable()) style |= NSWindowStyleMaskMiniaturizable; - if (spec->resizable()) style |= NSWindowStyleMaskResizable; - if (spec->borderless()) style |= NSWindowStyleMaskBorderless; + if (spec->titled()) + style |= NSWindowStyleMaskTitled; + if (spec->closable()) + style |= NSWindowStyleMaskClosable; + if (spec->minimizable()) + style |= NSWindowStyleMaskMiniaturizable; + if (spec->resizable()) + style |= NSWindowStyleMaskResizable; + if (spec->borderless()) + style |= NSWindowStyleMaskBorderless; NSRect contentRect; if (!spec->contentRect().isEmpty()) { - contentRect = - NSMakeRect(spec->contentRect().x - nsScreen.frame.origin.x, - nsScreen.frame.size.height - spec->contentRect().y2() - nsScreen.frame.origin.y, - spec->contentRect().w, - spec->contentRect().h); + contentRect = NSMakeRect( + spec->contentRect().x - nsScreen.frame.origin.x, + nsScreen.frame.size.height - spec->contentRect().y2() - nsScreen.frame.origin.y, + spec->contentRect().w, + spec->contentRect().h); } else if (!spec->frame().isEmpty()) { - NSRect frameRect = - NSMakeRect(spec->frame().x - nsScreen.frame.origin.x, - nsScreen.frame.size.height - spec->frame().y2() - nsScreen.frame.origin.y, - spec->frame().w, - spec->frame().h); - - contentRect = - [NSWindow contentRectForFrameRect:frameRect - styleMask:style]; + NSRect frameRect = NSMakeRect( + spec->frame().x - nsScreen.frame.origin.x, + nsScreen.frame.size.height - spec->frame().y2() - nsScreen.frame.origin.y, + spec->frame().w, + spec->frame().h); + + contentRect = [NSWindow contentRectForFrameRect:frameRect styleMask:style]; } else { // TODO is there a default size for macOS apps? @@ -114,7 +116,8 @@ - (WindowOSXObjc*)initWithImpl:(os::WindowOSX*)impl } if (spec->parent()) - self.parentWindow = (__bridge NSWindow*)static_cast(spec->parent())->nativeHandle(); + self.parentWindow = + (__bridge NSWindow*)static_cast(spec->parent())->nativeHandle(); [self makeKeyAndOrderFront:self]; @@ -195,16 +198,13 @@ - (void)setScale:(int)scale - (gfx::Size)clientSize { - return gfx::Size([[self contentView] frame].size.width, - [[self contentView] frame].size.height); + return gfx::Size([[self contentView] frame].size.width, [[self contentView] frame].size.height); } - (void)setMousePosition:(const gfx::Point&)position { NSView* view = self.contentView; - NSPoint pt = NSMakePoint( - position.x*m_scale, - view.frame.size.height - position.y*m_scale); + NSPoint pt = NSMakePoint(position.x * m_scale, view.frame.size.height - position.y * m_scale); pt = [view convertPoint:pt toView:view]; pt = [view convertPoint:pt toView:nil]; @@ -212,8 +212,7 @@ - (void)setMousePosition:(const gfx::Point&)position pt.y = [[self screen] frame].size.height - pt.y; CGPoint pos = CGPointMake(pt.x, pt.y); - CGEventRef event = CGEventCreateMouseEvent( - NULL, kCGEventMouseMoved, pos, kCGMouseButtonLeft); + CGEventRef event = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, pos, kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, event); CFRelease(event); } @@ -229,48 +228,23 @@ - (BOOL)setNativeCursor:(os::NativeCursor)cursor case os::NativeCursor::SizeNE: case os::NativeCursor::SizeNW: case os::NativeCursor::SizeSE: - case os::NativeCursor::SizeSW: - nsCursor = [NSCursor arrowCursor]; - break; - case os::NativeCursor::Crosshair: - nsCursor = [NSCursor crosshairCursor]; - break; - case os::NativeCursor::IBeam: - nsCursor = [NSCursor IBeamCursor]; - break; - case os::NativeCursor::Link: - nsCursor = [NSCursor pointingHandCursor]; - break; - case os::NativeCursor::Forbidden: - nsCursor = [NSCursor operationNotAllowedCursor]; - break; - case os::NativeCursor::Move: - nsCursor = [NSCursor openHandCursor]; - break; - case os::NativeCursor::SizeNS: - nsCursor = [NSCursor resizeUpDownCursor]; - break; - case os::NativeCursor::SizeWE: - nsCursor = [NSCursor resizeLeftRightCursor]; - break; - case os::NativeCursor::SizeN: - nsCursor = [NSCursor resizeUpCursor]; - break; - case os::NativeCursor::SizeE: - nsCursor = [NSCursor resizeRightCursor]; - break; - case os::NativeCursor::SizeS: - nsCursor = [NSCursor resizeDownCursor]; - break; - case os::NativeCursor::SizeW: - nsCursor = [NSCursor resizeLeftCursor]; - break; - default: - break; + case os::NativeCursor::SizeSW: nsCursor = [NSCursor arrowCursor]; break; + case os::NativeCursor::Crosshair: nsCursor = [NSCursor crosshairCursor]; break; + case os::NativeCursor::IBeam: nsCursor = [NSCursor IBeamCursor]; break; + case os::NativeCursor::Link: nsCursor = [NSCursor pointingHandCursor]; break; + case os::NativeCursor::Forbidden: nsCursor = [NSCursor operationNotAllowedCursor]; break; + case os::NativeCursor::Move: nsCursor = [NSCursor openHandCursor]; break; + case os::NativeCursor::SizeNS: nsCursor = [NSCursor resizeUpDownCursor]; break; + case os::NativeCursor::SizeWE: nsCursor = [NSCursor resizeLeftRightCursor]; break; + case os::NativeCursor::SizeN: nsCursor = [NSCursor resizeUpCursor]; break; + case os::NativeCursor::SizeE: nsCursor = [NSCursor resizeRightCursor]; break; + case os::NativeCursor::SizeS: nsCursor = [NSCursor resizeDownCursor]; break; + case os::NativeCursor::SizeW: nsCursor = [NSCursor resizeLeftCursor]; break; + default: break; } [self.contentView setCursor:nsCursor]; - return (nsCursor ? YES: NO); + return (nsCursor ? YES : NO); } - (BOOL)canBecomeKeyWindow @@ -297,8 +271,7 @@ - (void)noResponderFor:(SEL)eventSelector void WindowOSX::createWindow(const os::WindowSpec& spec) { - m_nsWindow = [[WindowOSXObjc alloc] initWithImpl:this - spec:&spec]; + m_nsWindow = [[WindowOSXObjc alloc] initWithImpl:this spec:&spec]; m_nsWindow.releasedWhenClosed = true; } @@ -316,7 +289,7 @@ - (void)noResponderFor:(SEL)eventSelector { auto app = [NSApplication sharedApplication]; auto index = [app.windows indexOfObject:m_nsWindow]; - if (index+1 < app.windows.count) { + if (index + 1 < app.windows.count) { ++index; } else { @@ -326,8 +299,7 @@ - (void)noResponderFor:(SEL)eventSelector [[app.windows objectAtIndex:index] makeKeyWindow]; } - [m_nsWindow discardEventsMatchingMask:NSEventMaskAny - beforeEvent:nullptr]; + [m_nsWindow discardEventsMatchingMask:NSEventMaskAny beforeEvent:nullptr]; [m_nsWindow close]; } m_nsWindow = nil; @@ -343,7 +315,8 @@ - (void)noResponderFor:(SEL)eventSelector NSRect r = m_nsWindow.frame; return gfx::Rect(r.origin.x, m_nsWindow.screen.frame.size.height - r.origin.y - r.size.height, - r.size.width, r.size.height); + r.size.width, + r.size.height); } void WindowOSX::setFrame(const gfx::Rect& bounds) @@ -360,7 +333,8 @@ - (void)noResponderFor:(SEL)eventSelector NSRect r = [m_nsWindow contentRectForFrameRect:m_nsWindow.frame]; return gfx::Rect(r.origin.x, m_nsWindow.screen.frame.size.height - r.origin.y - r.size.height, - r.size.width, r.size.height); + r.size.width, + r.size.height); } gfx::Rect WindowOSX::restoredFrame() const @@ -395,8 +369,7 @@ - (void)noResponderFor:(SEL)eventSelector { // Return true if the NSWindow is minimized or if the NSApplication // is hidden. - return (m_nsWindow.miniaturized || - os::AppOSX::instance()->isHidden()); + return (m_nsWindow.miniaturized || os::AppOSX::instance()->isHidden()); } bool WindowOSX::isFullscreen() const @@ -444,8 +417,7 @@ - (void)noResponderFor:(SEL)eventSelector [m_nsWindow setMousePosition:position]; } -void WindowOSX::performWindowAction(const WindowAction action, - const Event* event) +void WindowOSX::performWindowAction(const WindowAction action, const Event* event) { if (action == WindowAction::Move) { // We cannot use the "m_nsWindow.currentEvent" event directly on @@ -468,16 +440,15 @@ - (void)noResponderFor:(SEL)eventSelector mousePosOnWindow = rc.origin; } - NSEvent* newEvent = - [NSEvent mouseEventWithType:NSEventTypeLeftMouseDown - location:mousePosOnWindow - modifierFlags:0 - timestamp:0 - windowNumber:m_nsWindow.windowNumber - context:nil - eventNumber:0 - clickCount:1 - pressure:1.0]; + NSEvent* newEvent = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDown + location:mousePosOnWindow + modifierFlags:0 + timestamp:0 + windowNumber:m_nsWindow.windowNumber + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; [m_nsWindow performWindowDragWithEvent:newEvent]; } @@ -531,20 +502,19 @@ - (void)noResponderFor:(SEL)eventSelector bool WindowOSX::setCursor(NativeCursor cursor) { - return ([m_nsWindow setNativeCursor:cursor] ? true: false); + return ([m_nsWindow setNativeCursor:cursor] ? true : false); } bool WindowOSX::setCursor(const CursorRef& cursor) { [m_nsWindow.contentView - setCursor:(cursor ? (__bridge NSCursor*)cursor->nativeHandle(): - nullptr)]; + setCursor:(cursor ? (__bridge NSCursor*)cursor->nativeHandle() : nullptr)]; return true; } bool WindowOSX::isTransparent() const { - return (m_nsWindow.opaque ? false: true); + return (m_nsWindow.opaque ? false : true); } void* WindowOSX::nativeHandle() const diff --git a/os/osx/window_delegate.h b/os/osx/window_delegate.h index 9d05cfee4..fde25a460 100644 --- a/os/osx/window_delegate.h +++ b/os/osx/window_delegate.h @@ -6,7 +6,7 @@ // Read LICENSE.txt for more information. namespace os { - class WindowOSX; +class WindowOSX; } @interface WindowOSXDelegate : NSObject { @@ -97,8 +97,7 @@ namespace os { m_impl->onEndResizing(); } -- (NSRect)windowWillUseStandardFrame:(NSWindow*)window - defaultFrame:(NSRect)newFrame +- (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)newFrame { // In "newFrame" is the frame size when a window is maximized in the // current screen. We can cache this value to know when we are @@ -107,8 +106,7 @@ namespace os { return newFrame; } -- (BOOL)windowShouldZoom:(NSWindow*)window - toFrame:(NSRect)newFrame +- (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { if (m_impl) { if (NSEqualRects(newFrame, m_maximizedFrame)) @@ -117,7 +115,7 @@ namespace os { return YES; } -- (BOOL)windowShouldBecomeKey:(NSWindow *)sender +- (BOOL)windowShouldBecomeKey:(NSWindow*)sender { NSWindow* modalWindow = [NSApp modalWindow]; return !modalWindow || modalWindow == sender; diff --git a/os/paint.h b/os/paint.h index c83b9a587..56c7ee4de 100644 --- a/os/paint.h +++ b/os/paint.h @@ -10,66 +10,66 @@ namespace os { - // Same values as SkBlendMode - enum class BlendMode { - Clear, - Src, - Dst, - SrcOver, - DstOver, - SrcIn, - DstIn, - SrcOut, - DstOut, - SrcATop, - DstATop, - Xor, - Plus, - Modulate, - Screen, - LastCoeffMode = Screen, - Overlay, - Darken, - Lighten, - ColorDodge, - ColorBurn, - HardLight, - SoftLight, - Difference, - Exclusion, - Multiply, - LastSeparableMode = Multiply, - Hue, - Saturation, - Color, - Luminosity, - LastMode = Luminosity, - }; - - class PaintBase { - public: - // Same as SkPaint::Style - enum Style { - Fill, - Stroke, - StrokeAndFill, - }; - - // Same as SkCanvas::SrcRectConstraint - enum SrcEdges { - Strict, // Sample only inside bounds, is slower (don't use mipmaps) - Fast, // Sample outside bounds, is faster (use mipmaps) - }; +// Same values as SkBlendMode +enum class BlendMode { + Clear, + Src, + Dst, + SrcOver, + DstOver, + SrcIn, + DstIn, + SrcOut, + DstOut, + SrcATop, + DstATop, + Xor, + Plus, + Modulate, + Screen, + LastCoeffMode = Screen, + Overlay, + Darken, + Lighten, + ColorDodge, + ColorBurn, + HardLight, + SoftLight, + Difference, + Exclusion, + Multiply, + LastSeparableMode = Multiply, + Hue, + Saturation, + Color, + Luminosity, + LastMode = Luminosity, +}; - SrcEdges srcEdges() const { return m_srcEdges; } - void srcEdges(const SrcEdges srcEdges) { m_srcEdges = srcEdges; } +class PaintBase { +public: + // Same as SkPaint::Style + enum Style { + Fill, + Stroke, + StrokeAndFill, + }; - private: - SrcEdges m_srcEdges = SrcEdges::Strict; + // Same as SkCanvas::SrcRectConstraint + enum SrcEdges { + Strict, // Sample only inside bounds, is slower (don't use mipmaps) + Fast, // Sample outside bounds, is faster (use mipmaps) }; + SrcEdges srcEdges() const { return m_srcEdges; } + void srcEdges(const SrcEdges srcEdges) { m_srcEdges = srcEdges; } + +private: + SrcEdges m_srcEdges = SrcEdges::Strict; }; +}; // namespace os + #if LAF_SKIA #include "os/skia/paint.h" #else diff --git a/os/pointer_type.h b/os/pointer_type.h index db5cd9d66..0b1be8090 100644 --- a/os/pointer_type.h +++ b/os/pointer_type.h @@ -10,16 +10,16 @@ namespace os { - // Source of a mouse like event - enum class PointerType { - Unknown, - Mouse, // A regular mouse - Touchpad, // Touchpad/trackpad - Touch, // Touch screen - Pen, // Stylus pen - Cursor, // Puck like device - Eraser // Eraser end of a stylus pen - }; +// Source of a mouse like event +enum class PointerType { + Unknown, + Mouse, // A regular mouse + Touchpad, // Touchpad/trackpad + Touch, // Touch screen + Pen, // Stylus pen + Cursor, // Puck like device + Eraser // Eraser end of a stylus pen +}; } // namespace os diff --git a/os/ref.h b/os/ref.h index 51a13b01d..f8f403cea 100644 --- a/os/ref.h +++ b/os/ref.h @@ -12,18 +12,18 @@ namespace os { - template - using RefCountT = base::RefCountT; - using RefCount = base::RefCount; - - template - using Ref = base::Ref; - - template - Ref make_ref(Args&&...args) { - return base::make_ref(std::forward(args)...); - } +template +using RefCountT = base::RefCountT; +using RefCount = base::RefCount; + +template +using Ref = base::Ref; + +template +Ref make_ref(Args&&... args) +{ + return base::make_ref(std::forward(args)...); +} } // namespace os diff --git a/os/sampling.h b/os/sampling.h index 6c7930c62..6b3371cbe 100644 --- a/os/sampling.h +++ b/os/sampling.h @@ -13,30 +13,28 @@ namespace os { - // Same as SkSamplingOptions struct - struct Sampling { - enum class Filter { Nearest, Linear }; - enum class Mipmap { None, Nearest, Linear }; - struct Cubic { - float B, C; - static constexpr Cubic Mitchell() { return { 1/3.0f, 1/3.0f }; } - static constexpr Cubic CatmullRom() { return { 0.0f, 1/2.0f }; } - }; - - bool useCubic = false; - Cubic cubic = { 0, 0 }; - Filter filter = Filter::Nearest; - Mipmap mipmap = Mipmap::None; - - Sampling() = default; - Sampling(const Sampling&) = default; - Sampling& operator=(const Sampling&) = default; - Sampling(Filter f, Mipmap m = Mipmap::None) - : filter(f), mipmap(m) { } - Sampling(Cubic c) - : useCubic(true), cubic(c) { } +// Same as SkSamplingOptions struct +struct Sampling { + enum class Filter { Nearest, Linear }; + enum class Mipmap { None, Nearest, Linear }; + struct Cubic { + float B, C; + static constexpr Cubic Mitchell() { return { 1 / 3.0f, 1 / 3.0f }; } + static constexpr Cubic CatmullRom() { return { 0.0f, 1 / 2.0f }; } }; + bool useCubic = false; + Cubic cubic = { 0, 0 }; + Filter filter = Filter::Nearest; + Mipmap mipmap = Mipmap::None; + + Sampling() = default; + Sampling(const Sampling&) = default; + Sampling& operator=(const Sampling&) = default; + Sampling(Filter f, Mipmap m = Mipmap::None) : filter(f), mipmap(m) {} + Sampling(Cubic c) : useCubic(true), cubic(c) {} +}; + } // namespace os #pragma pop_macro("None") diff --git a/os/screen.h b/os/screen.h index 1dbb2e481..aa97a7c08 100644 --- a/os/screen.h +++ b/os/screen.h @@ -15,32 +15,32 @@ namespace os { - class Screen; - using ScreenRef = Ref; - using ScreenList = std::vector; +class Screen; +using ScreenRef = Ref; +using ScreenList = std::vector; - // A display or window to show graphics. - class Screen : public RefCount { - public: - virtual ~Screen() { } +// A display or window to show graphics. +class Screen : public RefCount { +public: + virtual ~Screen() {} - // Returns true if it's the main screen. - virtual bool isMainScreen() const = 0; + // Returns true if it's the main screen. + virtual bool isMainScreen() const = 0; - // Returns the size of the whole screen. - virtual gfx::Rect bounds() const = 0; + // Returns the size of the whole screen. + virtual gfx::Rect bounds() const = 0; - // Returns the area of the screen without the task bar, i.e. the - // desktop area, the maximum area of a window when it's maximized - // (but not in full screen). - virtual gfx::Rect workarea() const = 0; + // Returns the area of the screen without the task bar, i.e. the + // desktop area, the maximum area of a window when it's maximized + // (but not in full screen). + virtual gfx::Rect workarea() const = 0; - // Returns the color space of this screen. - virtual os::ColorSpaceRef colorSpace() const = 0; + // Returns the color space of this screen. + virtual os::ColorSpaceRef colorSpace() const = 0; - // Returns the HMONITOR (Windows), NSScreen* (macOS), or screen number (X11). - virtual void* nativeHandle() const = 0; - }; + // Returns the HMONITOR (Windows), NSScreen* (macOS), or screen number (X11). + virtual void* nativeHandle() const = 0; +}; } // namespace os diff --git a/os/shortcut.h b/os/shortcut.h index 70836e93e..80deb1a9c 100644 --- a/os/shortcut.h +++ b/os/shortcut.h @@ -12,23 +12,23 @@ namespace os { - class Shortcut { - public: - Shortcut(int unicode = 0, - KeyModifiers modifiers = kKeyNoneModifier) - : m_unicode(unicode) - , m_modifiers(modifiers) { - } - - int unicode() const { return m_unicode; } - KeyModifiers modifiers() const { return m_modifiers; } - - bool isEmpty() const { return m_unicode == 0; } - - private: - int m_unicode; - KeyModifiers m_modifiers; - }; +class Shortcut { +public: + Shortcut(int unicode = 0, KeyModifiers modifiers = kKeyNoneModifier) + : m_unicode(unicode) + , m_modifiers(modifiers) + { + } + + int unicode() const { return m_unicode; } + KeyModifiers modifiers() const { return m_modifiers; } + + bool isEmpty() const { return m_unicode == 0; } + +private: + int m_unicode; + KeyModifiers m_modifiers; +}; } // namespace os diff --git a/os/skia/os.cpp b/os/skia/os.cpp index 7a2f861ce..db01e9081 100644 --- a/os/skia/os.cpp +++ b/os/skia/os.cpp @@ -6,14 +6,15 @@ // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H -#include "config.h" + #include "config.h" #endif #include "os/skia/skia_system.h" namespace os { -System* make_system_impl() { +System* make_system_impl() +{ return new SkiaSystem; } diff --git a/os/skia/paint.h b/os/skia/paint.h index c47e1204a..7c55cf858 100644 --- a/os/skia/paint.h +++ b/os/skia/paint.h @@ -14,63 +14,56 @@ namespace os { - // SkPaint wrapper, information how to paint a shape/primitive in a - // canvas (stroke, fill or both; stroke width; color, etc.). - class Paint : public PaintBase { - public: - bool antialias() const { return m_skPaint.isAntiAlias(); } - void antialias(const bool state) { - m_skPaint.setAntiAlias(state); - } +// SkPaint wrapper, information how to paint a shape/primitive in a +// canvas (stroke, fill or both; stroke width; color, etc.). +class Paint : public PaintBase { +public: + bool antialias() const { return m_skPaint.isAntiAlias(); } + void antialias(const bool state) { m_skPaint.setAntiAlias(state); } - Style style() const { - return static_cast